Learn Docker · 12/12

Production Readiness & What's Next

8 min read

Production Readiness & What's Next 🏭

Congratulations! You have successfully learned how to containerize applications, write Dockerfiles, and spin up environments using Docker Compose. However, getting an application to run on your personal laptop is completely different from serving thousands of users on the public internet.

In this module, we are leaving the comfort of our development environment and entering Production. We will cover how to secure and shrink your images, keep your containers running smoothly, and figure out what to do when plain Docker is no longer enough.


1. Preparing Docker Applications for Production Environments

Definition

Production readiness in Docker refers to configuring your Docker images and containers so they are secure, lightweight, and predictably stable for live user traffic.

The Problem

When you develop an application, you want all the tools available: compilers, hot-reloading libraries, debugging utilities, and unrestricted permissions to read and write files. If you deploy this exact same "developer" container to a live server, you introduce massive problems:

  • Security Vulnerabilities: Running your app as the root user means if a hacker breaches your app, they own the entire container.
  • Bloated Sizes: Shipping a 2GB image with debugging tools wastes server storage, increases server costs, and takes forever to download and restart during deployments.
  • Unpredictability: Using image tags like node:latest means "latest" could be version 18 today and version 20 tomorrow. Your app might randomly break on the next deployment.

The Solution

Industry standards dictate three main practices to solve these issues: Multi-stage builds, the Principle of Least Privilege (non-root users), and deterministic image tagging.

A. Multi-Stage Builds

Multi-stage builds are a method of creating Docker images where you use multiple FROM statements in a single Dockerfile. Each FROM instruction begins a new phase of the build, and you can selectively copy artifacts from one phase to the next.

Imagine you are a car manufacturer. You need a massive factory with robots, welding machines, and hundreds of workers to build a car. But when you deliver the car to the customer, you don't ship the entire factory—you just ship the finished car. Multi-stage builds work the exact same way. You use a "factory" image to compile your code, and then copy only the finished code into a tiny, clean "production" image.

Example: A Production-Ready Dockerfile

dockerfile
# ---------------------------------------
# STAGE 1: The "Factory" (Build stage)
# ---------------------------------------
# We use a specific version tag, not 'latest'
FROM node:18.17.0-alpine AS builder

WORKDIR /app
# Copy package files and install ALL dependencies (including dev tools)
COPY package*.json ./
RUN npm install

# Copy source code and build the project
COPY . .
RUN npm run build

# ---------------------------------------
# STAGE 2: The "Showroom" (Production stage)
# ---------------------------------------
FROM node:18.17.0-alpine

WORKDIR /app

# Only copy the production dependencies and the compiled build from Stage 1
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist

# Drop root privileges for security
# The 'node' user is built into the official Node image
USER node

# Start the application
CMD ["npm", "start"]

B. The .dockerignore file

Just like .gitignore, you should always include a .dockerignore file in your root directory. This prevents your local node_modules, .env files with secret passwords, and .git history from being accidentally copied into the image.

text
# .dockerignore
node_modules
npm-debug.log
Dockerfile
.dockerignore
.git
.env

2. Managing Container Logs and Monitoring Health Checks

Definition

Container logs are the standard output (stdout) and standard error (stderr) streams written by the application running inside the container. Health checks are instructions that tell Docker how to test the container to verify that the application inside is actually functioning.

The Problem

Problem 1: The Silent Disk Killer (Logs)
By default, Docker captures all logs from your containers and saves them in a JSON file on the host machine. If you leave a heavily used application running for six months, that JSON file will grow to hundreds of gigabytes. Your server disk will fill up, your server will crash, and you will cry.

