Docker: Lunchboxes for Your App
The tool that solved "works on my machine" forever.
What you'll learn in this chapter
- Why "it works on my machine" was a catastrophic problem and how Docker solved it
- The difference between virtual machines and containers
- Core Docker concepts: images, containers, Dockerfiles, volumes, and networks
- How to write a real Dockerfile and use layer caching to speed up builds
- How Docker Compose orchestrates multiple containers together
- Multi-stage builds that keep production images lean and secure
- How to push images to container registries like AWS ECR and Docker Hub
The Lunchbox Analogy
Imagine you make an amazing meal for your friend. Jollof rice, the way your mother taught you โ the exact spice ratios, the smoky base, everything perfect. You write down the recipe and hand it over. Your friend goes home, follows every step, and calls back an hour later saying: "It tasted different. Mine isn't right." Why? Their kitchen runs hotter. Their tomatoes were a different variety. Their stove distributes heat unevenly. The same recipe, in a different environment, produces a different result.
For decades, software teams had exactly this problem. A developer would write code on their MacBook with Node.js 18, a specific version of a library, and their own local environment variables. The code worked perfectly. Then it landed on a production server running Node.js 16, a slightly different library version, and a different operating system โ and everything broke. The developer would say: "It works on my machine!" The operations team would say: "Well your machine isn't our server." This argument happened millions of times at millions of companies. It was not a people problem. It was a structural problem.
Docker's solution was elegant: don't send the recipe. Send the lunchbox with the exact meal already prepared, sealed inside a container that keeps it identical no matter where it is opened. The container has the exact same application, the exact same version of Node.js, the exact same libraries, the exact same configuration files. Open it on your laptop in Lagos, on a server in London, or in a datacenter in Oregon โ it is identical. The environment travels with the code.
A Docker container is a sealed lunchbox. The food (your application) is prepared once, in a controlled kitchen, with exact ingredients. The box is sealed and labeled. Wherever that box goes โ your laptop, a colleague's server, a cloud datacenter โ the food inside is always the same. No one needs to remake it in a different kitchen.
VMs vs Containers: Apartments vs Shared Housing
Before containers, the standard solution for environment consistency was the virtual machine (VM). A VM is like renting an entire apartment. You get your own living room, bedroom, kitchen, bathroom โ all four walls, everything. It is completely isolated. But it is expensive: a VM includes a full operating system, which can be gigabytes of data. Starting a VM takes two to five minutes. Running ten VMs means running ten full operating systems simultaneously, eating enormous amounts of RAM and CPU.
A Docker container is more like renting a single room in a co-living space. The building's foundation โ the plumbing, the electricity, the structural walls โ is shared between all residents. That shared foundation is the host operating system's kernel. But each room is private: its own furniture, its own decorations, its own contents. A container starts in a second or two and uses megabytes, not gigabytes, because it does not carry a full operating system. It only carries the libraries and files that are unique to it, borrowing the kernel from the host.
VIRTUAL MACHINE STACK CONTAINER STACK โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ Your Application โ โ App A โ App B โ App C โ โโโโโโโโโโโโโโโโโโโโโโโค โโโโโโโโโโโดโโโโโโโโโโดโโโโโโโโโ โ โ Guest OS (Ubuntu) โ โ Docker Engine โ โโโโโโโโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ Hypervisor โ โ Host OS (Linux) โ โโโโโโโโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ Physical Hardware โ โ Physical Hardware โ โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Each VM: full OS copy Each container: shared kernel Start time: 1-5 minutes Start time: 1-2 seconds Size: gigabytes Size: megabytes
This difference is not just academic. When you need to run 50 copies of your application to handle a traffic spike, containers let you do that in seconds using a fraction of the resources that 50 VMs would require. That speed and density is why containers transformed how software is deployed at scale.
A container is a lightweight, isolated process running on a host operating system. It packages an application together with all its dependencies (libraries, runtimes, config files) into a portable unit that runs identically anywhere Docker is installed. Containers share the host OS kernel but are isolated from each other using Linux kernel features called namespaces and cgroups.
Core Docker Concepts
Docker has a small vocabulary of terms. Learn these six and the rest falls into place.
Image โ The Recipe (Frozen)
A Docker image is a read-only snapshot of everything your application needs to run: the operating system base, the runtime (Node.js, Python, Java), the libraries, your application code, and a startup command. Images are built once and stored. When you run an image, Docker creates a container from it โ like waking up a frozen meal. The image itself never changes.
Container โ The Running Instance
A container is a live, running instance of an image. You can have ten containers all running from the same image simultaneously, each completely independent. Stop a container and it freezes. Delete it and it's gone. The image it came from is unaffected โ you can always start a fresh container from the same image.
Dockerfile โ The Instructions
A Dockerfile is a text file containing the instructions Docker follows to build an image. Think of it as the recipe for making the lunchbox. "Start with Alpine Linux. Install Node.js. Copy my code files. Run npm install. Tell Docker which port I'll use. Start the server." Each line in a Dockerfile becomes a layer in the image.
Registry โ The Image Library
A registry is a place where images are stored and shared. Docker Hub is the public registry โ
anyone can push and pull images there. Companies also run private registries: AWS ECR,
Google Artifact Registry, GitHub Container Registry. When you write FROM node:20-alpine
in your Dockerfile, Docker pulls that base image from Docker Hub.
Volume โ Persistent Storage
Containers are ephemeral by default โ when a container is deleted, any data it wrote to its filesystem disappears. Volumes solve this. A volume is a directory that lives outside the container's filesystem and persists independently. Your PostgreSQL container can write database files to a volume. Delete the container, create a new one, mount the same volume โ your data is still there.
Network โ Containers Talking to Each Other
Each container gets its own network interface. Docker networks let you group containers
so they can reach each other by name. Your Node.js app container can reach your PostgreSQL
container at the hostname db โ as if they are on the same local network.
From outside the cluster, nothing can reach them unless you explicitly publish a port.
Your First Dockerfile
Let's write a real Dockerfile for a Node.js application. Every line matters โ and understanding why each line is written in this specific order will save you hours of build time frustration later.
# Start from the official Node.js 20 Alpine image
# Alpine is a tiny Linux distro โ keeps our image small (~180MB vs ~900MB)
FROM node:20-alpine
# Set the working directory inside the container
# All subsequent commands run from here
WORKDIR /app
# Copy ONLY the package files first โ before copying source code
# This is critical for layer caching (explained below)
COPY package*.json ./
# Install production dependencies
# npm ci is faster and more reliable than npm install in CI environments
RUN npm ci --only=production
# NOW copy the rest of the source code
COPY . .
# Tell Docker which port the app listens on (documentation โ does not open the port)
EXPOSE 3000
# The command to run when the container starts
# Use JSON array form โ more reliable than shell string form
CMD ["node", "server.js"]
Understanding Layer Caching
Docker builds images in layers โ one layer per instruction. When you rebuild an image, Docker checks: has anything changed since the last build? If a layer's input hasn't changed, Docker reuses the cached version of that layer and every layer after it that's also unchanged. This is why the order of instructions is so important.
If you COPY . . before running npm install, then every time you
change a single line of source code, Docker invalidates the copy layer, which invalidates
the npm install layer โ meaning it re-downloads and reinstalls all your dependencies on
every build. That can take minutes. With the package.json copied first, changing your
source code only invalidates the final copy layer, and npm install uses the cache.
Builds that took three minutes now take ten seconds.
Layer Caching โ Why Package Files Come First: BUILD 1: BUILD 2 (code changed, deps unchanged): โโโ FROM node:20-alpine โ โโโ FROM node:20-alpine โ (cached) โโโ WORKDIR /app โ โโโ WORKDIR /app โ (cached) โโโ COPY package*.json โ โโโ COPY package*.json โ (cached โ unchanged) โโโ RUN npm ci โ โโโ RUN npm ci โ (cached โ reused!) โโโ COPY . . โ โโโ COPY . . โป (CHANGED โ rebuild only this) Result: 3-minute build โ 10-second build
Put things that change rarely (base image, system packages, dependencies) near the top of your Dockerfile. Put things that change often (your source code) near the bottom. Docker caches from top to bottom. Any change invalidates that layer and everything below it.
Docker Commands You Will Use Every Day
These are the commands you will type dozens of times a week. Learn them and Docker stops feeling mysterious.
# Build an image from the Dockerfile in the current directory
# -t gives it a name:tag
docker build -t myapp:1.0 .
# Run a container in detached mode (-d = background)
# -p maps host port 3000 to container port 3000
# --name gives the container a memorable name
docker run -d -p 3000:3000 --name myapp myapp:1.0
# List running containers
docker ps
# List ALL containers (including stopped ones)
docker ps -a
# View the logs of a container
docker logs myapp
# Follow logs in real time (like tail -f)
docker logs -f myapp
# Open an interactive shell inside a running container
# -it = interactive + TTY; sh because Alpine doesn't have bash by default
docker exec -it myapp sh
# Stop a running container gracefully
docker stop myapp
# Remove a stopped container
docker rm myapp
# Remove an image
docker rmi myapp:1.0
# Pull an image from Docker Hub (runs automatically with docker run too)
docker pull postgres:16
# Push an image to a registry
docker push myregistry/myapp:1.0
# See all images on your machine
docker images
# Remove stopped containers, unused images, dangling layers
# (reclaim disk space โ run this when Docker eats your hard drive)
docker system prune
By default, processes inside a container run as root. This is a security risk โ
if an attacker breaks out of the container, they are root on the host. Add a
USER instruction to your Dockerfile to run as a non-root user:
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
followed by USER appuser. Production-grade Dockerfiles always do this.
Docker Compose โ Running Multiple Containers Together
Real applications are not one container. A typical web application has a backend service,
a PostgreSQL database, a Redis cache for sessions, maybe a background worker queue.
Running these manually with individual docker run commands and networking
them together is tedious and error-prone.
Docker Compose solves this. You describe all your services in a single YAML file โ
docker-compose.yml โ and then start everything with one command:
docker compose up. Compose handles networking, environment variables,
startup order, and volumes. Tear it all down with docker compose down.
It is the closest thing to magic Docker offers.
# docker-compose.yml โ a Node.js app with PostgreSQL and Redis
version: '3.8'
services:
app:
build: . # build image from Dockerfile in current dir
ports:
- "3000:3000"
environment:
DATABASE_URL: postgresql://user:pass@db:5432/mydb
REDIS_URL: redis://redis:6379
depends_on:
db:
condition: service_healthy # wait for db to be ready
- redis
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data # persist data here
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d mydb"]
interval: 10s
retries: 5
redis:
image: redis:7-alpine
volumes:
postgres_data: # Docker manages this volume
Notice that the app connects to the database at the hostname db โ not
localhost or an IP address. Compose creates a private network between all
services, and each service is reachable by its service name. The app container can reach
the database container at db:5432 just like two offices in the same building
can call each other by extension number.
# Start all services in the background
docker compose up -d
# Follow the logs from all services at once
docker compose logs -f
# Follow logs from one service only
docker compose logs -f app
# Rebuild images if Dockerfile changed, then restart
docker compose up --build -d
# Stop containers without removing them
docker compose stop
# Stop and remove containers, networks (keeps volumes)
docker compose down
# Stop and remove containers, networks, AND volumes (wipes the database!)
docker compose down -v
Use Docker Compose for local development โ it is excellent. For production, you will want Kubernetes (Chapter 7). Compose lacks the self-healing, auto-scaling, and advanced networking that production systems need. But for running a full stack locally with a single command, nothing beats it.
Multi-Stage Builds โ Lean Production Images
Here is a problem that surprises many developers the first time they encounter it. You write a TypeScript application. To build it, you need the TypeScript compiler, all your dev dependencies, test frameworks, build tools โ hundreds of megabytes of development tooling. But to run the compiled JavaScript, you need almost none of that. Your production container should not be lugging around a compiler it will never use.
Multi-stage builds solve this elegantly. You define multiple FROM stages
in a single Dockerfile. One stage does the build work with all the heavy tools installed.
A second stage starts fresh from a minimal base image and copies only the compiled output
from the first stage. The final image is lean โ just what's needed to run.
# Stage 1: Build โ has all dev tools, compiles the TypeScript
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci # includes dev dependencies for building
COPY . .
RUN npm run build # outputs compiled JS to /app/dist
# Stage 2: Production โ starts fresh, only copies compiled output
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production # only prod deps in the final image
# Run as non-root
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
EXPOSE 3000
CMD ["node", "dist/server.js"]
The result is an image that may be 150MB instead of 900MB โ and crucially, it does not contain the TypeScript compiler, test files, or any development tooling that could represent a security surface in production. Smaller images build faster, push faster, pull faster, and start faster.
A naive Node.js image using the full node:20 base can easily reach 1.2GB.
The same application built with Alpine and multi-stage builds typically comes in under 200MB.
When Kubernetes pulls that image across 100 nodes during a deploy, the difference between
1.2GB and 200MB is the difference between a 20-minute deploy and a 3-minute one.
Image size is not vanity โ it is operational speed.
Container Registries โ Where Images Live
Once you build an image, you need somewhere to store it so that servers, CI pipelines, and Kubernetes clusters can pull it. That somewhere is a container registry. Docker Hub is the default public registry โ you can push public images there for free. For production environments, most companies use a private registry close to where their infrastructure lives.
The major cloud providers all offer registries: AWS has ECR (Elastic Container Registry), Google Cloud has Artifact Registry, and Microsoft Azure has ACR (Azure Container Registry). GitHub Container Registry (GHCR) is increasingly popular because it integrates directly with GitHub Actions.
Pushing to AWS ECR
# Step 1: Authenticate Docker with AWS ECR
# This gets a short-lived password from AWS and pipes it to docker login
aws ecr get-login-password --region us-east-1 | \
docker login --username AWS --password-stdin \
123456789.dkr.ecr.us-east-1.amazonaws.com
# Step 2: Tag your local image with the ECR repository URL
docker tag myapp:1.0 \
123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:1.0
# Step 3: Push the image to ECR
docker push \
123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:1.0
Pushing to GitHub Container Registry
# Authenticate with a personal access token (or GITHUB_TOKEN in Actions)
echo $GITHUB_TOKEN | docker login ghcr.io -u yourusername --password-stdin
# Tag with ghcr.io prefix
docker tag myapp:1.0 ghcr.io/yourusername/myapp:1.0
# Push
docker push ghcr.io/yourusername/myapp:1.0
Use meaningful tags. The latest tag is convenient but dangerous in production โ
you never know exactly which version latest points to after a new push.
Use semantic versions (1.2.3) or, even better, Git commit SHAs
(myapp:a3f9bc2). Then you always know exactly which code is running.
CI/CD pipelines (Chapter 6) automate this tagging for you.
A Complete Example: Dockerizing a NestJS Microservice
Let's put everything together with a realistic example โ a NestJS microservice with TypeScript, production multi-stage build, non-root user, and proper health check support.
# ---- Stage 1: Dependencies ----
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
# ---- Stage 2: Build ----
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# ---- Stage 3: Production Runner ----
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Create a non-root user
RUN addgroup --system appgroup && \
adduser --system --ingroup appgroup appuser
COPY --from=builder /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
COPY package*.json ./
USER appuser
EXPOSE 3000
# Health check โ Kubernetes and Docker will use this
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "dist/main.js"]
Just like .gitignore tells Git which files to ignore, a .dockerignore
file tells Docker which files to exclude from the build context. Always add
node_modules, .git, *.log, and .env
files to your .dockerignore. Sending node_modules (which can
be hundreds of thousands of files) to the Docker daemon on every build will make your
builds dramatically slower.
Chapter Summary
- Docker solved the "works on my machine" problem by packaging an application with all its dependencies into a portable container that runs identically anywhere.
- Containers are lighter than VMs because they share the host OS kernel rather than running a full guest operating system.
- A Dockerfile is a set of instructions for building an image. Images are immutable snapshots; containers are live running instances of an image.
- Layer caching speeds up builds dramatically โ copy package files before source code so that npm install only re-runs when dependencies actually change.
- Docker Compose orchestrates multi-container applications with a single YAML file, letting you bring up a full stack (app + database + cache) with one command.
- Multi-stage builds produce lean production images by separating the build environment from the runtime environment, stripping out compilers and dev tools.
- Container registries (Docker Hub, AWS ECR, GHCR) store and distribute images. Always use specific version tags in production, not
latest.