Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com Official Telegram Support (@PathubsSupport)
Pathubs

100% Free, Zero-Paywall Tech Career Roadmaps, In-Depth Practical Content, and Live Interactive Virtual Labs for Learners Worldwide.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
Backend Web Development RoadmapPhase 07: Containerization & OS • Docker Basics
Pathubs Backend Curriculum • Phase 07: Containerization

Docker Basics & Containerization

Master modern container architecture from first principles. Understand Linux kernel isolation, eliminate the “works on my machine” crisis, craft production-ready Dockerfiles, optimize layer caching, master port mapping, persist database state with volumes, and orchestrate services with Docker Compose.

⏱️ Estimated Time:45 Minutes
🎯 Level:Beginner to Intermediate
📊 Track:Backend & DevOps Engineering
✨ Mode:Interactive Architecture & CLI Lab

Curriculum Outline

• 1. Why Docker? The Problem It Solves• 2. Virtual Machines vs. Containers• 3. The Core Trinity: Image, Container & Registry• 4. Dockerfile Anatomy & Syntax⚡ 5. Interactive Layer Caching Simulator⚡ 6. Live Container Lifecycle Visualizer⚡ 7. Port Mapping & Networking Lab• 8. Data Persistence: Volumes vs. Bind Mounts• 9. Context Optimization with .dockerignore• 10. Multi-Container Orchestration (Docker Compose)• 11. 5 Dangerous Beginner Traps⚡ 12. Interactive Docker CLI Playground• 13. Production Best Practices & Security• 14. What You Should Know Now: Checklist🎯 15. Knowledge Assessment (Quiz)
1

Why Docker? The Real-World Problem It Solves

Before containerization, the software industry suffered from the notorious “It works on my machine!” syndrome. A developer would write a backend in Node.js or Python on macOS. It passed all tests locally. But when deployed to an Ubuntu production server or an AWS EC2 instance, it crashed immediately.

Why did this happen? Applications do not run in a vacuum. An application depends on:

  • The specific runtime version (e.g. Node 18 vs Node 20, Python 3.10 vs 3.12)
  • OS-level shared C libraries (like OpenSSL, glibc, image processing libs)
  • Environment variables and file system path configurations
  • System package managers and background daemon dependencies
The Container Solution
Docker packages your application code together with its exact runtime, libraries, binaries, configuration files, and operating system rootfs into a single standardized, portable artifact called a Container Image. If it boots on your laptop, it runs identically on your teammate's computer, in a CI/CD pipeline, and on a Kubernetes production cluster.
2

Virtual Machines vs. Containers: Architecture Breakdown

Developers often confuse containers with lightweight virtual machines. Mechanically, they are fundamentally different:

Diagram 1: Virtual Machines vs. Containers Architecture
Virtual Machines (Heavy)
[ App 1 ]   [ App 2 ]
[ Guest OS (Ubuntu 10GB) ]
[ Hypervisor (Type 1 or 2) ]
[ Host OS & Hardware ]
vs
Docker Containers (Lightweight)
[ App 1 ]   [ App 2 ] (Isolated)
[ Bins / Libs only (50MB) ]
[ Docker Engine ]
[ Shared Host Linux Kernel ]
FeatureVirtual Machines (VMs)Docker Containers
Kernel SharingRuns an independent Guest OS kernel per VMShares host Linux kernel via namespaces & cgroups
Startup TimeMinutes (full OS boot process)Milliseconds to seconds (process launch)
Resource OverheadGigabytes of RAM and disk storage per VMMegabytes (only app dependencies)
Isolation LevelHardware-level hypervisor virtualizationProcess-level isolation (cgroups, pid, net, mnt)
3

The Core Trinity: Image, Container & Registry

To master Docker, you must internalize three foundational concepts that make up the container workflow:

ConceptAnalogyWhat It Actually Is
Docker ImageOOP Class / Blueprint / RecipeAn immutable, read-only package containing code, binaries, runtime, and filesystem layers.
Docker ContainerOOP Object / House / Baked CakeA runnable, isolated process instantiated from an image with a thin, writable top layer.
Docker RegistryGitHub / npm / App StoreA centralized repository for storing and sharing images (e.g. Docker Hub, AWS ECR, GitHub Packages).
Diagram 2: The Universal Docker Workflow
1. Dockerfile
Text instructions
── docker build ──▶
2. Docker Image
Immutable package
── docker run ──▶
3. Container
Active running process
4