Problem 2: The Zombie Container (Health)
If your Node.js app connects to a database, but the database goes down, your Node.js app might freeze. The Docker container itself is still "Running" (the process hasn't exited), but the application is effectively dead. If a load balancer is sending users to this container, they will just see endless loading screens.

The Solution

A. Log Rotation

You must configure Docker to limit how large log files can get before they are rotated (archived and eventually deleted). You can do this globally in the Docker daemon, or per service in docker-compose.yml.

Industry Standard Compose Implementation:

yaml
services:
  web-app:
    image: my-web-app:1.0.0
    ports:
      - "8080:8080"
    logging:
      driver: "json-file"
      options:
        max-size: "10m" # Keep max 10 Megabytes per file
        max-file: "3"   # Keep only 3 files total before deleting the oldest

B. Docker HEALTHCHECK

A health check is Docker's way of asking your app, "Hey, are you actually okay in there?"

Imagine a restaurant with an "Open" sign on the front door. Just because the building is physically standing (the container is running) doesn't mean the kitchen isn't on fire (the app is broken). A health check is like sending a manager into the kitchen every 30 seconds to make sure food is actually being cooked.

You add the HEALTHCHECK instruction to your Dockerfile. It runs a command inside the container; if the command succeeds (returns exit code 0), the container is marked as healthy. If it fails, it becomes unhealthy.

dockerfile
# ... (rest of Dockerfile)

# Ping the local web server every 30s. If it fails 3 times, mark as unhealthy.
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget --quiet --tries=1 --spider http://localhost:8080/api/health || exit 1

CMD ["npm", "start"]

3. The Limits of Plain Docker: When to Use Orchestration

Definition

Container orchestration is the automated configuration, management, and coordination of multiple containers across multiple physical machines.

The Problem

Plain Docker (docker run) and Docker Compose (docker-compose up) are fantastic for single machines. However, they are bound to Single Points of Failure.

What happens if the physical server hosting your Docker Compose application loses power? The containers die, and your application goes completely offline. What if you are running a massive Black Friday sale and one container isn't enough to handle the 100,000 incoming requests? You can't easily spread Docker Compose across 10 different servers to share the load.

The Solution: Orchestration

You have outgrown plain Docker when you need:

  1. High Availability: Your app cannot go down, even if an entire physical server catches fire.
  2. Scaling: You need to instantly duplicate your container from 1 copy to 50 copies across multiple servers based on CPU usage.
  3. Self-Healing: If a container becomes unhealthy (remember our Healthchecks?), you need a system that automatically kills it and starts a fresh one without you waking up at 3:00 AM to do it manually.

If you hit these limits, you do not write complex bash scripts to manage your servers. You move to an Orchestrator.


4. Your Next Steps: Introduction to Container Orchestration (Kubernetes)

Definition

Kubernetes (often abbreviated as K8s) is an open-source container orchestration system for automating software deployment, scaling, and management. Originally designed by Google, it is now the undisputed industry standard for running containers in large-scale production.

How it Works (The Big Picture)

Kubernetes clusters machines together. You no longer care which server your container runs on. You simply hand Kubernetes a configuration file that says: "I want 5 copies of my web app running, and they need to be accessible via this domain name."

Imagine Kubernetes as the incredibly efficient general manager of a massive factory floor.

  • If a worker (a container) gets sick and collapses, the manager instantly spots it, drags them off the floor, and assigns a brand new worker to the station (Self-healing).
  • If a massive shipment of raw materials arrives and the current workers can't keep up, the manager instantly hires 10 new workers to help out, and fires them when the rush is over (Auto-scaling).
  • The manager stands at the front door and directs incoming trucks (web traffic) evenly to the least busy workers so no one gets overwhelmed (Load Balancing).

Brief Overview of Kubernetes Concepts (Minimal Scope)

To get you prepared for your next journey, here are the three primary vocabulary words you will learn in Kubernetes:

  • Pod: The smallest unit in Kubernetes. Kubernetes doesn't run containers directly; it wraps your container in a "Pod".
  • Deployment: A blueprint that tells Kubernetes how many identical Pods you want running. If you want 3 replicas of your app, you create a Deployment.
  • Service: Because Pods die and are recreated constantly, their IP addresses constantly change. A Service acts as a static phone number (Load balancer) that routes traffic to your Pods, no matter how many times they have died and respawned.

What's next?
Docker is the standard way to build and package your application. Kubernetes is the standard way to run those packages at a massive scale. Mastering Docker was your crucial first step; now you have the foundation needed to conquer container orchestration!


📚 References & Extra Reading

To deepen your knowledge on these production concepts, review the official documentation:

Challenge

You are tasked with creating a production-ready configuration for a Node.js web application. Your goal is to apply best practices for security, image size, and operational stability by creating two files in the editor below: a Dockerfile and a docker-compose.yml.

Dockerfile Requirements:

  1. Multi-Stage Build:
    • Use a multi-stage build. The first stage must be aliased as builder and use the specific base image node:18.17.0-alpine.
    • The builder stage should set its working directory, copy package*.json files, run npm install, and finally copy the application source.
  2. Production Stage:
    • The final production stage must also use the node:18.17.0-alpine base image.
    • Create a non-root user named nodeuser. The application must run as this user.
    • Copy only the necessary production artifacts (e.g., node_modules, package.json, source code) from the builder stage.
    • Expose port 3000.
  3. Health Check:
    • Add a HEALTHCHECK instruction. It should run every 30 seconds and use curl to check a health endpoint at http://localhost:3000. The container should be considered unhealthy if the command fails.
  4. Startup Command: Set the container's startup command to run the application using node server.js.

docker-compose.yml Requirements:

  1. Service Definition: Define a service named webapp using version 3.8 of the compose file format.
  2. Build: The service must be built from the Dockerfile in the current directory.
  3. Port Mapping: Map port 8080 on the host to the exposed port 3000 in the container.
  4. Log Rotation: Configure the default logging driver to implement log rotation. Set the maximum size of a log file to 10m and keep a maximum of 3 files.

Expected result

Your solution should consist of two complete configuration files provided in a single response, separated by the file markers.

Dockerfile

A valid Dockerfile that implements a multi-stage build.

  • It starts with FROM node:18.17.0-alpine AS builder.
  • The builder stage contains WORKDIR, COPY, and RUN npm install commands.
  • A second FROM node:18.17.0-alpine instruction starts the production stage.
  • This stage includes a command like RUN addgroup -S nodeuser && adduser -S nodeuser -G nodeuser to create a non-root user.
  • It uses COPY --from=builder ... to copy artifacts from the previous stage.
  • It includes a USER nodeuser instruction.
  • It has EXPOSE 3000.
  • It contains a HEALTHCHECK instruction, for example: HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:3000 || exit 1.
  • The file ends with a CMD ["node", "server.js"].

docker-compose.yml

A valid docker-compose.yml file.

  • It starts with version: '3.8'.
  • It defines a services block containing one service named webapp.
  • The webapp service has a build: . key.
  • It includes a ports section mapping - "8080:3000".
  • It has a logging section with a driver, and options for max-size: "10m" and max-file: "3".
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.