📘 Visual Posts About Contact
Explore 📋 Cheat Sheets ✏️ Practice 🎮 Games 🎬 Simulations 🃏 Flashcards 🎯 Interactive Layers 📖 Storytelling
💜 Support my site
Module 14 • Server Admin Course Zero to Hero 2026 Updated

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 →
PRODUCTION LINUX SERVER (HOST) Nginx Proxy -p 80:80 Static + TLS ● UP 14d Node.js API :3000 (net) App + Libs ● UP 14d PostgreSQL :5432 (net) DB Engine ● UP 14d Docker Engine (Container Runtime + Bridge Network) Shared Host Linux Kernel Host Volume (-v) pgdata (Safe) Fast startup • Isolated apps • Persistent data

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.

Traditional Virtual Machines (Heavy) App A Bins / Libs Guest OS #1 (2-10 GB) App B Bins / Libs Guest OS #2 (2-10 GB) Hypervisor (KVM / VMware / Hyper-V) Host OS + Physical Server Hardware Boot time: 30-90 seconds • High RAM overhead Docker Containers (Lightweight) Container A App A + Libs (50-150 MB) Container B App B + Libs (50-150 MB) NO Guest OS Needed — Shares Host Kernel! Docker Engine (dockerd + containerd) Host Linux Kernel + Server Hardware Boot time: < 1 second • Minimal RAM overhead

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!

1. Dockerfile (Recipe) FROM node:22-alpine WORKDIR /app COPY package*.json . RUN npm ci COPY . . CMD ["node","app.js"] Plain text instructions build 2. Image (Read-Only) Layer 4: App Source Code Layer 3: npm Dependencies Layer 2: Node.js 22 Runtime Layer 1: Alpine Linux Base Cached & Immutable run 3. Container (Live) Writable Layer Logs, temp files (Ephemeral!) Shared Read-Only Image Layers (Copied on write only) PID 1 Process Running

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.

⚠️ Beginner Trap: Why Container Data Disappears!
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 extension 80, but visitors outside on the street can't reach extension 80 directly. Writing -p 8080:80 tells 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.
LINUX SERVER HOST (203.0.113.10) User Browser http://host:8080 External Request Host Port :8080 Running Container Container Port :80 App Data Path /var/lib/pg/data -p 8080:80 -v pgdata:... Host Persistent Volume (pgdata) /var/lib/docker/volumes/pgdata/_data Survives container stop, rm, & image upgrades! Syntax Order Rule -p HOST : CONTAINER -v HOST : CONTAINER

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.

DOCKER COMPOSE BRIDGE NETWORK (app-net) HTTPS Client Port 80 / 443 service: nginx Reverse Proxy Exposed :80:80 Public Entrypoint api:3000 service: api Node / Python App Internal :3000 Not public db:5432 service: db PostgreSQL 17 Internal :5432 Hidden from web Volume: pgdata Persistent Storage Security Bonus: Least Exposure Only Nginx opens port 80; API & DB stay private!

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-stopped so 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 survives docker 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.

PS

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.

LOG

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.

EXEC

docker exec -it

Opens an interactive shell inside a running container (-i = interactive, -t = terminal) so you can inspect files or test network calls.

UP

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.

🎯 Knowledge Check

Test your Module 14 mastery (4 Questions) Score: 0 / 4

1. Why do Docker containers start in less than a second compared to traditional Virtual Machines?

They share the Host OS kernel instead of booting a full Guest OS✅
They convert all applications into static HTML files❌
They run remotely on Docker Hub servers❌

2. You run docker run -d -p 8080:80 nginx:alpine. Which port should a user type into their browser to reach the site?

Port 80❌
Port 8080✅
Port 443❌

3. You delete a PostgreSQL container and recreate it with a newer image. How do you ensure all your database tables survive?

Save the data inside the container’s default writable layer❌
Use the -p flag to map port 5432❌
Mount a persistent Docker Volume (-v) to the database data directory✅

4. A container named api is running, and you want to open an interactive shell inside it to inspect its environment. Which command should you use?

docker logs -f api❌
docker exec -it api sh✅
docker build -t api .❌