Containers & Docker on Servers
Stop fighting dependency nightmares and "it works on my machine" bugs. Learn how Docker packages apps into lightweight, portable shipping containers—complete with persistent volumes, port mapping, and multi-container Compose stacks.
Start Module 14 →01 "It Works on My Machine" Solved
Define: A container is a lightweight, standalone, executable package that bundles an application's code together with the exact libraries, runtime (like Python 3.12 or Node 22), and system dependencies it needs to run—without bundling a full operating system.
Understand (The Shipping Container Analogy): Before the 1950s, loading a ship was a nightmare. Bananas, pianos, and barrels of oil all had different shapes, so dockworkers had to pack each ship by hand, and things broke constantly. Then came the standardized steel shipping container. Suddenly, cranes, trucks, and cargo ships didn't care what was inside the box—they all moved the exact same standard box.
Docker brings that exact idea to servers. Before containers, a developer wrote code on a MacBook with Python 3.12, pushed it to an Ubuntu server running Python 3.8, and the app crashed with the famous excuse: "Well, it works on my machine!" With Docker, you ship the entire environment inside one standardized box. If it runs on your laptop, it runs identically on your staging server, production VPS, or cloud cluster.
Know (Containers vs. Virtual Machines): In Module 3, we learned how Virtual Machines (VMs) virtualize physical hardware so you can run a complete Guest OS (Windows or Linux) inside a hypervisor. Containers take a smarter shortcut: instead of booting a brand-new 4 GB Guest OS for every app, all containers on a server share the Host Linux Kernel.
When to use VMs vs. Containers: Use a VM when you need complete OS-level isolation (for example, running Windows Server and Ubuntu on the same physical machine). Use Containers when you want to run multiple Linux services (web apps, APIs, databases, workers) on one server with near-zero overhead and instant deployments.
Execute: Verify Docker is installed and running on your Linux server with:
docker --version
docker run --rm hello-world
🧠 Memory Trick: "Houses vs. Apartments"
A Virtual Machine is a detached house—it has its own plumbing, power meter, and roof (Guest OS). A Container is an apartment in a building—every tenant has a locked door (process isolation), but they all share the building's foundation and water main (Host Linux Kernel).
02 Images vs. Containers & Dockerfile Layers
Define: Every Docker workflow revolves around three connected pieces: a Dockerfile (the recipe), a Docker Image (the read-only blueprint), and a Docker Container (the live, running instance).
Understand (The Cake Recipe Analogy):
- Dockerfile = The Recipe: A plain text file with step-by-step instructions
(start with Node 22, copy my code, install packages, run
server.js). - Docker Image = The Frozen Cake Mold / Blueprint: Once you bake the recipe with
docker build, you get a read-only image. You cannot edit a running image directly, and you can store it on a registry like Docker Hub or GitHub Container Registry. - Docker Container = The Live Cake on a Plate: Every time you run
docker run, Docker creates a live container from that image. You can stamp out 1, 5, or 50 identical containers from a single image.
Know (How Dockerfile Layers Work): Each line in a Dockerfile creates a
cached, read-only layer stacked on top of the previous one. When you start a
container, Docker simply places a thin read-write layer on top of the image stack.
If two containers use the same nginx:alpine image, they share the read-only layers on
disk instead of duplicating them!
When layer ordering matters: Notice how COPY package*.json . and
RUN npm ci appear before COPY . . in the Dockerfile above. Because
Docker caches unchanged layers, editing a single line of your app code won't force Docker to
re-download every npm package—your rebuild finishes in 2 seconds instead of 2 minutes.
Execute: Build an image from the current directory and tag it as
my-api:1.0:
docker build -t my-api:1.0 .
docker images
03 Persistent Volumes & Port Mapping
Define: By default, a container is completely sealed off from the outside world and
has a temporary filesystem. To make a server container actually useful, you need two flags:
-p (Port Mapping) to let network traffic in, and
-v (Volumes) to keep data alive when the container is deleted or
upgraded.
Everything you save inside a container's normal writable layer disappears the moment you run
docker rm or upgrade the image. Never store database files, uploaded user photos, or
config edits inside the container layer—always attach a Volume.
Understand (The Hotel Room & Intercom Analogy):
- Port Mapping (
-p 8080:80): Think of a container like a locked hotel room. Nginx inside the container is listening on room phone extension80, but visitors outside on the street can't reach extension80directly. Writing-p 8080:80tells the server's front desk: "Forward anyone knocking on Host Port 8080 straight to Container Port 80." - Volumes (
-v pgdata:/var/lib/postgresql/data): Think of a volume as an external safe bolted to the server's concrete floor. Even if you tear down the hotel room (delete the container) and build a newer room (deploy Postgres 17), you plug the new room into the exact same safe, and all your data is still there.
Know (Named Volumes vs. Bind Mounts):
| Volume Type | Syntax Example | Best Used For |
|---|---|---|
| Named Volume | -v pgdata:/var/lib/postgresql/data |
Databases (Postgres, MySQL, Redis) where Docker manages the folder safely. |
| Bind Mount | -v /srv/www/html:/usr/share/nginx/html:ro |
Config files (nginx.conf) or website HTML folders you edit directly on
the host. |
Execute: Run an Nginx web server on host port 8080 serving files from
/srv/html, and run a Postgres database with a persistent named volume:
docker run -d --name web -p 8080:80 -v /srv/html:/usr/share/nginx/html:ro nginx:alpine
docker volume create pgdata
docker run -d --name db -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:17
🧠 Memory Trick: "Outside In" (Host : Container)
In both -p 8080:80 and -v pgdata:/data, the
left side is ALWAYS the Host (outside) and the right side is ALWAYS the
Container (inside). Think: Outside → Inside.
04 Docker Compose for Multi-Service Stacks
Define: Docker Compose is a tool (built into modern Docker as
docker compose) that lets you define and run a multi-container application using a
single human-readable YAML file named compose.yaml.
Understand (The Orchestra Analogy): Running one container with
docker run is like playing a solo guitar. Running a real production app—an Nginx reverse
proxy, a Node.js API, and a PostgreSQL database—with three separate, 200-character
docker run commands is error-prone and impossible to remember. Docker
Compose is the conductor's sheet music: one file describes every instrument, its ports,
its volumes, and how they talk to each other.
Know (Automatic Internal DNS): When you run docker compose up -d, Docker
automatically creates a private bridge network for your stack. Inside that network,
containers can find each other by service name! Your API doesn't need to know the
database's changing IP address—it simply connects to db:5432, and Nginx proxies to
http://api:3000.
Execute: Here is a clean, production-style compose.yaml for that exact
3-service stack:
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- api
restart: unless-stopped
api:
build: ./api
environment:
DATABASE_URL: postgres://app:secret@db:5432/prod
depends_on:
- db
restart: unless-stopped
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: prod
volumes:
- pgdata:/var/lib/postgresql/data
restart: unless-stopped
volumes:
pgdata:
✅ Checkpoint: Compose Design Habits
- Always add
restart: unless-stoppedso containers come back automatically after a server reboot. - Only publish
ports:on the reverse proxy (Nginx/Caddy)—keep databases off the public internet. - Declare named
volumes:at the bottom so database data survivesdocker compose down.
05 Practical Server Admin Commands
Define: As a server administrator, 90% of your daily Docker work comes down to four core commands: checking what is running, reading live logs, stepping inside a container to debug, and managing Compose stacks.
docker ps
Lists all currently running containers, their uptime, image, and port mappings. Add
-a (docker ps -a) to also see crashed or stopped containers.
docker logs -f
Streams live stdout/stderr output from a container (just like tail -f). Use
--tail 100 to view the last 100 lines first.
docker exec -it
Opens an interactive shell inside a running container (-i = interactive,
-t = terminal) so you can inspect files or test network calls.
docker compose up -d
Starts or updates your entire multi-container stack in detached (background) mode. Pair with
docker compose down to stop and clean up containers (volumes stay safe).
Execute (Real Server Troubleshooting Workflow):
# 1. Check which containers are running (and which exited)
docker ps -a
# 2. Follow live logs of the "api" container
docker logs -f --tail 50 api
# 3. Open a shell inside a running Alpine-based container
docker exec -it api sh
# 4. Launch or update a Compose stack in the background
docker compose up -d
# 5. Check disk usage and clean up unused old images
docker system df
docker image prune -f
🛠️ Practice Scenario: Broken Web App After Server Reboot
You SSH into a production server and users report a 502 Bad Gateway error. You run
docker ps and see nginx is running, but api is missing.
What two commands do you run to find out why api crashed and fix it?
Show Solution
1. Run docker ps -a to confirm api is in an
Exited (1) state rather than deleted.
2. Run docker logs --tail 100 api to read the exact crash error (for
example, a missing environment variable or database connection timeout).
3. Once fixed in compose.yaml, run docker compose up -d to
recreate and start only the updated service.