4 Hours

5. The Dockerfile Complete Reference

Dockerfile

Writing Production-Grade Dockerfiles

The Dockerfile is the blueprint for your containers — every instruction defines a layer, and the order matters. This module covers every Dockerfile instruction with production best practices, examples, and common pitfalls to avoid.

FROM: Choosing the Right Base Image

The `FROM` instruction sets the base image for subsequent instructions. Every valid Dockerfile must start with `FROM` (except in multi-stage builds where later stages can start with `FROM`). Choosing the right base image is the most important decision in your Dockerfile because it determines your image's size, security surface, and compatibility. The `alpine` variants are popular because they are tiny (5-10 MB) and contain only essential packages, but some software may have compatibility issues with musl libc (Alpine's C library). The `-slim` variants are larger (50-200 MB) but use glibc, the standard C library, making them compatible with most pre-compiled binaries. The `latest` tag is dangerous because it changes over time — always pin a specific version tag like `node:20.11.0-alpine`. For absolute minimum size and maximum security, you can use `scratch` — an empty image — but your application must be a statically compiled binary (like Go or Rust) because no operating system files are present. You cannot run `sh` or `bash` in a scratch-based container.

Text
# Good — specific version, Alpine for small size
FROM node:20.11.0-alpine

# Good — slim variant for glibc compatibility
FROM python:3.12.2-slim

# Good — scratch for static binaries (Go example)
FROM scratch
COPY --from=builder /app/server /server
ENTRYPOINT ["/server"]

# Bad — 'latest' tag (reproducible builds? no)
FROM node:latest

# Bad — full Ubuntu for a simple app (700MB+)
FROM ubuntu:22.04

WORKDIR: Setting the Working Directory

The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, `ENTRYPOINT`, `COPY`, or `ADD` instructions that follow. If the directory does not exist, Docker automatically creates it. Always use `WORKDIR` instead of `RUN mkdir -p /some/path && cd /some/path` because `WORKDIR` is cleaner and works across shell restarts. You can use multiple `WORKDIR` instructions — each one is relative to the previous one. For example, `WORKDIR /app` followed by `WORKDIR src` sets the working directory to `/app/src`. Absolute paths are also fine. Setting a `WORKDIR` makes your Dockerfile more readable and maintainable, and it ensures that subsequent commands run in the expected directory even if the user's shell environment differs.

Text
# Good — set WORKDIR early
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .

# Bad — using cd in RUN commands
FROM node:20-alpine
RUN mkdir -p /app && cd /app
# The cd effect does NOT persist to the next RUN instruction!
RUN npm install  # This runs in /, not /app

COPY vs ADD: Which One to Use and When

Both `COPY` and `ADD` copy files from the build context (the directory where you run `docker build`) into the image. `COPY` is straightforward — it copies files and directories exactly as they are. `ADD` has three extra features: it can copy from URLs, it automatically extracts tar files (`.tar`, `.gz`, `.xz`, `.bz2`), and it has special behavior for Git repositories (deprecated). Because of these extra features, `ADD` is considered less predictable. The official Docker documentation recommends using `COPY` unless you specifically need URL fetching or automatic tar extraction. For 99% of use cases, `COPY` is the right choice. The `--chown` flag lets you set ownership during the copy, which is essential when you later switch to a non-root user. Always use `--chown` in the same `COPY` instruction rather than a separate `RUN chown` command, because that would create an extra layer and waste disk space.

Text
# Good — COPY for local files
COPY package.json package-lock.json ./
COPY --chown=node:node . /app

# ADD — only when you need tar extraction
ADD https://example.com/file.tar.gz /tmp/
# This automatically extracts file.tar.gz into /tmp/

# Bad — using ADD for simple file copies (unnecessary overhead)
ADD package.json ./

# Good practice: copy with ownership in one layer
COPY --chown=1000:1000 . /app
# Instead of: COPY . /app && RUN chown -R 1000:1000 /app (creates extra layer)

RUN: Executing Commands During Build

