Container Security
Docker security, Kubernetes hardening, image scanning, and runtime protection.
Overview
Container security protects containerized applications.
Docker Security
Secure Dockerfile
# Use non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
USER appuser
# Don't store secrets
ENV API_KEY=""
# Use secrets management instead
# Read-only filesystem
RUN chmod -R 555 /app
Docker Bench Security
# Run security scan
docker run --rm -it \
--net host --pid host --userns host --cap-add audit_control \
-e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
-v /var/lib:/var/lib:ro \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-v /etc:/etc:ro \
docker/docker-bench-security
Kubernetes Security
Pod Security Policy
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
spec:
privileged: false
allowPrivilegeEscalation: false
requiredDropCapabilities:
- ALL
volumes:
- 'configMap'
- 'emptyDir'
- 'projected'
- 'secret'
- 'downwardAPI'
- 'persistentVolumeClaim'
hostNetwork: false
hostIPC: false
hostPID: false
Network Policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Image Scanning
# Trivy scan
trivy image nginx:latest
# Clair scan
clair-scanner --ip 127.0.0.1 nginx:latest
Runtime Protection
# Falco rule
- rule: Detect crypto miners
desc: Detect cryptocurrency mining
condition: >
spawned_process and container and
(proc.name in (xmrig, minerd, cpuminer))
output: >
Crypto miner detected (user=%user.name container=%container.name)
priority: CRITICAL
Security Best Practices
- Minimal images — Use distroless/alpine
- No root — Run as non-root user
- Read-only filesystem — Prevent modifications
- Resource limits — Prevent DoS
- Secrets management — Don't hardcode secrets
Practice
Harden a Kubernetes cluster with security policies.