The Tech Pulse

August 2, 20247 min read
Tags
  • Docker
  • Mcoding
Share

Docker Tutorial for Beginners

One Sentence Summary

A comprehensive Docker overview covering images, containers, layers, mounts, multi-stage builds, Compose orchestration, and deployment patterns for real apps today.

Main Points

  • Images are templates; containers are running instances.
  • Docker layers and caching speed up builds and reuse.
  • Mounts: volumes, bind mounts, tmpfs; volumes persist data.
  • Multi-stage builds reduce final image size and attack surface.
  • Docker Compose orchestrates multi-service apps and networking.
  • Port publishing (-p) exposes services to the host.
  • Avoid hard-coded secrets; use environment variables and secret management.
  • Pin images with digests for stable, reproducible references.
  • Optimize Dockerfile with cached steps; separate copy and install.
  • Store data in volumes; plan registry use for production deployments.

Takeaways

  • Separate images (templates) from containers (live processes) for predictable runs.
  • Favor volumes for production data; use bind mounts for rapid dev iteration.
  • Adopt multi-stage builds and wheel prebuilding to shrink final images.
  • Leverage Docker Compose to manage multi-service stacks and networks.
  • Never store secrets in images; use env files or a secrets manager.

1. Summary

This tutorial provides a complete, hands-on introduction to Docker, focusing on how to build, run, debug, and orchestrate containerized applications. The core problem addressed is environment inconsistency and dependency conflicts across systems, which Docker solves using isolated containers.

Primary technologies covered:

  • Docker / Docker Engine / Docker Desktop
  • Docker Compose
  • NGINX, Python FastAPI, MongoDB
  • Docker Hub (image registry)

The tutorial walks through building a multi-container application (frontend + backend + database), managing persistence, optimizing images, and deploying to registries.


2. Detailed Step-by-Step Breakdown

Step 1: Install Docker

Option A (Recommended for beginners):

  • Install Docker Desktop (includes CLI + GUI)
  • Supports Windows, Mac, Linux

Option B (Advanced):

  • Install Docker Engine (CLI only)

Linux (Ubuntu example):

sudo apt update # Add Docker repo (copy from official docs) sudo apt install docker-ce docker-ce-cli containerd.io

Start Docker daemon:

sudo systemctl start docker

Step 2: Run Your First Container

docker run hello-world
  • Pulls image if not available
  • Creates container from image
  • Executes default command

Check images:

docker image ls

Check containers:

docker ps -a

Step 3: Run a Web Server (NGINX)

docker run -p 80:80 nginx

Key flags:

  • -p host_port:container_port → port mapping

Run in background:

docker run -d -p 80:80 nginx

View logs:

docker logs <container_id>

Stop container:

docker stop <container_id>

Step 4: Images vs Containers

  • Image → blueprint (filesystem + config)
  • Container → running instance

One image → multiple containers


Step 5: Use Tags and Digests

Run specific version:

docker run nginx:1.27

Pin exact image (recommended for production):

docker run nginx@sha256:<digest>

Step 6: Environment Variables & Arguments

docker run -e KEY=value python:3.12-slim \ python -c "import os; print(os.environ)"
  • -e → environment variables
  • Command after image overrides default command

Step 7: Debug Containers

Interactive shell:

docker exec -it <container_id> /bin/bash

Flags:

  • -i → interactive
  • -t → terminal

Step 8: Persistent Storage

Volume (recommended for production)

docker run -v my_volume:/data nginx

Bind Mount (for development)

docker run -v $(pwd)/data:/data nginx

Differences:

  • Volume → managed by Docker
  • Bind mount → maps host filesystem

Step 9: Build Custom Docker Image

Dockerfile:

FROM nginx:1.27 COPY static/ /usr/share/nginx/html RUN rm /usr/share/nginx/html/50x.html

Build:

docker build -t my-nginx .

Run:

docker run -p 80:80 my-nginx

Step 10: Backend (FastAPI) Image

Dockerfile:

FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY src/ . EXPOSE 8000 CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Step 11: Optimize Builds with Caching