Dockerfile Anatomy: Step-by-Step Instructions

A Dockerfile is a plain-text script that contains ordered instructions for Docker Engine to assemble an image. Here is the canonical production structure for a Node.js / Express backend:

Dockerfile (Production Express.js Server)
# 1. Start from an official, hardened lightweight Linux image
FROM node:20-alpine

# 2. Set the working directory inside the container
WORKDIR /app

# 3. Copy dependency manifests FIRST (for layer cache optimization)
COPY package*.json ./

# 4. Install production dependencies cleanly
RUN npm ci --only=production

# 5. Copy the remaining application source code
COPY . .

# 6. Document the listening port for runtime operators
EXPOSE 3000

# 7. Define the default startup command executed when container launches
CMD ["node", "server.js"]
5

⚡ Live Interactive Lab: Dockerfile Layer Caching Simulator

Each instruction in a Dockerfile creates a read-only image layer. When rebuilding an image, Docker checks if the input files for that layer have changed. If not, it uses the cached layer in 0.05 seconds. But as soon as one layer misses the cache, every subsequent layer must be rebuilt from scratch!

Docker Build Cache Engine Simulator
Simulate developer edits and observe which layers hit the cache vs. which layers invalidate and rebuild.
Simulate Code Edit:
Layer 1: FROM node:20-alpine
CACHED (0.01s)
Layer 2: WORKDIR /app
CACHED (0.01s)
Layer 3: COPY package*.json ./
CACHED (0.01s)
Layer 4: RUN npm ci --only=production
CACHED (0.02s - Saved 38s!)
Layer 5: COPY . .
REBUILT (Source copied in 0.12s)
Layer 6: CMD ["node", "server.js"]
METADATA ATTACHED (0.01s)
💡 Takeaway: Because package*.json is copied before COPY . ., code edits skip the slow npm ci step completely!
6

⚡ Live Interactive Lab: Container Lifecycle & State Machine

A container transitions through formal states across its lifecycle: Created ➔ Running ➔ Paused ➔ Stopped ➔ Deleted. Test the transitions interactively:

Live Container State Machine Controller
Current Container Status: RUNNING
Created
➔
Running
⇄
Paused
➔
Stopped
➔
Deleted (rm)
$ docker run -d --name web-api -p 3000:3000 express-app:1.0 [+] Container started with PID 14209 (Listening on port 3000)
7

⚡ Live Interactive Lab: Port Mapping & Container Networking (-p 8080:3000)

By default, containers reside in an isolated network namespace with private IP addresses inaccessible from the host machine. To receive external traffic, you must explicitly bind a host port to the container port using -p <HOST_PORT>:<CONTAINER_PORT>.

Interactive Port Bridge & Packet Router
Configure your host port and test sending a real HTTP request across the Docker bridge.
💻 Your Laptop (Host)
Port:
── -p 8080:3000 ──▶
🐳 Docker Container
Port: 3000 (Internal)
Click "Test Request" to simulate a curl packet from your browser to container.
8

Data Persistence: Docker Volumes vs. Bind Mounts

Containers are ephemeral. Any files written to a container's writable layer are destroyed when the container is deleted. To retain database tables or uploaded media files, Docker provides two persistence models:

FeatureDocker Named VolumeBind Mount
Storage LocationManaged by Docker in host storage (/var/lib/docker/volumes/)Any arbitrary directory on host machine (e.g. $(pwd)/src)
Best Used ForDatabases (Postgres, MySQL, Redis) in productionLocal development hot-reloading
Command Syntax-v postgres_data:/var/lib/postgresql/data-v $(pwd):/app
Running PostgreSQL with a Named Volume
# 1. Create a dedicated storage volume
docker volume create postgres_data

# 2. Attach volume to container data directory
docker run -d --name pg-db \
  -v postgres_data:/var/lib/postgresql/data \
  -e POSTGRES_PASSWORD=mysecret \
  -p 5432:5432 \
  postgres:16-alpine
9

Context Optimization with .dockerignore