The `RUN` instruction executes commands in a new layer on top of the current image and commits the results. Each `RUN` instruction creates a new layer. To minimize image size, chain commands together using `&&` and clean up temporary files in the same `RUN` instruction. For example, `RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*` ensures the package lists are not persisted in a separate layer. If you split this into `RUN apt-get update`, `RUN apt-get install -y curl`, and `RUN rm -rf /var/lib/apt/lists/*`, the first two layers would still contain the cache files even though the third layer deletes them — because each layer is immutable. The cache files exist in the intermediate layers and contribute to the final image size. For package managers like `apt`, `apk`, `yum`, `pip`, and `npm`, always clean up the cache in the same `RUN` instruction where you installed packages.

Text
# Good — chained commands, cleanup in same layer
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        curl \
        git \
        build-essential \
    && rm -rf /var/lib/apt/lists/*

# Good — Alpine Linux pattern
RUN apk add --no-cache curl git
# --no-cache prevents apk from caching index locally

# Good — Python pattern
RUN pip install --no-cache-dir -r requirements.txt

# Bad — multiple RUN instructions for related operations
RUN apt-get update           # Layer 1: contains package lists
RUN apt-get install -y curl  # Layer 2: still has package lists from layer 1
RUN rm -rf /var/lib/apt/lists/*  # Layer 3: deletes lists but layer 1 and 2 still have them!

ENV and ARG: Environment Variables and Build Arguments

`ENV` sets environment variables that persist in the final image and are available to running containers. `ARG` sets variables only available during the build process — they are not present in the final image. Use `ARG` for version numbers, build timestamps, or credentials that should not be baked into the image. Use `ENV` for application configuration like `NODE_ENV`, `PORT`, or `DATABASE_URL`. `ENV` variables can be overridden at runtime with `docker run -e`. `ARG` variables can be set at build time with `docker build --build-arg VERSION=1.0.0`. Do NOT use `ARG` or `ENV` for secrets like passwords or API keys — build arguments are visible in `docker history`, and environment variables are visible with `docker inspect`. Use Docker secrets or external secret management instead.

Text
# ARG — build-time only, not in final image
ARG NODE_VERSION=20.11.0
FROM node:${NODE_VERSION}-alpine

# ENV — persists in final image
ENV NODE_ENV=production
ENV PORT=3000

# Use build arg for version info (safe to embed)
ARG BUILD_TIMESTAMP
ENV BUILD_TIMESTAMP=$BUILD_TIMESTAMP  # If you want it to persist

# Build command:
# docker build --build-arg BUILD_TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ") -t myapp .

# Runtime override:
# docker run -e PORT=8080 myapp

CMD vs ENTRYPOINT: The Critical Distinction

New Docker users often confuse `CMD` and `ENTRYPOINT`, but the distinction is crucial. `CMD` provides defaults for an executing container that CAN be overridden. `ENTRYPOINT` defines the fixed executable that CANNOT be overridden (without the `--entrypoint` flag). When both are present, the `CMD` becomes arguments to the `ENTRYPOINT`. Use `ENTRYPOINT` when your container should run as a specific executable (like `nginx`, `node`, `python`), and use `CMD` for the default arguments. For most application containers, use the exec form (`[node, app.js]`) rather than the shell form (`node app.js`) because the exec form sends signals directly to your application (SIGTERM, SIGINT). The shell form spawns a shell subprocess (like `/bin/sh -c node app.js`), which does NOT forward signals properly — your application won't receive SIGTERM when `docker stop` is called, causing a 10-second delay before Docker force-kills it.

Text
# Pattern 1: ENTRYPOINT as executable, CMD as args (recommended)
ENTRYPOINT ["node"]
CMD ["app.js"]
# docker run myapp → runs "node app.js"
# docker run myapp server.js → runs "node server.js"

# Pattern 2: Only CMD (default command)
CMD ["node", "app.js"]
# docker run myapp → runs "node app.js"
# docker run myapp npm test → runs "npm test" (overrides CMD completely)

# Pattern 3: Shell form (bad — no signal forwarding)
CMD node app.js  # Actually runs as /bin/sh -c "node app.js"

# Good — always use JSON array syntax for CMD and ENTRYPOINT
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]

USER: Running as Non-Root for Security

By default, containers run as root. This is dangerous — if an attacker compromises your container, they have root access to that container, and depending on your configuration, potentially to the host system. Production containers should NEVER run as root. Create a non-root user early in your Dockerfile and switch to it before the `CMD` or `ENTRYPOINT`. Use `USER` to switch. The user you create should have a known UID (like 1000) so that volume permissions work consistently across environments. For Alpine-based images, use `adduser`; for Debian/Ubuntu-based images, use `useradd`. You need to switch to the non-root user AFTER you have done all operations that require root privileges (installing packages, copying files to system directories, setting permissions).

Text
# Create non-root user (Alpine)
RUN addgroup -g 1001 -S appgroup && \
    adduser -S appuser -u 1001 -G appgroup

# Create non-root user (Debian/Ubuntu)
RUN groupadd -r appgroup -g 1001 && \
    useradd -r -g appgroup -u 1001 -s /sbin/nologin appuser

# Copy files as root (to set ownership)
COPY --chown=appuser:appgroup . /app

# Switch to non-root user for runtime
USER appuser

CMD ["node", "app.js"]

# If you must run a process that needs a privileged port (<1024),
# use Linux capabilities instead of running as root:
# docker run --cap-add=NET_BIND_SERVICE

HEALTHCHECK: Enabling Container Health Monitoring

The `HEALTHCHECK` instruction tells Docker how to test if a container is still working properly. Without a health check, Docker only knows if the container's main process is running — not if the application is actually responding. A web server could be running (process exists) but stuck in an infinite loop, returning 500 errors for every request. Docker wouldn't know. With `HEALTHCHECK`, Docker runs the specified command inside the container at regular intervals. If the command exits with 0, the container is considered healthy. Any non-zero exit code marks the container as unhealthy. The `--interval` sets how often to run the check (default 30s). `--timeout` sets how long to wait for the command to complete (default 30s). `--start-period` gives the container time to initialize before health checks begin — critical for apps that take time to start up. `--retries` sets how many consecutive failures before marking unhealthy. Once marked unhealthy, orchestration tools like Docker Swarm or Kubernetes can restart the container.

Text
# Health check for a web application
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1

# Health check for a database (PostgreSQL example)
HEALTHCHECK --interval=10s --timeout=5s --retries=5 \
  CMD pg_isready -U postgres || exit 1

# Health check for a generic TCP service
HEALTHCHECK --interval=30s --timeout=3s \
  CMD nc -z localhost 5432 || exit 1

# Check health status of running containers
docker ps --format "table {{.Names}}\t{{.Status}}"
# Output includes (healthy), (unhealthy), or (starting)

# Inspect health check logs
docker inspect --format='{{json .State.Health}}' container_name | jq

Complete Production-Ready Dockerfile Example

This example combines all the best practices into a single, production-ready Dockerfile for a Node.js application. It uses multi-stage builds (covered in the next module) to separate the build and runtime environments, ensuring the final image contains only what is needed to run the application.

Text
# Syntax: docker/dockerfile:1.4
FROM node:20.11.0-alpine AS builder

WORKDIR /build

# Copy dependency files first for layer caching
COPY package*.json ./
RUN npm ci --only=production --no-audit --no-fund

# Build stage (if using TypeScript)
FROM node:20.11.0-alpine AS builder-ts
WORKDIR /build
COPY package*.json ./
COPY tsconfig.json ./
RUN npm ci
COPY src ./src
RUN npm run build

# Production stage
FROM node:20.11.0-alpine

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001 -G nodejs

WORKDIR /app

# Copy built artifacts from builder stages
COPY --from=builder --chown=nodejs:nodejs /build/node_modules ./node_modules
COPY --from=builder-ts --chown=nodejs:nodejs /build/dist ./dist

# Set environment
ENV NODE_ENV=production
ENV PORT=3000

# Switch to non-root user
USER nodejs

# Document the port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3000/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

# Run the application
CMD ["node", "dist/server.js"]

Knowledge Check

Ready to test your understanding of 5. The Dockerfile Complete Reference?

Back