Docker Security Basics & Hardening
Complete guide to container security, non-root users, Linux capabilities, read-only root filesystems, secret management, and vulnerability scanning.
Containers share the host kernel. Hardening your containers prevents privilege escalation attacks, unauthorized host filesystem access, and data exfiltration.
1. Never Run as Root
By default, containers run as UID 0 (root). If an attacker breaks out of the container boundary, they gain root privileges on the underlying host kernel.
Dockerfile User Hardening
# Create dedicated system group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuserFor official Node images:
USER node2. Drop Unneeded Linux Capabilities
Linux divides root privileges into distinct capabilities (e.g. CAP_NET_RAW, CAP_SYS_ADMIN). Drop all default capabilities and add only what is strictly required:
docker run -d \
--cap-drop=ALL \
--cap-add=NET_BIND_SERVICE \
nginx:alpineIn compose.yaml:
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE3. Read-Only Root Filesystems
Prevent attackers from downloading malware, modifying binary files, or injecting web shells by mounting the container filesystem as read-only:
docker run -d \
--read-only \
--tmpfs /tmp \
--tmpfs /var/run \
my-app-image4. Vulnerability Scanning with Docker Scout / Trivy
Scan images for known Common Vulnerabilities and Exposures (CVEs) before deploying:
# Docker Scout
docker scout quickview myapp:latest
docker scout cves myapp:latest
# Trivy scanner
trivy image myapp:latest5. Secure Secret Management
- NEVER embed tokens, private keys, or credentials in
Dockerfilelayers or image tags. - Use Docker BuildKit
--mount=type=secretduring build time. - Inject secrets at runtime via Docker Secrets, HashiCorp Vault, or cloud secret managers.
Related Guides
Docker Resource Management & Limits
Complete guide to limiting container CPU, memory, swap, and disk I/O using Linux control groups (cgroups v2) to prevent noisy neighbor and OOM kills.
Docker Production Best Practices
Comprehensive checklist for deploying Docker containers into production, covering image size optimization, security, logging, graceful shutdown, and orchestration readiness.