When you run docker build ., the Docker client compresses the current directory and sends it to the Docker daemon as the build context. If you forget .dockerignore, you accidentally copy hundreds of megabytes of local node_modules and sensitive files into the build context!

.dockerignore (Essential Production Template)
# Dependency caches (installed inside container instead)
node_modules
npm-debug.log

# Version control
.git
.gitignore

# Security secrets & environment credentials
.env
.env.*

# Miscellaneous documentation and tests
coverage
README.md
10

Multi-Container Orchestration with Docker Compose

Real backend applications rarely exist as a single container. You typically run an Express API, a PostgreSQL database, and a Redis cache. Docker Compose allows you to define and run multi-container applications with a single declarative YAML file.

docker-compose.yml (Backend API + Postgres)
version: '3.8'
services:
  api:
    build: .
    ports:
      - "8080:3000"
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/myapp
    depends_on:
      - db

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: myapp
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

With this file in place, run docker compose up -d. Docker automatically sets up a private bridge network where the api container can communicate with the database simply using the hostname db:5432!

11

5 Dangerous Beginner Traps & How to Solve Them

Trap 1: “localhost” Connecting Between Containers
Problem: Inside a container, localhost means that specific container. If your backend connects to localhost:5432, it fails because Postgres is in a separate container.
Fix: In Docker Compose, use the service name as the hostname: db:5432.
Trap 2: Breaking Layer Caching with “COPY . .” Too Early
Problem: Placing COPY . . before RUN npm install forces Docker to reinstall all packages every time you fix a single typo in code.
Fix: Copy package*.json first, install dependencies, and only then copy application code.
Trap 3: Baking Secrets and .env into Docker Images
Problem: Committing API keys and production database passwords into the image exposes them to anyone who pulls the image.
Fix: Add .env to .dockerignore. Inject secrets at runtime using environment variables (docker run -e KEY=val) or secret managers.
Trap 4: Container Exits Immediately with Code 0
Problem: A container only stays alive as long as its foreground PID 1 process is running. If you launch a background daemon (like service nginx start), the script ends and the container shuts down immediately.
Fix: Keep processes in the foreground (e.g. CMD ["node", "server.js"] or nginx -g "daemon off;").
12

⚡ Live Interactive Lab: Interactive Docker CLI Playground

Practice executing everyday Docker management commands in this simulated production container terminal:

bash - production-server (Docker 24.0.7)
Click preset:
dev@production:~$ docker version
Docker Engine - Community
 Version:           24.0.7
 API version:       1.43
 Go version:        go1.20.10
 OS/Arch:           linux/amd64
13

Industry Production Best Practices & Security

  • Use Alpine or Distroless Base Images: Prefer node:20-alpine (45MB) over the standard node:20 (1GB) to minimize attack surface and network download times.
  • Never Run As Root: Add USER node or a dedicated non-root user in your Dockerfile to prevent privilege escalation if the application is compromised.
  • Pin Specific Version Tags: Avoid using :latest in production. Pin specific immutable versions (e.g. postgres:16.2-alpine) to ensure predictable builds.
  • Implement Docker Healthchecks: Use HEALTHCHECK in Dockerfiles or Docker Compose so container orchestrators can detect and replace unhealthy instances.
  • Adopt Multi-Stage Builds: Build your TypeScript or Go code in an initial build stage, and copy only the compiled binary to the final lean runtime container.
14

What You Should Know Now: Core Checklist

  • ✓Shared Kernel: Containers share the host Linux kernel and isolate processes using namespaces and cgroups.
  • ✓Image vs Container: An image is an immutable read-only blueprint; a container is an active running process instance.
  • ✓Layer Caching: Always copy package manifests and install dependencies before copying application code.
  • ✓Port Mapping: -p 8080:3000 forwards requests from host port 8080 to container port 3000.
  • ✓Persistence: Containers are ephemeral. Persist database records with named Docker volumes.
  • ✓Context Hygiene: Always maintain a comprehensive .dockerignore file.
Knowledge Assessment

Docker Basics Mastery Quiz

Test your understanding of containerization principles, Dockerfile syntax, layer caching, port forwarding, and networking.

Question 1 of 8Score: 0 / 0
Q1: What is the primary architectural difference between a Docker container and a traditional Virtual Machine (VM)?
Previous: Backend Architecture: LoggingNext: Linux Basics for Backend