Module 5: Docker — The Complete Guide
Goal
Containers are the unit of deployment in modern infrastructure. This module takes you from "what is a container" to writing optimized multi-stage Dockerfiles, running multi-service stacks with Compose, and shipping images through registries — the exact skills every DevOps job description lists.
1. The Problem Docker Solves
Classic incident: "It works on my machine!" — developer has Python 3.11, server has 3.8; dev installed a system library the server lacks; staging and prod drift apart. Deployments become archaeology.
A container image packages the app + runtime + libraries + OS userland into one immutable artifact. The same bytes run on your laptop, CI, staging, and prod. Deployment stops being "install and pray" and becomes "run this image, tag v2.3.1."
Analogy
Before shipping containers, dockworkers hand-loaded every barrel and crate differently at every port — slow, error-prone, works-on-my-dock chaos. The standardized sealed steel box changed everything: pack it once at the factory, and every crane, truck, and ship in the world handles it the same way without ever opening it. A Docker image is that sealed box for software — packed once, identical wherever it lands.
Containers vs Virtual Machines
App A + Guest OS | App B + Guest OS
↓ Hypervisor
↓ Host OS
every VM carries a full OS — GBs each, minutes to boot
App A | App B | App C
↓ Docker Engine
↓ ONE shared kernel
↓ Host OS
just processes on one kernel — MBs each, milliseconds to start
A container is not a mini-VM — it's a normal Linux process wearing isolation:
- Namespaces (Module 4!) — its own network, PIDs, filesystem view, hostname.
- cgroups — CPU/memory limits.
- Union filesystem — layered, copy-on-write image storage.
Consequences: containers start in milliseconds, share the host kernel (so a Linux container can't run a Windows kernel), and ps aux on the host shows container processes — because that's all they are.
Analogy
A VM is chartering a whole separate ship for each cargo — engine, crew, hull and all, which is why it takes ages to get underway. A container is just one more standardized box stacked on a shared ship: the vessel's engine (the kernel) is common to every box on board, so loading another one takes seconds. That also means every box must fit this ship's fittings — you cannot stack a box built for a different kind of vessel.
Architecture: the docker CLI talks to the Docker daemon (dockerd), which manages images, containers, networks, volumes. Docker Desktop (Mac/Windows) runs a hidden Linux VM to provide the kernel.
2. Images, Tags, Registries
- Image — immutable template (like a class).
- Container — a running instance of an image (like an object).
- Registry — server storing images: Docker Hub (public default), AWS ECR, GitHub Container Registry (ghcr.io), or self-hosted.
Image naming: registry/namespace/name:tag
nginx:1.25 → Docker Hub official image
ghcr.io/myorg/api:v2.3.1 → GitHub registry
123456789.dkr.ecr.us-east-1.amazonaws.com/api:v2.3.1 → AWS ECRTags are mutable pointers, not versions. latest is just a tag people overwrite — pulling myapp:latest twice can give different images. Production rule: deploy pinned tags (v2.3.1) or, for maximum rigor, digests (@sha256:...). Never latest in prod — you lose the ability to know what's running or roll back precisely.
Analogy
The image is the sealed box sitting in the yard; a running container is one copy of that box unloaded and opened for use, and the registry is the container port where sealed boxes wait to be shipped anywhere. A tag, though, is only a paper label pasted on a box — the yard crew can peel latest off one box and slap it on another overnight. Serious shippers therefore quote the serial number stamped into the steel: that is the digest.
Core CLI
docker pull nginx:1.25
docker images # local images
docker run -d --name web -p 8080:80 nginx:1.25
# -d = detached (background)
# -p = publish: hostPort:containerPort (iptables NAT!)
docker ps # running containers (-a: incl. stopped)
docker logs -f web # follow logs — your #1 debugging tool
docker exec -it web bash # shell INSIDE the container
docker stop web && docker rm web
docker inspect nginx:1.25 # full metadata JSON (env, layers, config)
docker system prune # clean up stopped containers, dangling imagesdocker exec -it <c> sh is the container equivalent of SSH — you'll use it daily to poke around a misbehaving container.
3. Writing Dockerfiles
A Dockerfile is a recipe; each instruction creates a layer.
# Dockerfile for a Python Flask app
FROM python:3.12-slim
WORKDIR /app
# Copy dependency list FIRST (layer-caching trick — see below)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Then copy the code
COPY . .
EXPOSE 8080
CMD ["gunicorn", "--bind", "0.0.0.0:8080", "app:app"]docker build -t myapp:dev .
docker run -p 8080:8080 myapp:devKey instructions
| Instruction | Purpose | Notes |
|---|---|---|
FROM | base image | prefer -slim/alpine variants |
WORKDIR | set working dir | creates it if missing |
COPY | files from build context | COPY src/ /app/src/ |
RUN | execute at build time | each RUN = one layer |
ENV | env var, baked into image | config defaults |
ARG | build-time variable | not in final image |
EXPOSE | documentation of port | doesn't actually publish |
CMD | default command at run time | overridable |
ENTRYPOINT | fixed command; CMD becomes its args | for CLI-style images |
USER | drop root | security best practice |
HEALTHCHECK | container self-test | Compose/K8s use it |
RUN vs CMD confusion kills beginners: RUN pip install happens when building; CMD ["python","app.py"] is what executes when the container starts.
Analogy
RUN is work done at the packing warehouse before the box is sealed — assembling the goods, bolting on parts. CMD is the instruction sheet taped inside the lid, telling the crew at the destination what to do the moment they open the box. Confusing the two is like expecting the unpacking crew to manufacture the product on the dock.
Layer caching — the difference between 5-second and 5-minute builds
Docker caches each layer; a layer rebuilds only if its inputs changed — and everything after it rebuilds too. Hence the golden ordering: least-changing things first.
COPY requirements.txt . # changes rarely → cached
RUN pip install -r ... # cached as long as requirements.txt is unchanged
COPY . . # changes every commit → only this rebuildsIf you COPY . . before pip install, every code change re-installs all dependencies. This single ordering mistake wastes thousands of CI hours worldwide.
Analogy
Layers are pallets stacked inside the container in a strict order: to swap out a pallet near the bottom, the crew must unload and repack every pallet above it too. So you load the heavy, rarely-changing pallets first and keep the paperwork you revise daily right on top. Put your daily paperwork at the bottom and every small change means restacking the whole box.
Best-practices checklist
FROM python:3.12-slim # 1. small, pinned base (never FROM python — that's 'latest')
RUN adduser --disabled-password appuser
USER appuser # 2. don't run as root
COPY --chown=appuser . . # 3. correct ownership- Add a
.dockerignore(like .gitignore):.git,node_modules,.env,*.md— smaller context, faster builds, no leaked secrets. - Combine related RUNs and clean up in the same layer:
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*(cleanup in a later layer doesn't shrink the image — the files still exist in the earlier layer!) - Never
COPYsecrets or bake credentials viaENV— anyone with the image can read them (docker history,docker inspect).
4. ARG vs ENV, and Multi-Stage Builds
ARG APP_VERSION=dev # exists only during build
ENV APP_VERSION=${APP_VERSION} # persist it into the runtime imagedocker build --build-arg APP_VERSION=v2.3.1 -t myapp:v2.3.1 .Typical use: CI passes the Git tag in so the app can report its own version.
Multi-stage builds — pro-level image optimization
Problem: building a Go/Node/Java app needs compilers and dev dependencies; running it doesn't. Shipping build tools = bloated, more-vulnerable images.
# ---- Stage 1: build (has the whole toolchain) ----
FROM golang:1.22 AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server
# ---- Stage 2: runtime (nearly empty) ----
FROM alpine:3.20
RUN adduser -D appuser
USER appuser
COPY --from=builder /app /app
EXPOSE 8080
ENTRYPOINT ["/app"]Result: ~900MB builder → ~15MB final image. Faster pulls, faster autoscaling, drastically smaller attack surface. Same pattern for Node (build stage runs npm run build, runtime stage is nginx serving /dist) and Java (Maven stage → JRE stage).
Analogy
A multi-stage build is manufacturing at the dockside factory but shipping only the finished goods. The first container holds the entire workshop — tools, scrap, raw materials — and when the product is done, you lift just that one finished item into a fresh, nearly empty box for the voyage. The workshop box never leaves the dock, so the ship carries kilograms instead of tonnes.
Inspect your layers: docker history myapp:v1, or better, the dive tool (dive myapp:v1) which shows exactly which files each layer adds and flags wasted space.
5. Container Networking
Docker's default bridge network = the namespace + veth + NAT setup you built by hand in Module 4.
docker network create appnet
docker run -d --name db --network appnet postgres:16
docker run -d --name api --network appnet -p 8080:8080 myapp:v1On a user-defined network, containers reach each other by name — Docker runs an internal DNS: the api connects to postgres://db:5432. No IPs hardcoded anywhere.
Analogy
A user-defined network is a fenced dock yard where every box carries a nameplate: crates call each other by name and the dockmaster keeps the directory, so nobody memorizes berth numbers that change with every shipment. Publishing a port cuts exactly one hatch in the yard's outer fence; everything without a hatch stays reachable only from inside the yard — exactly where you want a database.
-p 8080:80publishes to the host (iptables NAT rule).- No
-p= reachable only from other containers on the same network — perfect for databases. --network host= no isolation, container shares host's stack (rare; perf-sensitive cases).
Debug: docker network inspect appnet, or from inside: docker exec api ping db.
6. Volumes — Data That Survives
Container filesystems are ephemeral: docker rm deletes everything inside. Databases would lose all data. Volumes fix this.
Analogy
A volume is the warehouse standing next to the dock: ships and their boxes come and go, but goods moved into the warehouse stay put through every swap. Keep your ledgers inside the shipping box itself and they sail away — or get scrapped — with it. The warehouse survives any number of ship changes; that is the whole point of building it on land.
# Named volume (Docker-managed) — for databases
docker volume create pgdata
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:16
# Bind mount (host path) — for development live-reload
docker run -v $(pwd)/src:/app/src myapp:dev
# tmpfs — RAM only, for secrets/scratch
docker run --tmpfs /tmp myapp| Type | Use case |
|---|---|
| Named volume | production data (DBs, uploads) |
| Bind mount | dev: edit code on host, app reloads in container |
| tmpfs | sensitive scratch data |
Real incident to learn from: team runs Postgres in Docker without a volume; host reboots with --rm containers → entire database gone. Volumes are not optional for stateful services.
7. Docker Compose — Multi-Service Apps
Real apps = app + database + cache + proxy. Compose defines the whole stack in one YAML file:
# docker-compose.yml
services:
api:
build: . # build from local Dockerfile
ports: ["8080:8080"]
environment:
DATABASE_URL: postgres://app:secret@db:5432/appdb
REDIS_URL: redis://cache:6379
depends_on:
db:
condition: service_healthy # wait for REAL readiness, not just "started"
restart: unless-stopped
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck: # defines what "healthy" means
test: ["CMD-SHELL", "pg_isready -U app"]
interval: 5s
timeout: 3s
retries: 10
cache:
image: redis:7-alpine
volumes:
pgdata:docker compose up -d # start everything (builds if needed)
docker compose ps # status of the stack
docker compose logs -f api # follow one service's logs
docker compose exec db psql -U app appdb
docker compose down # stop & remove (add -v to also wipe volumes )Startup ordering — a classic real-world bug
depends_on alone only waits for the container to start, not for Postgres to be ready — so the api crashes with "connection refused" on boot. Two professional fixes:
- Healthcheck + condition (shown above) — Compose waits for the DB healthcheck to pass.
- Wait script as entrypoint — robust everywhere (including K8s):
#!/bin/sh
# entrypoint.sh — Module 3 skills in action
until nc -z db 5432; do echo "waiting for db..."; sleep 1; done
exec gunicorn --bind 0.0.0.0:8080 app:app(Also: build your app to retry connections — infrastructure should not be the only safety net.)
Compose is the standard for local dev environments and small single-host deployments. Multi-host orchestration is Kubernetes (Module 7) — same concepts, bigger scale.
Analogy
A Compose file is the shipping manifest for a whole convoy: which boxes to load, which fenced yard they share, which warehouse each one connects to — one document, one command, and the entire convoy sails together. And depends_on without a healthcheck is like waving the truck off the moment the crate touches the trailer, without ever checking that the goods inside are actually assembled.
8. Registries — Shipping Images
# Docker Hub
docker login
docker tag myapp:v2.3.1 yourname/myapp:v2.3.1 # tag = name it for the registry
docker push yourname/myapp:v2.3.1
# AWS ECR (private) — the login is generated by AWS CLI
aws ecr get-login-password --region us-east-1 \
| docker login --username AWS --password-stdin 123456789.dkr.ecr.us-east-1.amazonaws.com
docker tag myapp:v2.3.1 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:v2.3.1
docker push 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:v2.3.1The flow that powers every modern deploy: CI builds image → pushes to registry → servers/K8s pull by tag. The registry is the handoff point between "build" and "run".
Analogy
The registry is the container port sitting between the factory and the ships. The factory seals a box, stamps its version on the side, and delivers it to the port; from then on, any destination in the world pulls exactly that stamped box. Nobody hand-carries goods from the factory floor straight onto a ship — everything passes through the port, and that single handoff point is what makes the same cargo retrievable anywhere.
Building & pushing from GitHub Actions (preview of Module 6)
# .github/workflows/build.yml
name: build-and-push
on:
push:
tags: ["v*"]
jobs:
docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
push: true
tags: yourname/myapp:${{ github.ref_name }}
cache-from: type=gha # CI-persistent layer cache
cache-to: type=gha,mode=maxPush a git tag v2.3.1 → CI builds and publishes myapp:v2.3.1 automatically. Git tag = image tag = deployable version: full traceability.
9. Multi-Platform Images (buildx)
Your laptop may be ARM (Apple Silicon); servers are usually x86_64 (amd64); AWS Graviton is ARM again. An image built for one architecture won't run on the other (exec format error — recognize this error message!).
docker buildx create --use
docker buildx build \
--platform linux/amd64,linux/arm64 \
-t yourname/myapp:v2.3.1 --push .buildx builds both variants (via QEMU emulation) and pushes a manifest list — one tag that automatically serves the right architecture to each puller. Official images like nginx work this way, which is why the same docker pull works on your Mac and on EC2.
Analogy
Some ports fit one kind of crane coupling, others fit another, and a box built for the wrong coupling simply cannot be lifted — that is your exec format error. A manifest list is one catalog number that quietly stocks both fittings: order it from an ARM port and the ARM-fitted box arrives, order from an amd64 port and you get that one. The customer quotes a single name; the port picks the right variant.
10. Debugging Containers — Field Guide
| Symptom | First moves |
|---|---|
| Container exits immediately | docker logs <c>; docker inspect <c> --format '{{.State.ExitCode}}' (137 = OOM-killed/SIGKILL, 1 = app error) |
| "Works locally, dies in container" | missing env var? docker exec -it <c> env; missing file? docker exec -it <c> ls |
| Can't reach the app | is it binding 0.0.0.0? did you -p? docker port <c>; ss -tulpn inside |
| API can't reach DB | same network? docker network inspect; DNS name correct? docker exec api ping db |
| Image is huge | docker history, dive — usually missing .dockerignore or no multi-stage |
| Disk full on host | docker system df, then docker system prune -a --volumes ( understand before running) |
11. Hands-On Project (Do This)
Build a realistic 3-service stack:
- Write a small Flask/Express API with
/healthand one endpoint that reads/writes Postgres and counts hits in Redis. - Write its Dockerfile: slim base, layer-cached deps, non-root user, HEALTHCHECK. Then convert it to multi-stage and compare sizes with
docker imagesanddive. - Compose file: api + postgres (named volume, healthcheck) + redis. Prove data survives
docker compose down && up. - Break it on purpose: remove
condition: service_healthyand watch the race; fix with anc -zwait entrypoint. - Push the image to Docker Hub with a version tag; pull and run it on a different machine (or an EC2 instance).
- Set up the GitHub Actions workflow from §8 so tagging
v0.1.0publishes automatically. - Bonus: make the image multi-platform with buildx; verify with
docker manifest inspect.
12. Self-Check Questions
- Why can a container start in milliseconds while a VM takes minutes? What three kernel features make a container?
- Why must
COPY requirements.txt+RUN pip installcome beforeCOPY . .? - Exit code 137 — what happened?
- Why doesn't
RUN rm -rf /var/lib/apt/lists/*in a separate layer shrink the image? depends_ondidn't prevent "connection refused" at startup — why, and what are two fixes?- Why is deploying
:latestto production considered malpractice? - What is a manifest list and when do you need buildx?
Next → Module 6: CI/CD
