Docker Security Practices
This chapter covers Docker container security best practices for building and running secure containerized applications.
Image Security
Use Official Images
dockerfile
# ✅ Use official images
FROM node:20-alpine
# ❌ Avoid unknown sources
FROM random-user/node-customPin Image Versions
dockerfile
# ✅ Use specific version tags
FROM node:20.11.1-alpine3.19
# ⚠️ Avoid latest (may introduce unknown changes)
FROM node:latestScan for Vulnerabilities
bash
docker scout cves myimage:latest
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
aquasec/trivy image myimage:latestMinimize Images
dockerfile
FROM golang:1.22 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o main .
FROM scratch
COPY --from=builder /app/main /main
CMD ["/main"]Container Runtime Security
Use Non-Root Users
dockerfile
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
CMD ["node", "server.js"]Read-Only Filesystem
bash
docker run --read-only --tmpfs /tmp --tmpfs /var/run myapp:latestLimit Capabilities
bash
docker run --cap-drop ALL myapp:latest
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE myapp:latest
docker run --security-opt no-new-privileges myapp:latestResource Limits
bash
docker run -m 256m --cpus 0.5 myapp:latest
docker run --pids-limit 100 myapp:latestNetwork Security
Network Isolation
bash
docker network create --internal backend-net
docker network create frontend-net
docker run -d --name db --network backend-net postgres:16
docker run -d --name app --network frontend-net myapp
docker network connect backend-net appSecrets Management
Environment Variable Security
bash
# ❌ Don't hardcode secrets in Dockerfile
ENV DB_PASSWORD=secret123
# ✅ Pass at runtime
docker run -e DB_PASSWORD=secret123 myapp
# ✅ Use .env file
docker run --env-file .env myapp.dockerignore
.env
.env.*
*.key
*.pem
secrets/
.gitSecurity Checklist
| Check | Description |
|---|---|
| ✅ Use official base images | Ensure trusted image sources |
| ✅ Pin version tags | Avoid unexpected changes |
| ✅ Use non-root user | Reduce container escape risk |
| ✅ Multi-stage builds | Reduce attack surface |
| ✅ No secrets in images | Keep passwords/keys out of images |
| ✅ Minimize packages | Only install necessary dependencies |
| ✅ Use COPY not ADD | ADD has implicit behaviors |
| ✅ Set HEALTHCHECK | Monitor container health |
Chapter Summary
Docker security requires a multi-layered approach covering image building, container runtime, networking, and secrets management. Follow the principle of least privilege and regularly scan for vulnerabilities.