TL;DR
Learn essential security practices for Docker containers, including image scanning, runtime protection, and secure configuration patterns.
Docker Container Security: A Comprehensive Guide
Executive Summary
Container security is a chain: the base image you start from, the way you build, what you scan before deployment, and how the container is constrained at runtime. A weakness at any link undermines the others. This guide covers each link in order: choosing and scanning images, signing and verifying them, running with least privilege (non-root user, dropped capabilities, read-only filesystem, seccomp), segmenting networks, handling secrets without baking them into images, and monitoring runtime behaviour. By the end you should be able to review a Dockerfile and a Compose or Swarm definition and identify the specific controls that are present, missing, or misconfigured.
Why This Matters
Containers share the host kernel, so a container compromise is closer to the host than most teams assume. The common failure modes are mundane: an image built months ago carrying unpatched libraries, a container running as root with the Docker socket mounted, a database password committed into an image layer where anyone with pull access can extract it, or a flat network where a compromised frontend can reach the database directly. Attackers automate the search for exactly these conditions. The cost of getting this wrong ranges from cryptomining on your hosts to full environment breach, and the controls that prevent it are configuration, not new products.
Core Concepts
Image Security: Start Small, Scan Always, Sign What You Ship
Use official, minimal base images and pin them to specific versions. Every package in the image is a package you must patch, so a slim base is a security control, not just an optimisation. Scan images in CI and fail the pipeline on fixable high and critical findings; also scan images already sitting in your registry, because new CVEs are published against old images constantly. Where the supply chain matters, sign images at build time and verify signatures at deployment so only artifacts your pipeline produced can run.
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Security scan stage
FROM aquasec/trivy:latest AS scanner
COPY --from=builder /app /app
RUN trivy filesystem --severity HIGH,CRITICAL /app
# Production stage
FROM node:18-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/package*.json ./
RUN npm ci --only=production && \
npm cache clean --force
USER appuser
EXPOSE 3000
CMD ["npm", "start"]Multi-stage builds reinforce this: compilers, package managers, and source code stay in the build stage and never reach the runtime image, where they would only serve an attacker.
Runtime Least Privilege
The runtime defaults are permissive. Tighten them explicitly:
no-new-privileges so processes cannot gain privileges via setuid binaries.version: '3.8'
services:
app:
image: myapp:latest
security_opt:
- no-new-privileges:true
- seccomp=default
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE
user: "1000:1000"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3Note that NET_BIND_SERVICE in the example exists only so a non-root process can bind a low port; if your application listens above port 1024, drop it too. Never run production containers with --privileged, and never mount /var/run/docker.sock into a container that does not absolutely require it: socket access is effectively root on the host.
Resource limits belong in this section as well. CPU and memory limits are an availability control: they keep a leaking or compromised process from taking down everything else on the host.
Network Segmentation
Put services on separate networks by trust zone and let each service join only the networks it needs. A frontend that talks to an API does not need a route to the database. Marking a network internal: true removes its route to the outside world entirely.
version: '3.8'
services:
frontend:
networks:
- frontend
api:
networks:
- frontend
- backend
database:
networks:
- backend
networks:
frontend:
driver: bridge
ipam:
config:
- subnet: 172.20.0.0/16
backend:
driver: bridge
internal: true
ipam:
config:
- subnet: 172.21.0.0/16Publish only the ports the outside world must reach, encrypt traffic between services where it crosses hosts, and remember that containers on the same network can always reach each other: segmentation only helps if the boundaries are drawn deliberately.
Secrets Management
A secret baked into an image layer is published to everyone with pull access, and deleting it in a later layer does not remove it from history. Keep secrets out of images and out of plain environment variables where possible. Docker secrets mount values as files under /run/secrets, which keeps them out of the image and out of docker inspect output; external vaults serve the same purpose at larger scale.
version: '3.8'
services:
app:
image: myapp:latest
secrets:
- db_password
- ssl_cert
environment:
- DB_PASSWORD_FILE=/run/secrets/db_password
- SSL_CERT_FILE=/run/secrets/ssl_cert
secrets:
db_password:
external: true
ssl_cert:
file: ./certs/ssl.certMonitoring, Auditing, and Runtime Detection
Scanning covers what you deploy; monitoring covers what happens next. Ship logs centrally with rotation configured so containers cannot fill host disks. Runtime detection tools such as Falco watch syscalls and flag behaviour a healthy container should never exhibit, such as spawning a shell or writing to sensitive paths. Audit against a recognised baseline such as the CIS Docker Benchmark, and re-run it after Docker upgrades and configuration changes, not just once.
Decision Framework
| Situation | Recommendation |
|---|---|
| New service going to production | Minimal pinned base, CI scan gate, non-root user, capabilities dropped, read-only filesystem |
| Scan reports a critical CVE with a fix available | Rebuild on the patched base and redeploy; do not waive it |
| Scan reports a critical CVE with no fix | Document the exception, check exploitability in your configuration, and set a review date |
| Container needs the Docker socket | Refuse by default; if unavoidable, isolate the workload on its own host and audit it heavily |
| Secrets currently in environment variables | Migrate to mounted secret files or a vault integration |
| Multi-tenant or hostile workloads | Containers alone are not the boundary; use separate VMs or hosts per tenant |
Implementation Checklist
cap_drop: ALL is set and each cap_add is individually justifiedno-new-privileges and a seccomp profile are applied--privileged or a mounted Docker socketTrade-offs
Every control here costs some convenience. Read-only filesystems break applications that casually write to their working directory until they are fixed to use proper scratch space. Dropping capabilities surfaces obscure failures in software that assumed root. Scan gates slow releases and generate findings someone must triage, including false positives and vulnerabilities in code paths you never execute. Seccomp profiles can block legitimate syscalls after runtime upgrades. These costs are real but bounded, and they are paid once during setup rather than during an incident.
When Not to Use
Conclusion
Container security is mostly disciplined configuration: small pinned images, enforced scanning, least-privilege runtime settings, segmented networks, and secrets kept out of layers. None of it requires exotic tooling. The teams that get breached through containers are rarely missing a product; they are missing one of these basics on one overlooked service.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.