Key rules:

  • Changing a layer invalidates all following layers
  • Split dependencies from source code:
COPY requirements.txt . RUN pip install -r requirements.txt COPY src/ .

Step 12: Multi-Stage Builds

FROM python:3.12-slim AS builder COPY . . RUN pip wheel . FROM python:3.12-slim AS runner COPY --from=builder /wheels /wheels RUN pip install /wheels/*

Benefits:

  • Smaller image size
  • No build dependencies in final image

Step 13: Docker Compose (Multi-Container Setup)

docker-compose.yml:

services: backend: build: context: ./backend dockerfile: Dockerfile ports: - "8000:8000" frontend: build: context: ./frontend ports: - "80:80" mongodb: image: mongo:7.0.12 volumes: - mongodb_data:/data/db volumes: mongodb_data:

Run everything:

docker compose up

Stop & remove:

docker compose down

Step 14: Environment Variables via .env

.env file:

MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=example

In compose:

env_file: - ./mongodb/.env

Step 15: Connect Backend to MongoDB

Connection string:

mongodb://root:example@mongodb:27017
  • mongodb → service name (internal DNS)

Step 16: Publish Image to Docker Hub

Tag image:

docker tag my-image username/my-image:1.0

Login:

docker login

Push:

docker push username/my-image:1.0

3. Key Technical Details

  • Port mapping: -p host:container

  • Detach mode: -d

  • Auto-remove container: --rm

  • Interactive shell: -it

  • Volumes vs Bind mounts:

    • Volume → production
    • Bind mount → development
  • Layer caching rules:

    • Change invalidates downstream layers
  • Multi-stage builds: reduce size + improve security

  • Compose networking:

    • Services communicate via service name
  • Security note: Docker runs with root privileges by default


4. Pro Tips

  • Use digest pinning (sha256) for production stability

  • Prefer slim or alpine images for smaller size

  • Always split:

    • dependencies
    • source code
  • Use --no-cache-dir with pip to reduce size

  • Use Docker Compose instead of manual container management

  • Add database UI tools (e.g., Mongo Express) for debugging

  • Use retry logic instead of depends_on for startup ordering


5. Potential Limitations / Warnings

  • Security risks:

    • Containers run as root by default
    • Bind mounts expose host filesystem
  • Alpine Linux differences:

    • Uses musl instead of glibc
    • No bash
    • Different package manager (apk)
  • Secrets handling:

    • Do NOT store secrets in Dockerfile or compose
  • Layer history:

    • Deleted secrets still exist in previous layers
  • Networking issues:

    • CORS problems when frontend/backend use different ports

6. Recommended Follow-Up Resources

  • Official Docker Docs (installation & CLI reference)

  • Docker Hub (image registry exploration)

  • FastAPI documentation (API building)

  • MongoDB docs (data persistence & queries)

  • Cloud container platforms:

    • AWS ECS / EKS
    • Google Cloud Run
    • Azure Container Apps

7. Suggested Books (5)

  1. “Docker Deep Dive” — Nigel Poulton A highly practical guide focused on real-world Docker usage. It explains containers, networking, volumes, and orchestration with clarity, making it ideal for reinforcing the implementation patterns shown in this tutorial.

  2. “The Docker Book” — James Turnbull Covers Docker fundamentals through advanced usage including image building, registries, and deployment pipelines. Especially useful for understanding production workflows and Docker internals.

  3. “Container Security” — Liz Rice Focuses on security aspects of containers, including namespaces, isolation, and vulnerabilities. This directly supports the tutorial’s warnings about root access, layers, and secrets management.

  4. “Kubernetes Up & Running” — Kelsey Hightower et al. While Docker Compose is used here, this book helps you transition to Kubernetes for production orchestration, scaling, and deployment of containerized apps.

  5. “Python Web Development with FastAPI” — Bill Lubanovic A practical guide to building APIs with FastAPI, complementing the backend portion of the tutorial with deeper implementation details and production-ready patterns.

Get New Posts

Follow on your preferred channel for new articles, notes, and experiments.

Related Posts