Docker Security Best Practices
Running containers securely requires deliberate configuration. These practices reduce your attack surface.
1. Don't Run Containers as Root
Add a USER directive in your Dockerfile:
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
USER appuser
2. Use Specific Image Tags
# Bad (can change without warning):
FROM ubuntu:latest
# Good (reproducible, auditable):
FROM ubuntu:22.04
3. Scan Images for Vulnerabilities
# Using Docker Scout (built into Docker Desktop and CLI):
docker scout cves myapp:1.0
# Using Trivy (open-source):
apt install trivy -y
trivy image nginx:latest
4. Use Read-Only File Systems
docker run --read-only -v /tmp:/tmp nginx
5. Limit Resource Usage
docker run --memory="512m" --cpus="1.0" nginx
6. Never Expose the Docker Socket to Containers
Mounting /var/run/docker.sock into a container gives that container root-level access to the host. Only do this for trusted tools like Portainer, and understand the risk.
7. Use Secrets for Sensitive Values
Avoid hardcoding passwords in environment variables or Dockerfiles. Use Docker Secrets (Swarm) or mount a secrets file:
docker secret create db_password ./password.txt
8. Keep Docker and Images Updated
apt upgrade docker-ce -y
docker pull myapp:latest && docker compose up -d
9. Drop Capabilities
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx