2.5 Hours

8. Building for Production: Security and Reliability

Production

Making Containers Production-Ready

A Dockerfile that works on your laptop is not necessarily production-ready. Production containers need proper signal handling, health checks, resource limits, and security hardening. This module covers everything required to run containers in production.

Signal Handling: Why PID 1 Matters

When you run `docker stop`, Docker sends SIGTERM to PID 1 inside the container. Your application must handle this signal to shut down gracefully — closing database connections, finishing in-flight requests, and saving state. The problem is that many applications do not handle signals properly when they are PID 1. In Linux, PID 1 has special behavior: it does not receive default signal handlers. If your application does not explicitly handle SIGTERM, it will ignore it and Docker will have to wait 10 seconds before sending SIGKILL to force-kill the container. This causes slow shutdowns and potential data loss. The solution is to use `tini` (a tiny init process) as PID 1, which properly forwards signals to your application. You can include tini in your Dockerfile or use the `--init` flag at runtime. For Node.js applications, you must also add signal handlers to close your HTTP server gracefully.

Text
# Include tini in the Dockerfile
FROM node:20-alpine
RUN apk add --no-cache tini
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "server.js"]

# Or use the --init flag at runtime (no Dockerfile change needed)
docker run --init myapp

# Node.js graceful shutdown handler
const server = app.listen(3000);
process.on('SIGTERM', () => {
  console.log('SIGTERM received, closing server...');
  server.close(() => {
    console.log('Server closed, exiting');
    process.exit(0);
  });
});

Resource Limits: Preventing Noisy Neighbors

By default, containers have no resource limits — they can consume all available CPU and memory on the host. A single misbehaving container can starve other containers and even crash the host. In production, ALWAYS set memory limits (`--memory`) and CPU limits (`--cpus`). Memory limits are hard limits: if a container tries to use more memory than allowed, the kernel kills it (OOM kill). CPU limits are soft: the container is throttled when exceeding the limit. Set limits slightly above your application's normal usage. Use `--memory-reservation` to set a soft limit that the scheduler uses during contention. Use `--oom-kill-disable` with extreme caution — it can cause host instability.

Bash
# Set memory limit (hard limit, kills container if exceeded)
docker run -d --memory="512m" myapp

# Set CPU limit (50% of one core)
docker run -d --cpus="0.5" myapp

# Set both memory and CPU limits
docker run -d --memory="1g" --cpus="1.5" myapp

# Memory reservation (soft limit for scheduling)
docker run -d --memory="1g" --memory-reservation="768m" myapp

# In Docker Compose
services:
  app:
    deploy:
      resources:
        limits:
          cpus: '0.5'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 256M

Restart Policies: Self-Healing Containers

Containers crash — network timeouts, out-of-memory errors, unhandled exceptions. A restart policy tells Docker what to do when a container exits. The `--restart` flag accepts: `no` (never restart, default), `always` (always restart regardless of exit code), `on-failure[:max-retries]` (restart only if exit code is non-zero), and `unless-stopped` (always restart unless manually stopped). For production services, use `unless-stopped` or `always`. The `on-failure` policy is useful for batch jobs that should not restart on successful completion. Be careful: a container that crashes immediately will enter a restart loop. Docker implements exponential backoff (starting at 100ms, doubling each time) to prevent thrashing.

Bash
# Always restart (unless manually stopped)
docker run -d --restart unless-stopped myapp

# Restart only on failure, max 5 times
docker run -d --restart on-failure:5 myapp

# In Docker Compose (version 3+)
services:
  app:
    restart: unless-stopped

# Check current restart policy
docker inspect --format='{{.HostConfig.RestartPolicy.Name}}' container_name

Knowledge Check

Ready to test your understanding of 8. Building for Production: Security and Reliability?

Back