Docker makes deployment easier, but production-grade containers require more than docker run. These practices keep containers secure, debuggable, and reliable under load.
Keep images small
Smaller images deploy faster, use less disk, and have fewer security vulnerabilities. Start with minimal base images like Alpine Linux or distroless images.
Use multi-stage builds to separate build tools from runtime. Your final image should contain only the compiled binary and its runtime dependencies:
# Build stage
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o service
# Runtime stage
FROM alpine:3.19
COPY --from=builder /app/service /service
ENTRYPOINT ["/service"]
This pattern keeps build tools like compilers and package managers out of production images.
Optimize layer caching
Docker caches each layer. Order instructions from least to most frequently changing. Copy dependency manifests before application code so dependency installation layers are cached:
COPY package.json package-lock.json ./
RUN npm ci --only=production
COPY . .
This means code changes do not invalidate the dependency layer, speeding up builds significantly.
Run as non-root user
Never run containers as root in production. Create a dedicated user with minimal privileges:
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
This limits the blast radius if the container is compromised. Many base images now include a non-root user by default.
Implement health checks
Define a HEALTHCHECK instruction so orchestrators know when your app is ready and when it fails:
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
CMD curl -f http://localhost:8080/health || exit 1
Health checks should test actual application logic, not just that the process is running. Check database connectivity, critical dependencies, and internal state.
Set resource limits
Always set CPU and memory limits. Runaway containers should not starve other workloads:
docker run --memory=512m --cpus=1.0 myapp
In Kubernetes, define requests and limits in pod specs. Start conservative and adjust based on actual usage patterns.
Logging to stdout/stderr
Write logs to stdout and stderr, not to files inside the container. Container runtimes and log aggregators expect this pattern.
If your app writes log files, reconfigure it or symlink log paths to stdout:
RUN ln -sf /dev/stdout /var/log/nginx/access.log && \
ln -sf /dev/stderr /var/log/nginx/error.log
Secrets management
Never bake secrets into images. Use environment variables, mounted volumes, or secret management systems like Kubernetes Secrets or HashiCorp Vault.
For Docker Compose, use secrets instead of environment variables. For Kubernetes, mount secrets as files or environment variables from SecretKeyRef.
If a secret appears in a Dockerfile or is committed to an image layer, consider it compromised.
Security scanning
Scan images for vulnerabilities before deploying. Tools like Trivy, Snyk, or Docker Scout identify known CVEs in base images and dependencies.
Automate scanning in CI pipelines and fail builds on high-severity findings. Update base images regularly to patch vulnerabilities.
Use specific image tags
Never use :latest in production. Tag images with commit SHAs, semantic versions, or build numbers:
docker pull myapp:v1.2.3
docker pull myapp:abc123f
Specific tags make rollbacks predictable and deployments reproducible. :latest changes over time and breaks both.
Networking and ports
Expose only necessary ports. Use bridge networks or overlay networks to isolate containers. Avoid --net=host unless absolutely required — it bypasses Docker's network isolation.
Document exposed ports with EXPOSE instructions, even though they are advisory. They serve as documentation and are used by orchestration tools.
Graceful shutdown
Handle SIGTERM signals to shut down gracefully. Docker sends SIGTERM before SIGKILL, giving your app 10 seconds (default) to clean up.
Finish in-flight requests, close database connections, and flush buffers before exiting. Use a PID 1 init system like tini if your app does not handle signals properly:
ENTRYPOINT ["/sbin/tini", "--", "/app/start.sh"]
Build-time arguments
Use ARG for build-time configuration and ENV for runtime variables. ARG values are not persisted in the final image:
ARG BUILD_ENV=production
RUN if [ "$BUILD_ENV" = "production" ]; then npm prune --production; fi
ENV values become part of the image and can be overridden at runtime with docker run -e or Kubernetes env specs.
Container monitoring
Collect metrics on CPU, memory, disk I/O, and network usage. Use Prometheus exporters, cAdvisor, or cloud-native monitoring solutions.
Monitor container restart rates. Frequent restarts indicate crashes, OOM kills, or health check failures that need investigation.
Key takeaways
- Use multi-stage builds to keep final images minimal.
- Run containers as non-root users with limited permissions.
- Define health checks that test actual application readiness.
- Set CPU and memory limits to prevent resource contention.
- Log to stdout/stderr for aggregation and monitoring.
- Never bake secrets into images; use environment variables or secret managers.
- Scan images for vulnerabilities and update base images regularly.
- Use specific image tags instead of
:latestin production. - Handle SIGTERM for graceful shutdown.