🔒 Docker Security Best Practices
Containers have security risks. Docker security protects your apps. Minimal images, least privilege, secure configuration.
📝 Image Security
# Use official images
FROM node:18-alpine # Official, minimal
FROM postgres:15 # Official, trusted
# Use specific versions (not latest)
FROM python:3.11-slim
FROM nginx:1.25
# Scan for vulnerabilities
docker scan nginx:latest
docker scan --json myimage:latest
trivy image myapp:latest
# Minimize image layers
RUN apt-get update && apt-get install -y \
package1 \
package2 \
&& rm -rf /var/lib/apt/lists/*
# Use multi-stage builds
FROM node:18 AS builder
# Build stage
FROM nginx:alpine
# Runtime stage (smaller)
# Copy only what's needed
COPY --from=builder /app/dist /usr/share/nginx/html
# Use .dockerignore
# .dockerignore
node_modules
.git
.env
*.log
🎯 Runtime Security
# Run as non-root user
FROM node:18-alpine
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
USER nodejs
# Drop capabilities
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE myapp
# Use seccomp profiles
docker run --security-opt seccomp=./seccomp.json myapp
# Use AppArmor
docker run --security-opt apparmor=myapp-profile myapp
# Read-only root filesystem
docker run --read-only myapp
# No new privileges
docker run --security-opt no-new-privileges myapp
# Docker Compose
version: '3.8'
services:
app:
image: myapp:latest
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE
read_only: true
user: "1001:1001"
✅ Security Checklist
- ✓ Use official, minimal images
- ✓ Scan for vulnerabilities
- ✓ Run as non-root user
- ✓ Drop unnecessary capabilities
- ✓ Use read-only filesystem
- ✓ Secure network configuration
“Docker security is critical. Minimize risks, protect data. Essential for production containers.”
