Docker Best Practices
Build secure, optimized, and production-ready Docker images and containers.1. Security Best Practices
Don’t Run as Root
By default, Docker containers run as root. This is a security risk. Fix: Create a non-root user in your Dockerfile.Keep Images Minimal
Smaller images have a smaller attack surface.- Use Alpine or Distroless images.
- Remove build tools (compilers) after use (Multi-stage builds).
Scan for Vulnerabilities
Use tools likedocker scan (powered by Snyk) or Trivy.
2. Optimization & Performance
Leverage Build Cache
Order instructions from least changed to most changed.- Install OS dependencies.
- Copy dependency manifests (
package.json,go.mod). - Install language dependencies.
- Copy source code.
Use .dockerignore
Prevent unnecessary files from being sent to the Docker daemon.
node_modules(install fresh in image).git(metadata not needed)secrets.txt(never bake secrets into image!)
Multi-Stage Builds
Separate build environment from runtime environment.3. Operational Best Practices
Healthchecks
Define how Docker checks if your container is healthy (not just running).Logging
Log tostdout and stderr. Do not log to files inside the container.
- Docker captures
stdoutautomatically (docker logs). - Log drivers (Fluentd, Splunk) can ship these logs to a central system.
Graceful Shutdown
HandleSIGTERM signals in your application to shut down cleanly (close DB connections, finish requests).
- Docker sends
SIGTERM, waits 10s (default), then sendsSIGKILL.
4. The “Golden Rules”
One Process Per Container
Don’t run a database and a web server in the same container. Use Compose.
Immutable Infrastructure
Never SSH into a container to patch it. Rebuild the image and redeploy.
Statelessness
Containers should be ephemeral. Store state in Volumes or external DBs.
Environment Config
Use Environment Variables for config, not hardcoded files.
🎉 Congratulations! You’ve completed the Docker Crash Course. Next: RabbitMQ Crash Course →