Docker in ProductionLesson 5.1
Docker container security best practices
non-root user, USER instruction, read-only filesystem, --read-only flag, capability dropping, seccomp, no-new-privileges, image scanning
Running Containers as a Non-Root User
By default, container processes run as root. If an attacker exploits your app, they get root inside the container — which may translate to host access. Always create and use a non-root user.
Adding a Non-Root User in a Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
# Create a system user and group
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Switch to non-root user
USER appuser
CMD ["node", "server.js"]
Additional Hardening Flags
# Run with read-only root filesystem
docker run --read-only -d my-app
# Drop all Linux capabilities, add only what's needed
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE -d my-app
# Prevent container from gaining new privileges
docker run --security-opt=no-new-privileges:true -d my-app
Scan Images for Vulnerabilities
docker scout cves my-app:latest
# Or use Trivy (open source)
trivy image my-app:latest
Use alpine or slim base images to minimize attack surface — fewer packages means fewer CVEs. Rebuild images regularly to pick up OS-level security patches.
