4 Hours

15. Docker Security Best Practices

Security

Hardening Containers for Production

Containers share the host kernel. A vulnerability in your container can potentially compromise the host and all other containers. This module covers defense in depth: from Dockerfile practices to runtime security configurations.

Security Checklist: The Bare Minimum

Before any container hits production, verify these security controls are in place. Run as non-root (using `USER` in Dockerfile). Use specific image tags, not `latest` — you need to know exactly which version is running. Keep base images updated — regularly rebuild images to include security patches. Scan images for vulnerabilities with `docker scout` (built-in) or Trivy/Snyk. Drop unnecessary Linux capabilities with `--cap-drop=ALL --cap-add=NET_BIND_SERVICE` (add back only what you need). Set resource limits to prevent DoS from a single container. Use read-only root filesystem with `--read-only` when possible. Never store secrets in environment variables — use Docker Secrets or external secret management.

Bash
# Vulnerability scanning
docker scout quickview nginx:latest
docker scout cves nginx:latest --format table

# Run with dropped capabilities (container has almost no privileges)
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx

# Run with read-only root filesystem
docker run --read-only --tmpfs /tmp nginx

# Run with seccomp profile (system call filtering)
docker run --security-opt seccomp=/path/to/profile.json nginx

# In Docker Compose
services:
  app:
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    read_only: true
    tmpfs: /tmp

Image Trust and Supply Chain Security

How do you know the image you pulled is actually the one your team built? Image signing (Docker Content Trust, Notary, Cosign) ensures image integrity and publisher authenticity. Docker Content Trust (DCT) signs images with a key and verifies the signature when pulling. Enable DCT with `export DOCKER_CONTENT_TRUST=1`. For production, use a private registry with vulnerability scanning enabled (Docker Hub, AWS ECR, Google GAR, Azure ACR). Generate Software Bill of Materials (SBOM) for your images to understand what components are inside.

Bash
# Enable Docker Content Trust
export DOCKER_CONTENT_TRUST=1

# Push signs the image
docker push myregistry/myapp:latest

# Pull verifies the signature
docker pull myregistry/myapp:latest  # Fails if signature invalid

# Generate SBOM (Software Bill of Materials)
docker sbom nginx:latest
docker sbom --format spdx-json nginx:latest > sbom.json

# Scan for vulnerabilities with Trivy (more detailed than docker scout)
trivy image --severity CRITICAL nginx:latest

Knowledge Check

Ready to test your understanding of 15. Docker Security Best Practices?

Back