
--- PDF page 310 ---
UNIT 5 · PROJECT & DEVOPS




       05
       Docker — Build, Ship, Run
       Units 1–4 built an application. This chapter ships it. You will learn why "it works on my ma‐
       chine" happens, how Docker packs an app into an image and runs it as a container, how
       that differs from a virtual machine, how to write a Dockerfile and a compose.yaml, how to
       put the Unit 2 Django project into containers next to PostgreSQL, and how to push, deploy
       and secure it. Every Docker question from past papers is answered in full here, and the
       command tables are built to collect the "write the commands" marks.

          40 marks asked in 2 papers      4 PYQs solved in 2 answer blocks           1 gap filled (G15)      11 drills




1. Why Docker exists                                            10. Docker Compose
2. Containers vs virtual machines                               11. Integrating Django with Docker
3. Under the hood: namespaces, cgroups, OCI                     12. Registries, tagging and CI/CD
4. Docker architecture                                          13. Deployment and security
5. Images: layers, tags, base images                            14. Limitations of Docker (gap)
6. The Dockerfile                                               15. Best practice and debugging
7. Containers: lifecycle and commands                           16. The Docker Lab, level by level
8. Storage: volumes, bind mounts, tmpfs                         17. Master command reference
9. Networking and the localhost trap                            18. Likely questions · Last-minute recap




  ✍️ EXAM RADAR FOR THIS UNIT
    Paper                      Question                                                                    Marks     Answered in

    Re-Exam 2023-24 · Q2(b)    Docker architecture + frequently used Docker commands                       10        §5.7 (end)

    Re-Exam 2023-24 · Q6(b)    Docker vs virtual machine + commands that deal with images                  10        §5.14 (end)

    Final 2024-25 · Q4(b)      Docker architecture + short note on a Docker container                      10        §5.7 (end)

    Final 2024-25 · Q6(b)      Docker vs traditional virtualisation + 3 container commands + limitations   10        §5.14 (end)


  Two facts drive this chapter. (1) Three of the four Docker questions asked for commands , so the com‐
  mand tables in §5.5, §5.7 and §5.17 are worth the most marks. (2) The newest paper (Final 2025-26) asked
  no Docker question at all, but the syllabus line ("Docker CLI Command, Integrate Django with Docker,
  Image, Docker Deployment") has not changed. That paper's style was scenario-based, so expect some‐
  thing like "your Django app works on your laptop but not your friend's: containerise it, write the Dockerfile
  and compose file, explain each line". §5.11 covers exactly that.

--- PDF page 311 ---
5.1 Why Docker exists
📚 Sources: Unit 5 Notes §1–2      LEC 6 (Docker) Block A    Docker Cheatsheet      One-Shot Revision    Complete Revision deck


  🧠 START FROM ZERO
  An application is never just its code. To run, it needs code + a runtime (for example Python 3.12) + li‐
  braries (Django, psycopg2) + operating-system packages (libpq, OpenSSL) + configuration (environ‐
  ment variables, ports). Git ships only the code, so everything else differs from machine to machine. Docker
  ships all five together.



▸ "But it works on my machine!"
The lecture showed the same Git commit producing four different results:

 Machine                     What is installed                                                                   Result

 Your laptop                 Windows 11 · Python 3.12 · Postgres 16 · libpq 16                                   Works

 Teammate                    macOS (Apple M-chip) · Python 3.10 · Postgres 14 · no libpq                          ImportError

 College server              Ubuntu 22.04 · Python 3.8 · no Postgres client · old OpenSSL                        Crashes on boot

 Cloud (production)          Amazon Linux · Python 3.11 · different env vars · port 80 not 8000                  502 Bad Gateway


The problem appears even on one laptop. A final-year project needs Django 3.2 + Python 3.8 + PostgreSQL 12,
and an internship project needs Django 5.2 + Python 3.12 + PostgreSQL 16. You cannot install both side by side
in the normal way. This is called dependency hell.


▸ Why the usual fixes fall short

  Usual fix                      What it isolates                      Where it falls short

  venv / conda                   Python packages only                  Not PostgreSQL, not system libraries, not the OS

  README "setup steps"           Nothing, it is documentation          Goes out of date; step 7 always fails on Windows

  Virtual machine                Everything                            Gigabytes of disk, minutes to boot, one app per VM

  Container                      Everything the app needs              Megabytes, starts in about a second, dozens per laptop


You want the isolation of a VM at the cost of a venv . That is what a container gives you.


▸ The definition to write in the exam

  🔑 DEFINITION — LEARN WORD FOR WORD
  Docker is an open-source platform that packages an application with everything it needs to run (code, run‐
  time, libraries, OS files and configuration) into a standard, portable unit called an image, and runs that im‐
  age as an isolated process called a container.

--- PDF page 312 ---
Docker's own cheat sheet puts it the same way: Docker packages and runs an application in a "loosely isolated
environment" called a container, the isolation lets you run many containers on one host, and everyone you share
a container with gets one that behaves identically.

  💡 THINK OF IT LIKE THE SHIPPING CONTAINER (1956)
  Before 1956, cargo was loaded by hand, sack by sack and barrel by barrel. A ship could take a week to
  load. Then one standard steel box arrived, and every crane, ship, train and truck handled it the same way
  without caring what was inside. Loading cost fell from about $5.86 to $0.16 per ton.

    Shipping                                     Software

    The cargo                                    Your app + Python + libraries + config

    The standard steel box                       A container image (the OCI standard)

    Ship, train, truck                           Laptop, college server, AWS, Azure, GCP

    The port crane                               The Docker Engine

    "Don't care what's inside"                   Docker runs Python, Java, Node or Go the same way




▸ Six reasons every team uses containers

  Benefit                What it means

  Consistency            The same image runs on your laptop, in CI and in production: "works on my machine" becomes
                         "works on every machine".

  Speed                  No OS to boot. In the lab an Alpine container started, ran a command and exited in 0.7 s.

  Density                Containers share one kernel, so a laptop runs dozens where it could manage only 2–3 VMs.

  Isolation              Each app has its own Python, its own libraries and its own Postgres version, with no conflicts.

  Ecosystem              Docker Hub has official images for postgres, redis, nginx, python, node and thousands more, one pull
                         away.

  Cloud-native           Kubernetes, CI/CD pipelines, AWS Fargate, Google Cloud Run and Azure Container Apps all run con‐
  base                   tainer images.



  DOCKER IS…                                                          DOCKER IS NOT…

       an image format and a builder ( docker                              a virtual machine (no guest OS boots)
       build )                                                             a programming language or a framework
       a runtime that starts containers ( docker run )                     a replacement for Git, or for the venv in your
       a registry ecosystem (Docker Hub)                                   editor
       tooling: Compose, Desktop, Scout, buildx                            as strong a security wall as a VM, by default

--- PDF page 313 ---
▸ Ten words you must know

 Term                   Plain meaning

 Image                  Read-only template (layers + config) that contains the app and everything it needs. Like a class.

 Container              A running (or stopped) instance of an image, an isolated process. Like an object.

 Dockerfile             Text recipe, one instruction per line, that builds an image.

 Docker Engine          The daemon ( dockerd ) + its REST API + the docker CLI client.

 Registry               Server that stores and shares images (Docker Hub, GHCR, Amazon ECR).

 Tag                    Label after the colon, e.g. python:3.12-slim . Movable.

 Volume                 Docker-managed storage that outlives containers. Databases live here.

 Network                Virtual switch; containers on the same user-defined network reach each other by name.

 Compose                Tool that starts a multi-container stack from one compose.yaml .

 Docker Desktop         The Windows/macOS app that runs a hidden Linux VM with the Docker Engine inside it.



  🔑 MEMORY HOOK — BUILD, SHIP, RUN
  Build an image ( docker build ) → Ship it through a registry ( docker push / docker pull ) → Run it
  anywhere as a container ( docker run ). This chapter's title is the whole workflow.




    5.2 Containers vs virtual machines
📚 Sources: Unit 5 Notes §3      LEC 6 (Docker) Block B     One-Shot Revision      Complete Revision deck


Both give you isolation, at very different costs. A virtual machine virtualises the hardware: each VM boots its
own complete operating system with its own kernel, on top of a hypervisor. A container virtualises the oper‐
ating system (the user space): every container shares the host's single kernel and ships only its own files.


▸ What "traditional virtualisation" means
The 2024-25 paper says "traditional virtualization". That means hypervisor-based virtualisation, i.e. virtual ma‐
chines. A hypervisor is the software layer that creates and runs VMs by giving each one virtual CPU, RAM, disk
and network hardware. Your lecture names three hypervisors: Hyper-V, VirtualBox and KVM. Standard textbooks
split them into two types, a useful extra line in a 10-mark answer:

 Hypervisor type           Runs on                                                     Examples

 Type 1 (bare-metal)       Directly on the hardware, no host OS underneath             VMware ESXi, Microsoft Hyper-V, KVM, Xen

 Type 2 (hosted)           As an application on top of a normal host OS                Oracle VirtualBox, VMware Workstation

--- PDF page 314 ---
Virtual machines (traditional virtualisation)                                       Containers (OS-level virtualisation)


               each VM boots its own OS: gigabytes, minutes                                     no guest OS: megabytes, about a second

             App A                      App B                   App C


           Bins / libs                Bins / libs             Bins / libs                   App A                    App B                  App C

           Guest OS                  Guest OS                 Guest OS
           (full kernel)             (full kernel)            (full kernel)               Bins / libs              Bins / libs             Bins / libs


                   Hypervisor (Hyper-V, VirtualBox, KVM)                                            Docker Engine (container runtime)


                               Host operating system                                                    Host OS: ONE shared kernel


                           Infrastructure: CPU · RAM · disk                                             Infrastructure: CPU · RAM · disk




                              Figure 5.1 — The red "Guest OS" row is the cost you pay for every VM. Containers do not have it.



▸ Side by side

  Point                             Virtual machine                                        Container (Docker)

  What is virtualised               The hardware                                           The operating system (user space)

  Kernel                            Its own, one per VM                                    Shared with the host

  Software layer                    Hypervisor                                             Docker Engine (container runtime)

  Typical size                      Gigabytes                                              Megabytes: alpine 12 MB, the lab app 235 MB

  Start time                        Tens of seconds to minutes                             Milliseconds to a couple of seconds

  How many per                      2–3                                                    Dozens (hundreds on a server)
  laptop

  Isolation                         Strong: hardware-level                                 Process-level: namespaces + cgroups

  Different                         Yes, e.g. Windows on a Linux host                      No, Linux containers need a Linux kernel
  OS/kernel?

  Resource use                      Fixed RAM/CPU reserved per VM                          Uses only what the process needs

  Packaging                         Large VM disk images, hard to version                  Small layered images, versioned by tag, shared via
                                                                                           registries

  Best for                          Different OSes, legacy apps, hard multi-               Packaging and shipping apps, microservices, CI
                                    tenancy



▸ A container is just a process
This is the key insight of the lecture. On a Linux host, start nginx in a container and look at the host's process
list:

--- PDF page 315 ---
terminal — on a Linux host (LEC 6 slide 14)


  $ docker run -d --name web nginx:alpine
  $ ps -ef | grep nginx                           # seen from the HOST
  root      48211   ...   nginx: master process nginx
  101       48260   ...   nginx: worker process
  $ docker exec web ps                            # the same process seen from INSIDE
  PID       USER    COMMAND
     1      root    nginx: master process
    30      nginx nginx: worker process



    The host sees an ordinary process (PID 48211).
    Inside, the same process believes it is PID 1, with its own hostname, network and filesystem.
    No guest OS boots, so it starts as fast as any program. When the main process exits, the container stops.

  🧠 IT IS NOT EITHER/OR
  In the cloud, your containers usually run inside VMs. The VM keeps different customers apart (strong isola‐
  tion), and containers pack each customer's apps efficiently (density). Write this as your conclusion line in
  any "Docker vs VM" answer.



▸ Docker on Windows and macOS
Linux containers need a Linux kernel. Windows and macOS do not have one, so Docker Desktop quietly runs
a small Linux VM (WSL2 on Windows, Apple Virtualization on a Mac) and runs the Docker Engine and your con‐
tainers inside it. The lab proved it with the same script:

            terminal — measured on a Windows 11 lab machine


  $ python hello.py
     Operating system : Windows 11
  $ docker run --rm hello-docker
     Operating system : Linux 6.6.87.1-microsoft-standard-WSL2



    CPU architecture matters too. Apple M-series Macs and Raspberry Pi are arm64 ; most servers are
     amd64 . An image built for one fails on the other with exec format error (fix in §5.12).

    Windows containers exist (they need a Windows Server kernel) but are rare.

  ⚠️ COMMON MISTAKES
         "Docker is a lightweight VM." No: no guest OS boots and there is no hypervisor per container. Say "OS-
         level virtualisation" or "containerisation".
         "Containers are more secure than VMs." The reverse: containers share the host kernel, so their isolation
         is weaker (§5.14).
         "A Windows app can run in a Linux container." No: a container cannot bring its own kernel.

--- PDF page 316 ---
The complete 10-mark model answer for "Docker vs VM / traditional virtualisation" is at the end of §5.14, because both papers com‐
bined it with commands and limitations, which you learn first.




    5.3 Under the hood: namespaces, cgroups, OCI
📚 Sources: LEC 6 (Docker) Block C           Unit 5 Notes §3   Docker Lab L0


A container is a normal Linux process that the kernel restricts (what it can see) and limits (what it can use).
Docker ties together three Linux kernel features: namespaces, control groups (cgroups) and a layered
filesystem.


▸ Namespaces control what a process can SEE

 Namespace               Isolates                                      Inside the container you see…

  pid                    Process IDs                                   Your app is PID 1; host processes are invisible

  net                    Interfaces, IPs, ports, routes                Your own eth0 and IP (e.g. 172.18.0.2)

  mnt                    Mount points                                  The image's files as / , not the host's disk

  uts                    Hostname                                      Hostname = container ID (e.g. e4ec22ada128 )

  ipc                    Shared memory, semaphores                     A private IPC space

  user                   User and group IDs                            root inside can map to an unprivileged user outside

  cgroup                 cgroup tree view                              Only your own resource limits


           terminal — the whole visible world is one process


  $ docker run --rm ubuntu:24.04 ps -e
     PID TTY                  TIME CMD
         1 ?            00:00:00 ps




▸ Control groups limit what a process can USE

           terminal — measured in the lab


  $ docker run -d --name api \
         --memory 256m \
         --cpus 0.5 \
         --pids-limit 100 \
         campuspulse:v1
  $ docker stats --no-stream
  NAME                     MEM USAGE / LIMIT
  pulseprod-web-1          52.06MiB / 256MiB



 Resource         Flag                                        Effect

 CPU                --cpus 0.5                                At most half a core

--- PDF page 317 ---
Resource         Flag                                       Effect

 Memory             --memory 256m                            Going over the limit gets the process OOM-killed: exit code 137

 Processes          --pids-limit 100                         Stops fork bombs

 Block I/O          --device-read-bps etc.                   Throttles disk reads and writes


Result: one noisy container cannot slow down the others.


▸ The layered filesystem
The third ingredient: an image is a stack of read-only layers, and each container adds one thin writable layer on
top. The kernel's union filesystem (Docker's default storage driver is overlay2 ) shows the stack as one normal
directory tree. Details in §5.5.


▸ OCI: why your image runs anywhere
The Open Container Initiative (OCI, 2015) turned Docker's formats into open standards, so you can build with
Docker and run with anything (Podman, containerd, CRI-O, Kubernetes, AWS Lambda), with no vendor lock-in.

 OCI spec               Defines

 Image spec             What an image is: layer tarballs + a JSON config (env, cmd, user) + a manifest listing them by sha256 digest

 Runtime spec           How to run an unpacked image: the process, mounts, namespaces and cgroups. runc is the reference
                        implementation

 Distribution           The HTTP API for push and pull. Docker Hub, GHCR, ECR and Harbor all speak it
 spec



  🔑 MEMORY HOOK
  Namespaces = what you can SEE · cgroups = what you can USE · layers = what you are MADE of.
  OCI = the standard that makes the box fit every crane.




    5.4 Docker architecture: client, daemon, registry
📚 Sources: Unit 5 Notes §4        LEC 6 (Docker) Block D     Docker Lab L0     Docker Cheatsheet     One-Shot Revision

 Complete Revision deck


Docker uses a client–server architecture spread across three places. The docker command you type does
almost nothing by itself: the client asks, the daemon works, the registry stores .

--- PDF page 318 ---
DOCKER HOST
             CLIENT                                                                                                        REGISTRY
                                  REST API              dockerd — the Docker daemon
           the docker CLI                                                                                             stores & shares images
                                                  builds images · runs containers · storage · networks
                                   socket                                                                  pull
          docker build                                                                                                     Docker Hub

          docker pull                                 Images                         Containers                               ghcr.io
           docker run                           python:3.12-slim                         web-1             push            Amazon ECR
                                                                            run
          docker push                              postgres:16                            db-1                                Harbor

     docker compose up                            campuspulse:v1                        cache-1
                                                  read-only templates                running instances

        only sends requests                                                                                             e.g. postgres, nginx
                                                                 Volumes · Networks


                                                  containerd → runc: sets up namespaces + cgroups



 Figure 5.2 — Docker architecture: the client sends requests to the daemon over a REST API; the daemon manages images, containers, volumes
                                               and networks, and pulls from / pushes to a registry.



▸ The components

  Component                 What it is and does                                                                   Examples

  Docker client             The docker command-line tool. It turns what you type into REST API                     docker build , dock‐
                            calls and sends them to a daemon (local, or remote over a socket/TCP).                er run , docker pull
                            One client can talk to many daemons.

  Docker host               The machine running the daemon. It holds the local image cache, the                   Your laptop (inside
                            containers, volumes and networks.                                                     Desktop's Linux VM), a
                                                                                                                  server, a droplet

  Docker daemon             Background service that does the real work: builds images, pulls/push‐                Started by Docker Desktop
  ( dockerd )               es them, creates, starts and stops containers, manages storage and                    or systemctl start
                            networks. Listens on /var/run/docker.sock .                                           docker

  Docker objects            The nouns the daemon manages: images, containers, volumes, net‐                       See the next table
                            works (plus Compose projects).

  Registry                  Server that stores and distributes images. Public or private. docker                  Docker Hub (default),
                            pull downloads from it, docker push uploads to it.                                    GHCR, Amazon ECR,
                                                                                                                  Harbor


Docker Engine = the daemon + its REST API + the CLI client. Inside the host (an extra-marks detail): dockerd
hands containers to containerd (manages the container lifecycle), which calls runc (the OCI runtime) to create
the namespaces and cgroups and start the process.


▸ The six nouns you use every day

 Object                       What it is

 Image                        A read-only template: layers + config. Built from a Dockerfile, identified by name:tag .

--- PDF page 319 ---
Object                     What it is

 Container                  A running (or stopped) instance of an image, with its own writable layer.

 Volume                     Storage managed by Docker that outlives containers. Databases live here.

 Network                    A virtual switch. Containers on the same network reach each other by name.

 Registry                   A server that stores and serves images: Docker Hub, GHCR, ECR…

 Compose project            Services, networks and volumes declared together in compose.yaml .



  IMAGE                                                                      CONTAINER
  Read-only template, built once from a Dockerfile.                          A running (or stopped) instance of an image with a
  Immutable: "changing" it produces a new image.                             thin writable layer. Disposable: delete it and start
  Stored in a registry and in the local cache. Like a                        another. Many containers from one image. Like an
  class.                                                                     object.



▸ What happens when you type docker run

            the command we trace


  $ docker run -d -p 8080:80 --name web nginx:alpine



 1         CLI → daemon. The client sends a "create + start" request to dockerd over the REST API.

 2         Image lookup. The daemon checks whether nginx:alpine is already in its local image cache.

 3         Pull. If not, it downloads each missing layer from Docker Hub, by digest.

 4         Create. It stacks the read-only layers, adds a thin writable layer on top and records the config (name
            web , env, ports).


 5         Network. It gives the container a virtual network interface and IP, and maps host port 8080 → container
           port 80.

 6         Start. runc builds the namespaces and cgroups and starts nginx as PID 1.

 7         Detach. Because of -d , the CLI prints the container ID and returns. Logs are available with
            docker logs web .


Measured in the lab: an Alpine container went from start to exit in 0.7 s.


THE VERY FIRST COMMAND OF THE LAB, EXPLAINED

            terminal — Docker Lab L0, step 1


  $ docker run hello-world
  Unable to find image 'hello-world:latest' locally
  latest: Pulling from library/hello-world

--- PDF page 320 ---
Hello from Docker!
  This message shows that your installation appears to be working correctly.
  $ docker ps                # nothing: it already exited
  $ docker ps -a             # there it is, status Exited (0)
  $ docker images            # the image stays in the cache (26 kB)



Four things happened: the CLI asked the daemon to run hello-world ; it was not in the local cache, so it was
pulled from Docker Hub; a container was created and started; its output was streamed to your terminal and it
exited. The container still exists (Exited) and the image stays cached.


▸ The three verbs and where they act

 Verb                              Client sends              Daemon does                                     Registry

  docker build -t                  The build context         Runs the Dockerfile, creates layers, tags the   Pulls the base image if
 app:1.0 .                         (folder)                  image                                           missing

  docker run app:1.0               Create + start request    Creates a container from the image and          Pulls the image if missing
                                                             starts it

  docker push                      Push request              Uploads the layers the registry does not        Stores the image
 you/app:1.0                                                 have



  ⚠️ CHEAT-SHEET CORRECTION: "DOCKER -D"
  Your Docker cheat sheet lists docker -d as "start the docker daemon". That syntax is from very old
  Docker versions. Today the daemon is a separate program, dockerd . On Windows and macOS you simply
  start Docker Desktop (the whale icon); on a Linux server it is sudo systemctl start docker . If you see
  "Cannot connect to the Docker daemon", the daemon is not running. In the exam you may write "start the
  daemon: dockerd (old form docker -d )".


  ✍️ HOW TO DRAW THE ARCHITECTURE IN THE EXAM (2 MINUTES)
  Draw three boxes left to right: Client (list build / pull / run), Docker Host (a daemon bar on top; inside it two
  boxes, Images → Containers; a strip for Volumes · Networks), Registry (Docker Hub). Arrow client → dae‐
  mon labelled "REST API". Two arrows between host and registry labelled "pull" and "push". That diagram
  alone is worth 2–3 marks. The full written answer is the PYQ block at the end of §5.7.




    5.5 Images: layers, tags and base images
📚 Sources: Unit 5 Notes §5.1–5.3    LEC 6 (Docker) Block E     Docker Lab L2     Docker Cheatsheet      Complete Revision deck


An image is a lightweight, standalone, executable package of software: code, runtime, system tools, system li‐
braries and settings (that is how the cheat sheet defines it). Technically it is a stack of read-only layers + a
small JSON config + a manifest.

--- PDF page 321 ---
▸ Anatomy: layers + config + manifest

            terminal — real output from the lab


  $ docker history campuspulse:v1
  SIZE         CREATED BY
  0B           CMD ["gunicorn" "--bind" "0.0.0.0:8000" …]
  0B           EXPOSE 8000/tcp
  36.9kB       COPY . .
  35MB         RUN pip install --no-cache-dir -r …
  12.3kB       COPY requirements.txt .
  8.19kB       WORKDIR /app
  …            (python:3.12-slim base layers)



 Part          What it is

 Layers        Tarballs of file changes, one per filesystem-changing instruction ( RUN , COPY , ADD )

 Config        JSON with env vars, CMD , WORKDIR , USER , exposed ports. CMD and EXPOSE show as 0 B: metadata only

 Manifest      Lists the layers by sha256 digest




                container A                 container B               container C       one thin writable layer
                writable layer              writable layer             writable layer   per container


                                  COPY . . — 36.9 kB (your code)

                                    RUN pip install … — 35 MB

                                                                                        IMAGE: read-only,
                                 COPY requirements.txt . — 12.3 kB
                                                                                        shared by all containers

                                    WORKDIR /app — 8.19 kB


                       python:3.12-slim base layers (Debian + Python)


          CMD and EXPOSE add no layer (0 B): they only record settings in the config.


 Figure 5.3 — Three containers from one image share every read-only layer. Each has only its own writable layer, which docker rm deletes.


      Content-addressed: layers are identified by a hash of their content, so identical layers are shared between
      images and cached instead of downloaded twice.
      Immutable: you never edit an image; a "change" produces a new image.
      Only RUN , COPY and ADD add size. When an image is too big, those layers are where to look.


▸ Reading an image name

 Part                      Example                            Meaning                           Default

 Registry                   ghcr.io                           Server that holds it               docker.io (Docker Hub)

 Namespace                  /snehe                            User or organisation               library (official images)

 Repository                 /campuspulse                      The image's name                  (required)

--- PDF page 322 ---
Part                   Example                    Meaning                                 Default

 Tag                    :1.2.0                     Mutable label                            latest

 Digest                 @sha256:9f3c…              Immutable content hash                  —



 You type                                             Docker reads it as

  nginx                                                docker.io/library/nginx:latest

  postgres:16-alpine                                   docker.io/library/postgres:16-alpine

  snehe/campuspulse:1.0                                docker.io/snehe/campuspulse:1.0

  ghcr.io/org/app@sha256:…                            Exactly that content, forever



▸ "latest" is not a version
A tag is only a pointer that the publisher can move to new content at any time. latest simply means "what‐
ever was pushed most recently". A real bug from preparing the lab:

            terminal — the lab's own bug


  FROM python:latest              # worked when the file was written
  …
  $ docker run --rm python:latest python --version
  Python 3.14.7                   # 'latest' moved on
  $ docker build -f Dockerfile.broken .
  ERROR: Could not find a version that satisfies the
            requirement psycopg-binary==3.2.9
            (from versions: 3.2.10, …, 3.3.5)



Pinned requirements + an unpinned base image = a time bomb. Pin at least major.minor: python:3.12-slim .
For fully reproducible builds, pin the digest: python:3.12-slim@sha256:… . The same Dockerfile should build
the same image next year.


▸ Choosing a base image

 Image (measured in the lab)       Size      Flavour · use when

  python:3.12                      1.62 GB   full — you need compilers, and only in a build stage

  python:3.12-slim                 190 MB    slim — the default choice for Python/Node apps

  ubuntu:24.04                     119 MB    a general Linux userland for experiments

  nginx:alpine                     103 MB    web server on Alpine

  alpine:3.20                      12.2      alpine — tiny, but uses musl libc, so some Python wheels do not install cleanly
                                   MB

  gcr.io/distroless/…              small     distroless — production images with no shell or package manager, very little to
                                             attack

  hello-world (FROM                26 kB     scratch — static binaries (Go, Rust): the image is just your file
 scratch)

--- PDF page 323 ---
The lab built the same app twice: 1.65 GB on python:3.12 , 235 MB on python:3.12-slim , seven times
smaller with identical code.


▸ Commands that deal with images
The complete table (command, what it does, important flags, example) is §5.17-B; the exam-sized version is
Part 2 of the PYQ answer at the end of §5.14. The everyday ones: docker build -t app:1.0 . ·
 docker images · docker pull · docker tag · docker push · docker rmi · docker image prune ·
 docker history .


   ✏️ DRILL 1 · WHICH IMAGE COMMAND?
    1. You edited app.py ; build a new image called campuspulse:v2 →
    2. Find out which layer makes the image 1.65 GB →
    3. Rename campuspulse:v1 as asha/campuspulse:1.0 for Docker Hub →
    4. Upload it →
    5. Download PostgreSQL 16 (Alpine) without running it →
    6. Rebuild ignoring every cached layer →
    7. Delete the fat image →
    8. Free disk used by untagged images →

   🔓 Answer key: 1) docker build -t campuspulse:v2 . 2) docker history campuspulse:fat 3)
    docker tag campuspulse:v1 asha/campuspulse:1.0 4) docker push asha/campuspulse:1.0 5)
    docker pull postgres:16-alpine 6) docker build --no-cache -t campuspulse:v1 . 7)
    docker rmi campuspulse:fat 8) docker image prune




    5.6 The Dockerfile, instruction by instruction
📚 Sources: Unit 5 Notes §5.4   LEC 6 (Docker) Block F   Docker Lab L1, L2, L6   Unit 3 Notes §9.2    One-Shot Revision


A Dockerfile is the recipe for an image: a plain text file named Dockerfile , one instruction per line, executed
top to bottom. A typical one starts FROM a base image, sets a WORKDIR , COPY s files in, RUN s commands
such as installing packages, and ends with the CMD the container runs.

--- PDF page 324 ---
▸ Your first image (Lab Level 1)


              level1-hello/hello.py                                         level1-hello/Dockerfile


     import os                                                       FROM python:3.12-slim
     import platform                                                 WORKDIR /app
     import socket                                                   COPY hello.py .
                                                                     ENV NAME=docker-learner
     name = os.environ.get("NAME", "engineer")                       CMD ["python", "hello.py"]
     print(f"Hello, {name}!")
     print(f"      Operating system : {platfor‐                 Five lines: a base, a folder, a file, a default setting and a
     m.system()} {platform.release()}")                         command.

     print(f"      Python version     : {platfor‐
     m.python_version()}")
     print(f"      Hostname           : {socket.geth‐
     ostname()}")
     print(f"      Working directory:
     {os.getcwd()}")




           terminal — build, run, override


  $ docker build -t hello-docker .                      # -t names (tags) the image; . = build context
  $ docker run --rm hello-docker
  Hello, docker-learner!
     Operating system : Linux 6.6.87.1-microsoft-standard-WSL2
     Python version       : 3.12.14
     Hostname             : d085f094d73e                 # = the container ID
     Working directory: /app
  $ docker run --rm -e NAME=Priya hello-docker
  Hello, Priya!                                          # -e overrides ENV at run time




▸ The real app's Dockerfile, line by line (Lab Level 2)

           campuspulse/Dockerfile


  FROM python:3.12-slim
  WORKDIR /app
  # dependencies first: this layer is cached until requirements.txt changes
  COPY requirements.txt .
  RUN pip install --no-cache-dir -r requirements.txt
  # source code last: it changes most often
  COPY . .
  EXPOSE 8000
  CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "--access-logfile", "-", "app:app"]

--- PDF page 325 ---
Line                                                      Why it is written this way

  FROM python:3.12-slim                                    Official, pinned, slim base: Debian + Python 3.12

  WORKDIR /app                                             Every later path is relative to /app (created if missing)

  COPY requirements.txt .                                  Copy only the dependency list, so the pip layer stays cached

  RUN pip install --no-cache-dir -r                        Install packages; --no-cache-dir keeps the layer small
 requirements.txt

  COPY . .                                                 Now copy the code, the part that changes most

  EXPOSE 8000                                              Documents the port. It publishes nothing: that is -p

  CMD ["gunicorn", …]                                      Default command in exec form. Binds 0.0.0.0, not localhost. gunicorn is a pro‐
                                                           duction server; flask run is not




               requirements.txt                                                           .dockerignore


     flask==3.1.1                                                               .git
     gunicorn==23.0.0                                                           venv/
     psycopg[binary]==3.2.9                                                     __pycache__/
     redis==6.2.0                                                               .env
                                                                                *.db
                                                                                Dockerfile*
                                                                                compose*.yaml




▸ Every instruction you need

                                                                               Adds
 Instruction            What it does                                                        Example
                                                                               size?

 FROM                   Base image. Every Dockerfile starts here ( AS          base          FROM python:3.12-slim AS builder
                        name names a stage)                                    layers

 WORKDIR                Sets (and creates) the working directory               tiny          WORKDIR /app

 COPY                   Copies files from the build context into the image     yes           COPY requirements.txt .

 ADD                    Like COPY, but also unpacks local .tar files and       yes           ADD site.tar.gz /srv/
                        fetches URLs. Prefer COPY

 RUN                    Runs a command at build time and saves the re‐         yes           RUN pip install -r
                        sult as a layer                                                     requirements.txt

 ENV                    Environment variable, available at build and run       no            ENV PYTHONUNBUFFERED=1
                        time

 ARG                    Build-time variable only ( --build-arg ), gone         no            ARG PY_VERSION=3.12
                        at run time

 CMD                    Default command or arguments at run time.              no            CMD ["gunicorn", "app:app"]
                        Replaced by anything after the image name

 ENTRYPOINT             The fixed executable. CMD becomes its default          no            ENTRYPOINT ["ping", "-c", "3"]
                        arguments

--- PDF page 326 ---
Adds
 Instruction            What it does                                                      Example
                                                                                 size?

 EXPOSE                 Documents the listening port (publishing needs -         no         EXPOSE 8000
                        p )

 USER                   Runs everything after it (and the container) as this     no         USER appuser
                        user

 HEALTHCHECK            A command Docker runs regularly to mark the              no         HEALTHCHECK CMD curl -f http://lo‐
                        container healthy/unhealthy                                       calhost:8000/health || exit 1

 VOLUME                 Marks a path as a mount point for persistent data        no         VOLUME /var/lib/postgresql/data

 LABEL                  Metadata key=value (author, version, source repo)        no         LABEL
                                                                                          org.opencontainers.image.title=puls
                                                                                          e



▸ Order matters: the layer cache
Docker reuses a cached layer as long as that instruction, the files it copies, and everything before it are
unchanged. Once one layer changes, every later layer is rebuilt. Code changes on nearly every build; depen‐
dencies rarely do. So copy and install dependencies first, copy the code last .


  GOOD ORDER (1.0 S REBUILD)                                                   BAD ORDER (5.4 S REBUILD)

               Dockerfile                                                                Dockerfile.slow


      COPY requirements.txt .                                                    COPY . .
      RUN pip install --no-cache-dir -r require‐                                 RUN pip install --no-cache-dir -r
      ments.txt                                                                  requirements.txt
      COPY . .

                                                                                         build output after editing app.py

               build output after editing app.py
                                                                                 => [3/4] COPY . .
      => CACHED [3/5] COPY requirements.txt .                                    => [4/4] RUN pip install …         # reinstalls
      => CACHED [4/5] RUN pip install …                                          EVERYTHING
      => [5/5] COPY . .




On campus Wi-Fi the bad order re-downloads every package on every build.


▸ The build context and .dockerignore

           terminal


  $ docker build -t campuspulse:v1 .
  #                                                ^ the BUILD CONTEXT: this whole folder is packed up and sent to
  the builder



      Only files inside the context can be COPY -ed.

--- PDF page 327 ---
Without .dockerignore , COPY . . ships your venv (hundreds of MB), the .git history and the .env
    file with its passwords into the image.
    A smaller context means faster builds and fewer cache misses. The syntax is the same as .gitignore .


▸ The look-alikes examiners love

CMD VS ENTRYPOINT

ENTRYPOINT = the program. CMD = its default arguments. Anything typed after the image name replaces
CMD; --entrypoint replaces ENTRYPOINT.

                                                                 docker run                     docker run pinger
 Dockerfile has…
                                                                pinger                        google.com

  CMD ["ping","localhost"]                                      ping localhost                tries to run google.com as a pro‐
                                                                                              gram: error

  ENTRYPOINT ["ping","-c","3"]                                  ping -c 3: error, no host     ping -c 3 google.com
                                                                given

  ENTRYPOINT ["ping","-c","3"] + CMD                            ping -c 3 localhost           ping -c 3 google.com
 ["localhost"]


            terminal — Lab Level 1, Dockerfile.entrypoint


  $ docker build -f Dockerfile.entrypoint -t pinger .                     # -f picks a Dockerfile with another name
  $ docker run --rm pinger                                # ping -c 3 localhost
  $ docker run --rm pinger google.com                     # replaces CMD only
  $ docker run --rm --entrypoint echo pinger hi
  hi                                                      # replaces ENTRYPOINT



 Pair             First                                        Second                               Rule

 COPY vs          COPY copies local files, nothing else        ADD also auto-extracts local         Use COPY; ADD only when you
 ADD                                                           .tar.gz files and can download       want the tar unpacked
                                                               URLs

 ARG vs ENV       ARG exists only while building ( --build-    ENV is baked into the image and      Neither is safe for secrets: both
                  arg )                                        seen by the running app              show in docker
                                                                                                    history / inspect

 RUN vs           RUN executes at build time and creates a     CMD executes when a contain‐         Install with RUN; start the app with
 CMD              layer                                        er starts; it only records a         CMD
                                                               default

 EXPOSE vs        EXPOSE documents a port in the image          -p 8000:8000 actually pub‐          EXPOSE alone makes nothing
  -p                                                           lishes it on the host                reachable

 Shell vs          CMD gunicorn app:app runs via                CMD ["gunicorn",                    Use exec form (JSON array) so
 exec form         /bin/sh -c ; the app is not PID 1 and       "app:app"] runs the app di‐           docker stop shuts it down
                  misses SIGTERM                               rectly as PID 1                      cleanly


            ARG and ENV in practice (LEC 6 slide 39)

--- PDF page 328 ---
ARG PY_VERSION=3.12
  FROM python:${PY_VERSION}-slim             # docker build --build-arg PY_VERSION=3.13 .
  ENV PYTHONUNBUFFERED=1                     # logs appear immediately in docker logs
  ENV PORT=8000                              # the app reads os.environ['PORT']




▸ Multi-stage builds: build with the big tools, ship without them
One stage has all the build tools; a second, slim stage copies in only the finished result with
 COPY --from=builder , so compilers never reach production. This is the lab's Dockerfile.prod :

           campuspulse/Dockerfile.prod (Lab Level 6)


  # ---- stage 1: builder (pip lives here, then gets thrown away)
  FROM python:3.12-slim AS builder
  RUN python -m venv /opt/venv
  ENV PATH="/opt/venv/bin:$PATH"
  COPY requirements.txt .
  RUN pip install --no-cache-dir -r requirements.txt


  # ---- stage 2: runtime (only the finished venv crosses over)
  FROM python:3.12-slim
  ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 \
        PATH="/opt/venv/bin:$PATH"
  RUN useradd --create-home --uid 10001 appuser \
    && mkdir /data && chown appuser /data
  WORKDIR /app
  COPY --from=builder /opt/venv /opt/venv
  COPY --chown=appuser:appuser . .
  USER appuser
  EXPOSE 8000
  # slim has no curl, so the healthcheck uses Python
  HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
      CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health',
  timeout=2)"
  CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "app:app"]



 Language               Builder image      Final image

 Go                     golang (~800 MB)   scratch + binary (~10–20 MB)

 React / Vue            node (~1 GB)       nginx + static files (~50 MB)

 Python (the lab)       slim: 235 MB       239 MB: no size win, but a cleaner, safer runtime with no build tools

--- PDF page 329 ---
▸ docker build flags

 Flag                   Meaning                                                    Example

  -t name:tag           Name (tag) the image; repeatable                            docker build -t app:1.0 -t app:latest
                                                                                   .

  -f file               Use a Dockerfile with another name                          docker build -f Dockerfile.prod -t
                                                                                   app:prod .

  --no-cache            Ignore all cached layers                                    docker build --no-cache -t app:1.0 .

  --build-arg           Set an ARG value                                            --build-arg PY_VERSION=3.13
 K=V

  --target              Stop at a named stage                                       --target builder
 stage

  --platform            Build for another CPU architecture                          --platform linux/amd64

  -f -                  Read the Dockerfile from standard input (the lab's          docker build -t campuspulse:fat -f -
                        "fat" experiment)                                          . <<'EOF'

  . (last               The build context folder                                   always required
 argument)



   ✏️ DRILL 2 · COMPLETE THE DOCKERFILE
   Fill the blanks so the image is small, rebuilds fast after a code edit, and is reachable from the laptop.

              Dockerfile (blanks)


     ______ python:3.12-slim                                            # (1)
     ______ /app                                                        # (2)
     COPY ______________ .                                              # (3)
     RUN pip install --no-cache-dir ___ requirements.txt                        # (4)
     COPY . .
     ______ 8000                                                        # (5) documents the port
     CMD ["gunicorn", "--bind", "_______:8000", "app:app"] # (6)



    7. Command to build it as campuspulse:v1 : docker                                    -t campuspulse:v1

    8. File that keeps .env and venv/ out of the image:

   🔓 Answer key: (1) FROM (2) WORKDIR (3) requirements.txt (4) -r (5) EXPOSE (6) 0.0.0.0 (7) build … . (the build context) (8)
   .dockerignore




   ✏️ DRILL 3 · PREDICT THE OUTPUT
   Image A: CMD ["echo", "Hello, world"] . Image B: ENTRYPOINT ["echo", "Hello,"] +
    CMD ["world"] .

    1. docker run --rm A
    2. docker run --rm A Priya
    3. docker run --rm A echo bye

--- PDF page 330 ---
4. docker run --rm B
    5. docker run --rm B Priya
    6. docker run --rm --entrypoint date B
    7. docker run --rm -e NAME=Priya hello-docker (the Level 1 image)

   🔓 Answer key: 1) Hello, world 2) error: Docker tries to run a program called "Priya" (executable file not found, exit 127) — arguments
   replace CMD 3) bye 4) Hello, world 5) Hello, Priya — arguments replace only CMD 6) prints the current date — --entrypoint re‐
   places ENTRYPOINT and clears the image's CMD 7) Hello, Priya! — -e overrides ENV




    5.7 Containers: lifecycle, docker run, commands
📚 Sources: Unit 5 Notes §6.1–6.2            LEC 6 (Docker) Block G        Docker Lab L0        Docker Cheatsheet

 Lecture 5 Commands Reference (Step 10)


A container is a runtime instance of an image. It always runs the same regardless of the infrastructure, because
it isolates the software from its environment (the cheat sheet's definition, paraphrased). Physically it is the im‐
age's read-only layers + one thin writable layer + an isolated process.


▸ The five states of a container


                                                      Paused


          docker create                       pause               unpause
                                                                       stop · kill · exits
                                   start                                                                                   rm
             Created                                  Running                                         Exited                         Removed
                                                                         start · restart


                                                     docker run = pull (if needed) + create + start
                                docker rm -f removes a running container directly · --rm removes it automatically when it exits


               Figure 5.4 — Container lifecycle. An Exited container still exists (with its writable layer and logs) until you remove it.


 State                  How it gets there                                                  What still exists

 Created                docker create (or the first half of docker                         Config + writable layer; no process yet
                        run )

 Running                docker start / docker run                                          The main process, running as PID 1

 Paused                 docker pause                                                       Processes frozen (cgroup freezer), memory kept

 Exited                 docker stop / docker kill / the main                               Writable layer and logs, no process. docker ps -a
 (stopped)              process ends                                                       shows it

 Removed                docker rm                                                          Nothing: writable layer and logs are gone


You may also see Restarting (a restart policy is bringing it back) and Dead (removal failed) in docker ps .

--- PDF page 331 ---
▸ Decoding a docker run command, flag by flag
The command from Lecture 5 (Step 10) that gave you PostgreSQL for Django:

           terminal — Lecture 5, Step 10


  $ docker run --name imap-postgres \
        -e POSTGRES_PASSWORD=yourpassword \
        -e POSTGRES_DB=imapdb \
        -p 5432:5432 -d postgres:16
  # next time, just:
  $ docker start imap-postgres



 Option                        Meaning

  --name imap-postgres         A readable name instead of a random ID

  -e                           Sets an environment variable inside the container (the image uses it to create the superuser
 POSTGRES_PASSWORD=…           password)

  -e POSTGRES_DB=imapdb        Creates the database imapdb on first start

  -p 5432:5432                 Publishes a port: host on the left, container on the right

  -d                           Detached: runs in the background

  postgres:16                  The image and tag to run



  🔑 THE ONE RULE OF DOCKER RUN
   Options go before the image name. Anything after the image name is the command to run inside the con‐
  tainer , replacing the image's default CMD. docker run ubuntu:24.04 -it bash is wrong;
    docker run -it ubuntu:24.04 bash is right.


EVERY DOCKER RUN FLAG YOU WILL NEED

 Flag                          Meaning                                                Example

  -d                           Detached (background); prints the container ID          docker run -d nginx:alpine

  -it                          Interactive + terminal (for shells)                     docker run -it ubuntu:24.04
                                                                                      bash

  --rm                         Delete the container when it exits (one-off             docker run --rm hello-docker
                               commands)

  --name                       Give it a name                                          --name web

  -p HOST:CONTAINER            Publish a port ("outside : inside")                     -p 8080:80 , -p
                                                                                      127.0.0.1:5432:5432

  -P                           Publish every EXPOSEd port to a random host port        docker run -d -P nginx:alpine

  -e KEY=value / --env-        Set environment variables / load them from a file       --env-file .env
 file

  -v src:/path                 Mount a named volume or a host folder ( :ro =           -v pulse-data:/data
                               read-only)

--- PDF page 332 ---
Flag                          Meaning                                           Example

  --mount                      Long, explicit form of -v                          --mount type=volume,src=pulse-
                                                                                 data,dst=/data

  --network                    Join a user-defined network                        --network pulse-net

  --restart                    Restart policy: no , on-failure , always ,         --restart unless-stopped
                                unless-stopped

  -u , -w                      Run as a user / set the working directory          -u 1000 -w /app

  --memory , --cpus , --       cgroup resource limits                             --memory 256m --cpus 0.5
 pids-limit

  --read-only , --tmpfs ,      Hardening: read-only root FS, RAM scratch dir,     --read-only --tmpfs /tmp --
  --cap-drop                   drop Linux capabilities                           cap-drop ALL

  --entrypoint                 Replace the image's ENTRYPOINT                     --entrypoint echo

  --platform                   Run an image built for another CPU architecture    --platform linux/amd64

 (after the image)             Replaces CMD                                       docker run --rm ubuntu:24.04
                                                                                 ls /



▸ Everyday container commands
The full lifecycle and debugging tables are §5.17-C and §5.17-D; the exam-sized version is Part 3 of the PYQ
answer in §5.14. Core set: run · ps -a · stop / start / restart / kill · rm -f · logs -f ·
 exec -it · inspect · stats . Note: docker stop sends SIGTERM, then SIGKILL after 10 s; docker kill
sends SIGKILL at once.

EXIT CODES YOU WILL SEE IN DOCKER PS -A

 Code                    Meaning

  Exited (0)             Finished normally (e.g. hello-world)

  Exited (1)             The application itself crashed: read docker logs

  Exited (127)           Command not found (typo in CMD, or argument treated as a program)

  Exited (137)           Killed with SIGKILL (128+9): out of memory, docker kill , or stop timeout

  Exited (143)           Stopped by SIGTERM (128+15), a normal docker stop

--- PDF page 333 ---
▸ Two lab demos that teach isolation

  EDIT INSIDE, LOSE IT (L0 STEP 5)                                                DESTROY A CONTAINER, NOT YOUR
                                                                                  LAPTOP (L0 STEP 4)
               terminal

                                                                                               terminal
       $ docker run -d -p 8080:80 --name web ng‐
       inx:alpine                                                                    $ docker run --rm ubuntu:24.04 \
       $ docker exec -it web sh                                                             sh -c 'rm -rf --no-preserve-root / ;
       / # echo '<h1>Edited live</h1>' >                                             ls'
       /usr/share/nginx/html/index.html                                              sh: 1: ls: not found                 # it deleted its
       / # exit                                                                      own ls!
       $ docker rm -f web                                                            $ docker run --rm ubuntu:24.04 ls /
       $ docker run -d -p 8080:80 --name web ng‐                                     bin     boot     dev    etc   home   lib    …     #
       inx:alpine                                                                    fresh and untouched
       # refresh → "Welcome to nginx!" again

                                                                                  The container only saw its own filesystem. But with -v
  Changes live in the writable layer and die with the container.                  C:\Users\you:/host the same command would delete
  That is why code goes in images and data in volumes.                            your files: isolation is only as good as what you share in.



   ✏️ DRILL 4 · COMPLETE THE DOCKER RUN COM MA ND S
    1. Start PostgreSQL 16 in the background, named imap-postgres , password yourpassword , database
         imapdb , on laptop port 5432:
         docker run                          imap-postgres                           POSTGRES_PASSWORD=yourpassword
                           POSTGRES_DB=imapdb                              5432:5432                         postgres:16

    2. Start that same container again next morning: docker                                            imap-postgres

    3. Open psql inside it: docker                                -it imap-postgres psql -U postgres -d imapdb

    4. A throw-away Ubuntu shell that deletes itself on exit:
         docker run                                            ubuntu:24.04 bash

    5. List containers including stopped ones: docker ps
    6. Remove a running container in one step: docker rm                                            web

    7. Follow the logs of web live: docker logs                                       web


   🔓 Answer key: 1) --name · -e · -e · -p · -d 2) start 3) exec 4) -it · --rm 5) -a (or --all) 6) -f 7) -f

   PYQ        Final 2024-25 · Q4(b)       Re-Exam 2023-24 · Q2(b)                                                                          10 M


  Final 2024-25 Q4(b): Explain Docker Architecture? A short note on Docker Container.
  Re-Exam 2023-24 Q2(b): Explain Docker Architecture? Write frequently used Docker commands.

   ✓    MODEL ANSWER — WRITE THIS

  Write Part 1 for both papers. Then add Part 2 if the question asks for a note on containers (2024-25) or Part 3 if it asks for fre‐
  quently used commands (2023-24).

--- PDF page 334 ---
PART 1 · DOCKER ARCHITECTURE (BOTH PAPERS)

  Docker is an open-source containerisation platform that packages an application with its code, runtime, li‐
  braries and configuration into an image and runs it as an isolated container. Docker uses a client–server
  architecture: the Docker client sends commands to the Docker daemon, which does the work of build‐
  ing, running and distributing containers, and images are stored in a registry. The client and daemon talk
  through a REST API over a UNIX socket ( /var/run/docker.sock ) or a network connection.


                                                                   Docker Host
                                     REST API
                                                          Docker daemon (dockerd)
                Docker Client                                                                                   Registry
                                                                                                  pull
                 docker build                                                                                  Docker Hub
                                                       Images                    Containers
                  docker pull                                                                                 GHCR / ECR
                                                       read-only                    running
                  docker run                                                                     push            (private)


                                                               Volumes · Networks




       Draw this: client → daemon (REST API); daemon manages images → containers, volumes, networks; host   ⇄ registry (pull / push).
  Components:

    1. Docker Client — the docker CLI that the user types commands into ( docker build , docker pull ,
        docker run ). It does no work itself; it converts each command into an API request for the daemon.
       One client can control several daemons, local or remote.
    2. Docker Host — the machine that runs the daemon and stores images, containers, volumes and
       networks.
            Docker daemon ( dockerd ) — a background service that listens for API requests and manages all
            Docker objects: builds images, pulls and pushes them, creates, starts and stops containers, and
            sets up storage and networking. Internally it hands containers to containerd and runc (the OCI run‐
            time), which create Linux namespaces (isolation: what a process can see) and cgroups (limits:
            what it can use).

    3. Docker objects — Images (read-only templates built from a Dockerfile, made of cached layers),
       Containers (runnable instances of images with a thin writable layer), Volumes (persistent storage that
       outlives containers) and Networks (virtual networks; containers on the same network reach each other
       by name).
    4. Docker Registry — stores and distributes images. Docker Hub is the default public registry; private
       ones include GitHub Container Registry, Amazon ECR and Harbor. docker pull downloads an image,
        docker push uploads one.

  Working — what happens on docker run -d -p 8080:80 nginx : (1) the client sends a create + start re‐
  quest to the daemon; (2) the daemon looks for the image in its local cache; (3) if missing, it pulls the layers
  from the registry; (4) it creates the container: read-only layers + a writable layer; (5) it connects the container
  to a network and maps host port 8080 to container port 80; (6) runc starts nginx as PID 1 inside its name‐
  spaces and cgroups; (7) the container ID is returned.

--- PDF page 335 ---
Why this design works: the client and daemon can be on different machines; an image built once is
  shared through a registry and runs identically on any Docker host; one daemon manages every container
  on a host. Conclusion: client asks, daemon works, registry stores.

  PART 2 · SHORT NOTE ON DOCKER CONTAINER (2024-25)

  Definition. A Docker container is a runnable, isolated instance of a Docker image. It packages an applica‐
  tion with everything it needs and runs it as an isolated process on the host, sharing the host operating
  system's kernel instead of booting its own OS.

  How it is built. Container = the image's read-only layers + a thin writable layer + an isolated process.
  Namespaces give it its own process list (the app is PID 1), network, hostname and filesystem; cgroups limit
  its CPU, memory and number of processes.

  Characteristics:

       Lightweight — megabytes, no guest OS.
       Fast — starts in about a second.
       Portable — runs the same on a laptop, a college server or the cloud.
       Isolated — each app has its own libraries and versions with no conflicts.
       Disposable (ephemeral) — changes in the writable layer are lost when the container is removed, so
       data is kept in volumes.
       Scalable — many identical containers can run from one image.

  Lifecycle: Created → Running    ⇄ Paused → Exited (stopped) → Removed. docker run = create + start;
    docker ps -a shows exited containers; --rm removes a container automatically on exit.

              example


     docker run -d --name web -p 8080:80 nginx:alpine                # create + start
     docker ps                                                        # list running containers
     docker logs web                                                  # see its output
     docker exec -it web sh                                           # shell inside it
     docker stop web && docker rm web                                 # stop, then remove



  Image vs container: an image is like a class (a template); a container is like an object (an instance). One
  image can produce any number of independent containers. Conclusion: containers give VM-like isolation at
  the cost of a process, which is why "works on my machine" becomes "works on every machine".

  PART 3 · FREQUENTLY USED DOCKER COMMANDS (2023-24)

    Command                       Purpose                                  Example

     docker --version /           Check installation / system-wide          docker info
     docker info                  information

     docker pull                  Download an image from a registry         docker pull postgres:16

     docker images                List local images                         docker images

     docker build                 Build an image from a Dockerfile          docker build -t myapp:1.0 .

--- PDF page 336 ---
Command                              Purpose                                     Example

     docker run                          Create and start a container                 docker run -d --name web -p
                                                                                     8080:80 nginx:alpine

     docker ps / docker ps               List running / all containers                docker ps -a
    -a

     docker stop / docker                Stop / start an existing container           docker stop web
    start

     docker rm                           Remove a stopped container                   docker rm web

     docker rmi                          Remove an image                              docker rmi myapp:1.0

     docker exec -it                     Open a shell / run a command in a run‐       docker exec -it web sh
                                         ning container

     docker logs -f                      Fetch and follow a container's logs          docker logs -f web

     docker inspect                      Detailed JSON configuration of a             docker inspect web
                                         container/image

     docker tag + docker                 Name an image for a registry and up‐         docker push asha/myapp:1.0
    push                                 load it

     docker login                        Log in to Docker Hub                         docker login -u asha

     docker volume create                Create persistent storage                    docker volume create pgdata

     docker network create               Create a user-defined network                docker network create appnet

     docker compose up -d /              Start / stop a multi-container stack         docker compose up -d --build
     down

     docker system prune                 Remove unused containers, networks,          docker system prune
                                         images



  🎯 Marking scheme guess: Both papers: diagram 2 M + client/daemon/objects/registry explained 4 M. Then 2024-25: container note 4 M
  (definition 1, characteristics 2, lifecycle/example 1). 2023-24: commands 4 M (roughly 1 M per 3–4 correct commands with purpose and
  example).




    5.8 Storage: volumes, bind mounts, tmpfs
📚 Sources: Unit 5 Notes §6.1, §6.3      LEC 6 (Docker) Block H     Docker Lab L3     Unit 3 Notes §4.2, §9.5



▸ The problem: the writable layer dies with the container
Any file a container changes lives in its own thin writable layer, which is deleted together with the container.
Lab Level 3 makes you watch it happen:

--- PDF page 337 ---
WITHOUT A VOLUME                                                          WITH A NAMED VOLUME

              terminal                                                                    terminal


     $ docker run -d --name pulse -p 8000:8000                                    $ docker volume create pulse-data
     campuspulse:v1                                                               $ docker run -d --name pulse -p 8000:8000
     # vote Samosa, Samosa, Maggi in the brows‐                                   \
     er…                                                                              -v pulse-data:/data campuspulse:v1
     $ docker rm -f pulse                                                         # vote Samosa × 3, then rm -f and run
     $ docker run -d --name pulse -p 8000:8000                                    again
     campuspulse:v1                                                               $ curl localhost:8000/api/results
     $ curl localhost:8000/api/results                                            {"votes": {… "Samosa": 3}}
     {"votes": {"Maggi": 0, "Samosa": 0, …}}                                      # survived
     # all gone                                                                   $ docker volume inspect pulse-data



This is correct behaviour: the image stays clean and data belongs outside the container. It gives the central rule
of Docker: code belongs in images, data belongs in volumes .


▸ Three ways to mount storage

                            HOST                                                                          CONTAINER

                                                                 -v pulse-data:/data
                    Docker area (volume)
                                                                                                             /data
             /var/lib/docker/volumes/pulse-data


                                                                  -v "$(pwd)":/app
             Any folder you choose (bind mount)
                                                                                                              /app
                  C:\Users\you\campuspulse


                                                                    --tmpfs /tmp
                 RAM, memory only (tmpfs)                                                                     /tmp


                        Figure 5.5 — Volume, bind mount and tmpfs: three sources outside the container's writable layer.


  Point                       Volume                                  Bind mount                                      tmpfs

  Managed by                  Docker                                  You (a host folder)                             Memory

  Lives at                      /var/lib/docker/volumes               Any path you choose                             RAM only
                              /…

  Best for                    Databases, uploads, app data            Source code during development, con‐            Scratch space,
                                                                      fig files                                       secrets

  Survives docker             Yes                                     Yes (it is your folder)                         No
  rm ?

  Syntax                        -v pulse-data:/data                    -v "$(pwd)":/app:ro                                 --tmpfs /tmp

--- PDF page 338 ---
▸ Volume commands
 docker volume create · ls · inspect · rm · prune (deletes data!), and two mount syntaxes:
 -v pulse-data:/data or --mount type=volume,src=pulse-data,dst=/data ; bind mount
 -v "$(pwd)":/app:ro (PowerShell: ${PWD} ). Full table: §5.17-E.

           tip — back up a volume to a .tgz in the current folder


  docker run --rm -v pulse-data:/data -v "$(pwd)":/backup alpine tar czf /backup/data.tgz /data




▸ Databases in containers (Unit 3 link)
    PostgreSQL keeps its data in /var/lib/postgresql/data , so that is where the named volume is mounted:
     pgdata:/var/lib/postgresql/data .

    The three POSTGRES_USER / POSTGRES_PASSWORD / POSTGRES_DB variables create the first user, password
    and database only when the volume is empty (first start).
    Unit 3 mounts ./sql:/docker-entrypoint-initdb.d:ro : every *.sql file there runs automatically, but
    only on a brand-new, empty volume. "I changed the SQL file and nothing happened" means the volume al‐
    ready existed: apply the change with psql, or docker compose down -v to start from scratch (which deletes
    the data).

  ⚠️ COMMON MISTAKES
       Storing a database inside the container without a volume: it disappears on docker rm .
       Thinking a bind mount is "safe because it is a container": a bind mount gives the container real access
       to that folder on your laptop.
       Running docker volume prune or docker compose down -v casually: both delete database data.




    5.9 Networking: ports, names, the localhost trap
📚 Sources: Unit 5 Notes §6.4–6.6   LEC 6 (Docker) Block I   Docker Lab L4     Unit 3 Notes §9.1     Complete Revision deck



▸ Port publishing: -p HOST:CONTAINER
A container has its own network namespace, so an app inside it is not reachable from your laptop until a port is
published. Read -p 8080:80 as "outside : inside" : laptop port 8080 forwards to container port 80 (Docker
adds a NAT rule).

 You write                           Effect

  -p 8080:80                         Browser opens http://localhost:8080 → nginx on port 80 inside

  -p 8001:8000                       Use when host port 8000 is taken ("port is already allocated")

  -p 127.0.0.1:5432:5432             Publishes only to your own laptop, not the whole Wi-Fi network (Unit 3 does this for Postgres)

 no -p at all                        Only other containers on the same network can reach it (correct for databases)

  EXPOSE 8000 in the Dockerfile      Documents the port only; publishes nothing

--- PDF page 339 ---
Bind to 0.0.0.0, not 127.0.0.1. Inside a container, 127.0.0.1 means "this container only", so traffic arriving from
outside through the published port is refused. That is why gunicorn is started with --bind 0.0.0.0:8000
(works) while flask run listens on 127.0.0.1:5000 (unreachable).


▸ Service discovery: on a user-defined network, names are addresses


       YOUR LAPTOP (host)                              user-defined network pulse-net · embedded DNS at 127.0.0.11

                                                                                     pulse-db:5432
              Browser                                                                                          pulse-db
            localhost:8000                                                                                    172.18.0.2
                                                         pulse-web                                       postgres on 5432 (no -p)
                                                         172.18.0.4
                                                   gunicorn 0.0.0.0:8000 ✓
                                                 localhost here = pulse-web itself
            host port 8000                                                                                   pulse-cache
            Docker NAT rule                                                                                   172.18.0.3
                                        -p 8000:8000                           pulse-cache:6379           redis on 6379 (no -p)


                                              IPs change on every restart; names do not. In Compose the service name is the hostname.




  Figure 5.6 — The browser reaches the web container through a published port; the web container reaches the database and cache by name
                                                           through Docker's DNS.


    Docker runs a small DNS server (127.0.0.11) on every user-defined network, so containers reach each other
    by container or service name.
    The default bridge network has no name DNS, so always create your own network (Compose does it for
    you).
    Proven in Lab Level 4:

            terminal — Lab Level 4


  $ docker exec pulse-web python -c "import socket; print(socket.gethostbyname('pulse-db'))"
  172.18.0.2                                     # Docker's DNS resolved the name
  $ docker exec pulse-db psql -U pulse -d campuspulse -c "select * from votes;"
  $ docker network inspect pulse-net --format "{{range .Containers}}{{.Name}} {{end}}"
  pulse-web pulse-cache pulse-db




▸ The localhost trap — the number-one beginner bug
Inside the web container, localhost means the web container itself, and there is no database there. Almost
every "connection refused" in the lab was this.

  You are here…                                                                         …to reach PostgreSQL, use

  Your laptop (port published with -p 5432:5432 )                                        localhost:5432

  Another container on the same network                                                  db:5432 (the service or container name)

  A container, reaching a service installed on your laptop                               host.docker.internal:5432

--- PDF page 340 ---
This is exactly why Unit 2's "HOST": "localhost" must become "HOST": "db" once Django itself runs in a
container (§5.11). The same rule appears in Unit 3's nginx config: proxy_pass http://web:8000; , never
localhost.


▸ One image, many configurations
In Lab Level 4 the same image stored votes in SQLite when started with no settings, and in PostgreSQL +
Redis when started with environment variables. Nothing was rebuilt:

           terminal — Lab Level 4 (by hand)


  $ docker network create pulse-net
  $ docker volume create pulse-pg
  $ docker run -d --name pulse-db --network pulse-net \
        -e POSTGRES_USER=pulse -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=campuspulse \
        -v pulse-pg:/var/lib/postgresql/data postgres:16-alpine
  $ docker run -d --name pulse-cache --network pulse-net redis:7-alpine
  $ docker run -d --name pulse-web --network pulse-net -p 8000:8000 \
        -e DATABASE_URL=postgresql://pulse:secret@pulse-db:5432/campuspulse \
        -e REDIS_URL=redis://pulse-cache:6379/0 \
        campuspulse:v1



Configuration comes from the environment, not the code (the "12-factor" idea), so one image serves develop‐
ment, testing and production. Note: no -p on the database: only other containers need it.


▸ Network drivers (extra)

 Driver                  Use

  bridge (default)       Private network on one host; the default bridge has no DNS by name

 user-defined bridge      docker network create pulse-net : DNS by name, isolation per app. What you should use

  host                   Container shares the host's network directly (no isolation, no -p needed; Linux)

  none                   No networking at all

  overlay                Spans several hosts (Docker Swarm)



▸ Network commands
 docker network create · ls · inspect · connect / disconnect · rm · prune , and
 docker run --network pulse-net … . Full table: §5.17-E.


   ✏️ DRILL 5 · PORTS AND HOSTNAMES — PRE DI CT
    1. docker run -d -p 9090:80 nginx:alpine . Which URL opens nginx in your browser?
    2. Django runs in container web , PostgreSQL in container db , same user-defined network. "HOST" in
       settings.py = ?
    3. Django runs directly on your laptop; PostgreSQL in a container started with -p 5432:5432 . "HOST" =
       ?

--- PDF page 341 ---
4. A container must reach a PostgreSQL installed directly on your laptop. Host name = ?
    5. An image whose CMD is flask run is started with -p 5000:5000 . The browser shows nothing.
       Why?
    6. Two containers started without --network . Can web resolve the name db ?
    7. The Dockerfile says EXPOSE 8000 ; you run docker run -d myapp . Is localhost:8000 reachable?
    8. docker run -p 8000:8000 … fails: "port is already allocated". Fix?

   🔓 Answer key: 1) http://localhost:9090 2) "db" (port 5432) 3) "localhost" 4) host.docker.internal 5) flask run listens on 127.0.0.1 inside
   the container, so outside traffic is refused; bind to 0.0.0.0 (or use gunicorn --bind 0.0.0.0:…) 6) No — the default bridge has no name
   DNS; create a network and use --network 7) No — EXPOSE only documents; add -p 8000:8000 8) Another program/container already
   uses host port 8000: stop it or use -p 8001:8000




    5.10 Docker Compose: the whole stack in one file
📚 Sources: Unit 5 Notes §7        LEC 6 (Docker) Block J     Docker Lab L5     Unit 3 Notes §4.2, §9.4–9.5    One-Shot Revision

 Complete Revision deck


Starting a web app and its database by hand took five long commands in Level 4 (network, volume, three con‐
tainers with the right names, variables, ports and order). Docker Compose replaces all of it with one file,
 compose.yaml , and one command:

            terminal — Level 5


  $ docker compose up -d --build                    # build, create network + volumes, start everything
  $ docker compose down                             # …and throw it all away (volumes kept)



    Declarative — describes the end state, not the steps.
    Version-controlled — the stack lives in Git next to the code.
    Reproducible — a teammate starts the whole stack with one command.
    Compose creates the network and volumes itself, sets the start order, and each service name becomes a
    hostname.


▸ Anatomy of compose.yaml (the CampusPulse stack)

            campuspulse/compose.yaml


  services:
     web:
        build: .                                        # build ./Dockerfile (or use image: to pull one)
        ports:
           - "8000:8000"                                # same as -p HOST:CONTAINER; always quote it
        environment:                                    # same as -e; ${VAR} comes from .env
           DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
           REDIS_URL: redis://cache:6379/0 # service names are DNS names
           POLL_QUESTION: ${POLL_QUESTION}

--- PDF page 342 ---
depends_on:
           db:
             condition: service_healthy      # wait until the db healthcheck passes
           cache:
             condition: service_started
        restart: unless-stopped              # same as --restart


     db:
        image: postgres:16-alpine
        environment:
           POSTGRES_USER: ${POSTGRES_USER}
           POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
           POSTGRES_DB: ${POSTGRES_DB}
        volumes:
           - pgdata:/var/lib/postgresql/data     # named volume: data survives "down"
        healthcheck:
           test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"]         # $$ = a literal $
           interval: 5s
           retries: 10


     cache:
        image: redis:7-alpine                # one line: pulled from Docker Hub


     adminer:
        image: adminer
        ports: ["8080:8080"]
        profiles: ["tools"]                  # only starts with --profile tools


  volumes:
     pgdata:                                 # top-level declaration of the named volume



           campuspulse/.env (never committed — commit .env.example instead)


  POSTGRES_USER=pulse
  POSTGRES_PASSWORD=change-me-please
  POSTGRES_DB=campuspulse
  POLL_QUESTION=Best canteen snack?




▸ Every key mapped to its docker run option

 Compose key                   Equivalent                        Meaning

  services:                    one docker run each               Each service becomes one (or more) containers

  build: / image:              docker build / image name         Build from a Dockerfile, or pull a ready image

  ports:                       -p                                Publish HOST:CONTAINER

--- PDF page 343 ---
Compose key                   Equivalent                                    Meaning

  environment: / env_‐          -e / --env-file                              Variables inside the container
 file:

  volumes:                      -v                                           Named volumes or bind mounts

  networks:                     --network                                    Which networks it joins (default: one per project)

  restart:                      --restart                                    Restart policy

  command:                     args after the image                          Overrides CMD

  depends_on:                  (start order)                                 Start order; with condition: service_healthy it
                                                                             waits for readiness

  healthcheck:                  --health-cmd                                 How Docker tests that the service is really ready

  profiles:                    —                                             Optional services started only on request

  deploy.re‐                    --memory , --cpus                            Resource limits
 sources.limits

 top-level volumes: /           docker volume create / net‐                  Declares them; Compose names them
  networks:                    work create                                     <project>_pgdata



▸ Three ideas that matter most

 1        Secrets in .env. Compose automatically reads .env from the same folder and fills in ${VARIABLE}
          values. .env is in .gitignore and .dockerignore ; a .env.example with placeholder values is
          committed instead. Change POLL_QUESTION in .env and the poll changes with no code edit and no
          rebuild.

 2        Started is not ready. A database container can be "running" while PostgreSQL inside it is still initialis‐
          ing. A healthcheck ( pg_isready ) tests real readiness, and depends_on with
           condition: service_healthy makes the web service wait for it. Plain depends_on: [db] only orders
          the start.

 3        down vs down -v. docker compose down removes containers and the network but keeps volumes,
          so data survives. down -v also deletes the volumes, wiping the database.


 Command sequence                         Result                             Why

  docker compose down , then up           All data still there (Samosa: 2)   The named volumes were kept
 -d

  docker compose down -v , then           Everything starts empty            The volumes were deleted; Postgres re-initialises and re-
  up -d                                   (Samosa: 0)                        runs init SQL files

--- PDF page 344 ---
⚠️ YAML AND COMPOSE GOTCHAS
        Quote ports: YAML 1.1 reads unquoted xx:yy values (with yy under 60) as base-60 numbers. Write
        "8000:8000" .

        $$ escapes $ so Compose leaves it for the container's shell ( $${POSTGRES_USER} in the
        healthcheck).
        Indent with spaces only, never tabs.
        The file is compose.yaml (older name docker-compose.yml ). The top-level version: key is obso‐
        lete. Old installs use docker-compose with a hyphen; current Docker uses docker compose .
        Network and volumes are prefixed with the project (folder) name: campuspulse_default ,
        campuspulse_pgdata , containers campuspulse-web-1 .



▸ The Compose toolbox
Most used: docker compose up -d --build (add --wait to block until healthy, --scale web=3 for copies) ·
 ps · logs -f web · exec web sh · run --rm web python seed.py · config (first debugging step) ·
 watch · down / down -v . Every Compose command with an example: §5.17-F.

           terminal — Lab Level 5 output


  $ docker compose up -d --build --wait
    ✔ Network campuspulse_default          Created
    ✔ Volume campuspulse_pgdata            Created
    ✔ Container campuspulse-db-1           Healthy
    ✔ Container campuspulse-cache-1        Healthy
    ✔ Container campuspulse-web-1          Healthy
  $ docker compose ps
  SERVICE       STATUS                   PORTS
  cache         Up 6 seconds             6379/tcp
  db            Up 6 seconds (healthy)   5432/tcp
  web           Up 1 second              0.0.0.0:8000->8000/tcp



THE BIGGER UNIT 3 STACK, IN ONE TABLE
Unit 3 §9.4 runs five services from one file: db (postgres:16 + healthcheck + ./sql init scripts), mongo (mon‐
go:7), storage (an S3-compatible server on 9000), web (build: ., waits for db and mongo to be healthy) and
 nginx (the single entrance on 8080). The design rules: databases publish no ports,
 DATABASE_URL / MONGO_URL use the service names db and mongo , and only the entrance (and what a
browser must reach directly) is published.


   ✏️ DRILL 6 · COMPLETE THE COMPOSE FIL E
                compose.yaml (blanks)


       services:
         web:
           ______: .                                       # (1) build from ./Dockerfile

--- PDF page 345 ---
ports:
              - "____:8000"                                             # (2) open on laptop port 8000
           environment:
              DATABASE_URL: postgresql://pulse:${POSTGRES_PASSWORD}@____:5432/campuspulse                                  # (3)
           depends_on:
              db:
                 condition: _______________                             # (4) wait until db is READY
        db:
           ______: postgres:16-alpine                                   # (5)
           environment:
              POSTGRES_USER: pulse
              POSTGRES_PASSWORD: ${_________________}                   # (6) read from .env
              POSTGRES_DB: campuspulse
           volumes:
              - ______:/var/lib/postgresql/data                         # (7)
           ___________:                                                 # (8)
              test: ["CMD-SHELL", "pg_isready -U pulse"]
              interval: 5s
     _______:                                                           # (9)
        pgdata:



   10. Start the stack in the background, rebuilding images:
        docker compose

   11. Stop it and delete the database data too: docker compose down
   12. See the YAML after .env substitution: docker compose

   🔓 Answer key: (1) build (2) 8000 (3) db (4) service_healthy (5) image (6) POSTGRES_PASSWORD (7) pgdata (8) healthcheck (9) vol‐
   umes (10) up -d --build (11) -v (12) config




    5.11 Integrating Django with Docker
📚 Sources: Unit 5 Notes §8         Unit 3 Notes §9.2–9.6   Lecture 5 Commands Reference (Steps 9–11)       LEC 5 (Django code-along)

 Unit 2 Notes §6.2      LEC 8 (Databases & Deployment)     One-Shot Revision


This is the syllabus line "Integrate Django with Docker". You did it in two stages during the course:


  STAGE 1 · LECTURE 5 (UNIT 2)                                            STAGE 2 · UNIT 5
  Only PostgreSQL runs in Docker ( docker run --                          Both Django and PostgreSQL run as containers in
  name imap-postgres … -p 5432:5432 -d post‐                              one Compose project. Now Django is inside a
  gres:16 ). Django runs on your laptop with run‐                         container, so localhost would mean the Django
  server , so "HOST": "localhost" is correct: the                         container itself. The host becomes "db" , the ser‐
  port is published to the laptop.                                        vice name.

--- PDF page 346 ---
▸ What changes when Django moves into a container

  Change           Before (Unit 2, laptop)   After (in Docker)                    Why

  Server            python manage.py          gunicorn mysite.wsgi:ap‐            runserver is a development tool; guni‐
                   runserver                 plication --bind                     corn is a production WSGI server. Bind
                                             0.0.0.0:8000                         0.0.0.0 so traffic from outside the con‐
                                                                                  tainer gets in

  Settings          SECRET_KEY , DEBUG       Read from environment variables,     One image works everywhere and no
                   = True , DB password      supplied by .env                     secret is baked into it
                   typed in settings.py

  Database          "HOST":                   "HOST": "db"                        The localhost trap: containers reach
  host             "localhost"                                                    each other by service name

  Migrations       Run by hand               Run when the web container starts,   The database does not exist while the
                                             before gunicorn; superuser created   image is being built
                                             inside the running container

  Static files     Served by runserver        collectstatic + the                 With DEBUG off Django stops serving
                   while DEBUG = True        WhiteNoise package                   CSS, which is why the admin suddenly
                                                                                  looks unstyled

  ML model          mlpredict_iris/ml/       Travels inside the image with the    The scikit-learn version in the image
                   iris_model.pkl on         code                                 must match the one that trained it, or
                   disk                                                           the model may fail to load



▸ Project layout

             imap-django/ (the Unit 2 project, containerised)


  imap-django/
  ├── manage.py
  ├── requirements.txt
  ├── Dockerfile
  ├── .dockerignore
  ├── compose.yaml
  ├── .env                    ← real values, git-ignored
  ├── .env.example            ← placeholders, committed
  ├── mysite/                 ← project: settings.py, urls.py, wsgi.py
  ├── accounts/               ← app from Lecture 5
  └── mlpredict_iris/
        └── ml/iris_model.pkl




▸ Step 1 · requirements.txt (pin everything)

             requirements.txt

--- PDF page 347 ---
Django==5.0.6
  djangorestframework==3.15.1
  psycopg2-binary==2.9.9               # lets Python talk to Postgres
  gunicorn==22.0.0                     # production server
  whitenoise==6.7.0                    # serves static files when DEBUG is off
  scikit-learn==1.5.0                  # must equal the version that trained iris_model.pkl
  joblib==1.4.2


Exact numbers are an example; the rule is to pin the versions you developed and trained with
( pip freeze > requirements.txt ).



▸ Step 2 · settings.py reads the environment

            mysite/settings.py (only the parts that change)


  import os
  from pathlib import Path


  BASE_DIR = Path(__file__).resolve().parent.parent


  SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]                            # no default: fail loudly if missing
  DEBUG = os.environ.get("DJANGO_DEBUG", "0") == "1"
  ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost").split(",")


  DATABASES = {
        "default": {
             "ENGINE": "django.db.backends.postgresql",
             "NAME": os.environ.get("POSTGRES_DB", "imapdb"),
             "USER": os.environ.get("POSTGRES_USER", "postgres"),
             "PASSWORD": os.environ.get("POSTGRES_PASSWORD", ""),
             "HOST": os.environ.get("DB_HOST", "db"),                      # was "localhost" in Unit 2
             "PORT": os.environ.get("DB_PORT", "5432"),
        }
  }


  MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
        "whitenoise.middleware.WhiteNoiseMiddleware",                      # right after SecurityMiddleware
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
  ]

--- PDF page 348 ---
STATIC_URL = "static/"
  STATIC_ROOT = BASE_DIR / "staticfiles"                             # collectstatic copies everything here




▸ Step 3 · The Dockerfile

           Dockerfile


  FROM python:3.12-slim


  ENV PYTHONDONTWRITEBYTECODE=1 \
        PYTHONUNBUFFERED=1


  WORKDIR /app


  # 1. dependencies first: this slow layer stays cached
  COPY requirements.txt .
  RUN pip install --no-cache-dir -r requirements.txt


  # 2. code last (includes mlpredict_iris/ml/iris_model.pkl)
  COPY . .


  # 3. gather static files for WhiteNoise (a throw-away key is enough for this step)
  RUN DJANGO_SECRET_KEY=build-only-not-secret python manage.py collectstatic --noinput


  # 4. never run as root
  RUN useradd --create-home --uid 10001 appuser
  USER appuser


  EXPOSE 8000


  # 5. migrate at START-UP (no database exists at build time), then gunicorn becomes PID 1
  CMD ["sh", "-c", "python manage.py migrate --noinput && exec gunicorn mysite.wsgi:application --
  bind 0.0.0.0:8000 --workers 2"]


     PYTHONUNBUFFERED=1 makes print/log output appear immediately in docker logs ; PYTHONDONTWRITEBYTECODE=1
    stops .pyc files.
     exec replaces the shell with gunicorn, so gunicorn receives SIGTERM from docker stop and shuts down cleanly.
    The course's own Unit 3 version is the same idea in five lines: FROM python:3.12-slim · WORKDIR /srv · copy and in‐
    stall requirements · COPY . . ·
     CMD ["gunicorn", "project.wsgi:application", "--bind", "0.0.0.0:8000"] .

--- PDF page 349 ---
▸ Step 4 · .dockerignore and .env


              .dockerignore                                             .env.example → copy to .env


     .git                                                         DJANGO_SECRET_KEY=change-me-to-a-long-ran‐
     venv/                                                        dom-string
     .venv/                                                       DJANGO_DEBUG=0
     __pycache__/                                                 DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1
     *.pyc                                                        POSTGRES_USER=postgres
     .env                                                         POSTGRES_PASSWORD=change-me
     db.sqlite3                                                   POSTGRES_DB=imapdb
     staticfiles/
     Dockerfile*
     compose*.yaml




▸ Step 5 · compose.yaml: Django + PostgreSQL

            compose.yaml


  services:
     db:
        image: postgres:16-alpine
        environment:
            POSTGRES_USER: ${POSTGRES_USER}
            POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
            POSTGRES_DB: ${POSTGRES_DB}
        volumes:
            - pgdata:/var/lib/postgresql/data         # data survives "docker compose down"
        healthcheck:
            test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
            interval: 5s
            timeout: 3s
            retries: 12
        restart: unless-stopped                       # no ports: only web can reach the database


     web:
        build: .
        env_file: .env                                # SECRET_KEY, DEBUG, ALLOWED_HOSTS, POSTGRES_*
        environment:
            DB_HOST: db                               # the service name, never localhost
            DB_PORT: "5432"
        ports:
            - "8000:8000"
        depends_on:
            db:

--- PDF page 350 ---
condition: service_healthy                                  # started is not ready
        restart: unless-stopped


  volumes:
     pgdata:


 .env is used twice: Compose reads it automatically to fill ${…} in the YAML (for the db service), and env_file: .env injects
every line into the web container, where settings.py reads them.



                                                                Compose project · network imap-django_default


                                                   web (build: .)                                  db (postgres:16-alpine)
                                                                                     db:5432
                                             gunicorn mysite.wsgi                                     healthcheck: pg_isready
                        8000:8000
       Browser                             Django + DRF + iris_model.pkl                                 no published port
    localhost:8000                              WhiteNoise static files

                                              migrate runs first, at start-up


                                                                                                         volume pgdata
                                        .env → SECRET_KEY, DB password                             /var/lib/postgresql/data




 Figure 5.7 — The containerised Unit 2 project: one published port, the database reachable only by name, data in a named volume, secrets from
                                                                            .env.



▸ Step 6 · Run it

           terminal


  cp .env.example .env                                                   # then put real values in .env
  docker compose up -d --build                                           # build the Django image, start db, wait until
  healthy, start web
  docker compose ps                                                      # db (healthy) and web Up
  docker compose logs -f web                                             # "Applying …", then gunicorn "Listening at:
  http://0.0.0.0:8000"
  docker compose exec web python manage.py createsuperuser
  docker compose exec db psql -U postgres -d imapdb                                 # \dt lists the Django tables
  # open http://localhost:8000/admin/                   and the API / ML endpoints
  docker compose down                                                    # stop; database kept in pgdata
  docker compose down -v                                                 # stop and wipe the database



One docker compose up now gives any teammate the full Unit 2 application, API and ML endpoint included,
with no local Python or PostgreSQL at all.

--- PDF page 351 ---
⚠️ WHEN IT BREAKS: DJANGO-IN-DOCKER ERRORS
    Symptom                                 Cause                               Fix

    Admin page has no CSS                   DEBUG is off and static files are    collectstatic + WhiteNoise middleware +
                                            not served                           STATIC_ROOT

     could not connect to server            HOST still localhost , or db         DB_HOST=db ; healthcheck + ser‐
    … localhost … 5432                      not ready yet                       vice_healthy

     DisallowedHost / 400 Bad               The address is not in               Add it to DJANGO_ALLOWED_HOSTS
    Request                                 ALLOWED_HOSTS

     KeyError:                              .env missing or not passed in       Create .env; env_file: .env
    'DJANGO_SECRET_KEY'

     relation "…" does not                  Migrations did not run              Check the CMD; docker compose exec web
    exist                                                                       python manage.py migrate

    CSRF verification failed behind nginx   Origin with a port is not trusted    CSRF_TRUSTED_ORIGINS =
    on :8080                                                                    ["http://localhost:8080"]

    Model will not load / version warning   scikit-learn in the image differs   Pin the same version in requirements.txt
                                            from training

    With --scale web=3 , migrations         Every replica runs migrate at       Run it once: docker compose run --rm
    clash                                   start                               web python manage.py migrate



  ✍️ IF ASKED "EXPLAIN THE STEPS TO INTEGRATE (DOCKERISE) A DJANGO APPLICATION" (6–10 M)
    1. Freeze dependencies into requirements.txt (add gunicorn, psycopg2-binary, whitenoise).
    2. Move configuration to environment variables: SECRET_KEY, DEBUG, ALLOWED_HOSTS, database
       settings; database HOST = db .
    3. Write the Dockerfile: slim pinned base → WORKDIR → copy and install requirements → copy code →
       collectstatic → non-root user → EXPOSE 8000 → CMD gunicorn bound to 0.0.0.0:8000.
    4. Add .dockerignore (venv, .git, .env, db.sqlite3).
    5. Write compose.yaml: web (build: ., ports 8000:8000, env_file, depends_on db healthy) and db (post‐
       gres image, named volume, healthcheck).
    6. Create .env (kept out of Git) from .env.example.
    7. Run docker compose up -d --build ; migrations run at start-up;
        docker compose exec web python manage.py createsuperuser .

    8. Test at localhost:8000, then deploy: tag and push the image to a registry and pull/run it on the server
       (§5.12).

  Write the Dockerfile and compose file in full, then two lines on "why" (gunicorn, env vars, service name, mi‐
  grations at start, static files). That is a complete 10-mark answer.


   ✏️ DRILL 7 · DJANGO IN DOCKER — FILL TH E BLA NK S
               blanks across settings.py, Dockerfile and compose.yaml


     # settings.py
     "HOST": os.environ.get("DB_HOST", "______"),                                        # (1)

--- PDF page 352 ---
"whitenoise.middleware.____________________",                                             # (2)
     STATIC_______ = BASE_DIR / "staticfiles"                                                    # (3)


     # Dockerfile
     RUN python manage.py _____________ --noinput                                                # (4)
     CMD ["sh", "-c", "python manage.py _______ --noinput && exec ________ mysite.wsgi:application
     --bind _______:8000"]             # (5)(6)(7)


     # compose.yaml (web service)
           depends_on:
              db:
                 condition: _______________                                                      # (8)


     # terminal: create an admin user in the running stack
     docker compose ______ web python manage.py _______________                                  # (9)(10)



   🔓 Answer key: (1) db (2) WhiteNoiseMiddleware (3) ROOT (4) collectstatic (5) migrate (6) gunicorn (7) 0.0.0.0 (8) service_healthy (9)
   exec (10) createsuperuser




    5.12 Registries, tagging and CI/CD
📚 Sources: Unit 5 Notes §9.1–9.2       LEC 6 (Docker) Block K       Docker Lab L6     Docker Cheatsheet (Docker Hub)     Unit 3 Notes §9.6

 Complete Revision deck



▸ The image is the deliverable
Deploying with Docker is three steps: tag the image with a registry name, push it, then pull and run it anywhere.
In Lab Level 6 a classmate ran a pushed image on their own laptop with one command: no code, no Python, no
pip. The code, runtime and libraries travel together inside the image, which is what finally solves "works on my
machine".

          docker build              docker tag               docker push                  docker pull                  docker run
          on your laptop
                             →       you/app:1.0
                                                     →          to the registry
                                                                                  →      on any machine
                                                                                                            →       it works there too



           terminal — Lab Level 6 (create a free account at hub.docker.com first)


  # on YOUR laptop
  $ docker login                                                                  # or: docker login -u <username>
  $ docker tag campuspulse:v1 <your-hub-user>/campuspulse:1.0
  $ docker push <your-hub-user>/campuspulse:1.0


  # on your FRIEND's laptop: no clone, no Python, no pip
  $ docker run -d -p 8000:8000 <your-hub-user>/campuspulse:1.0
  # → open http://localhost:8000 … it works on their machine

--- PDF page 353 ---
▸ Where images live

 Registry               What it is

 Docker Hub             The default ( docker.io ). Official images like postgres and nginx. Free public repos; anonymous pulls are rate-
                        limited. Cheat-sheet commands: docker login -u , docker push <username>/<image_name> ,
                         docker search , docker pull

 GitHub                  ghcr.io/<you>/<repo> . Lives next to your code; pushed from GitHub Actions with the built-in token
 Container
 Registry

 Cloud registries       Amazon ECR, Google Artifact Registry, Azure ACR. Private, close to where you deploy, with IAM permissions

 Self-hosted            Harbor (with scanning and replication), or the tiny registry:2 image for a lab or an air-gapped network


A registry is to images what GitHub is to code, or PyPI is to Python packages.


▸ A tagging strategy that will not hurt you later

 Tag                        Example                      Changes?                         Use it for

 Semantic version            1.4.2 , 1.4 , 1               1.4.2 never changes            Releases; what production runs

 Git commit SHA              sha-3f2a9c1                 Never                            Tracing an image back to its exact code

 Branch                      main , dev                  Moves every push                 Test and staging environments

  latest                     latest                      Moves every push                 Convenience only. Never in production

 Digest                      @sha256:9f3c…               Impossible to change             Deploying exactly what was tested



  🔑 RULE
  Never push different content under a version tag that already exists, and never run latest in production.
  If 1.4.2 can change, nobody can say what is running.



▸ Arm vs Intel: "exec format error"
Apple M-series Macs build arm64 images; most servers are amd64 . Running the wrong one gives
 exec format error . Build for both at once with buildx:

            terminal


  docker buildx build --platform linux/amd64,linux/arm64 -t <you>/campuspulse:1.0 --push .




▸ CI/CD: from git push to a running image, with no hands
Continuous Integration and Delivery automates the path from code to server. On every git push , a pipeline
such as GitHub Actions starts a fresh machine and runs the same steps every time, so nothing depends on any‐
one's laptop.

--- PDF page 354 ---
git push                build                     test                           scan                         push
          you
                        →   buildx + cache
                                             →     run it, curl /health
                                                                           →       docker scout / trivy
                                                                                                          →      ghcr.io, tagged
                                                                                                                                    →

                                                                 deploy
                                                         server pulls & restarts



           .github/workflows/docker-publish.yml (simplified from the lab)


  name: docker-publish
  on:
     push:
        branches: [main]
        tags: ["v*"]


  jobs:
     docker:
        runs-on: ubuntu-latest
        permissions:
           contents: read
           packages: write
        steps:
           - uses: actions/checkout@v4
           - uses: docker/setup-buildx-action@v3
           - uses: docker/login-action@v3
             with:
                registry: ghcr.io
                username: ${{ github.actor }}
                password: ${{ secrets.GITHUB_TOKEN }}
           - uses: docker/build-push-action@v6
             with:
                context: .
                file: Dockerfile.prod
                push: true
                tags: |
                   ghcr.io/${{ github.repository }}:latest
                   ghcr.io/${{ github.repository }}:sha-${{ github.sha }}


The lab's full workflow also tags by branch and version and caches layers between runs. GHCR needs a lower-case repository name.



▸ Deploying on a server (Unit 3 droplet)
Because the whole application is one compose file, deploying to a DigitalOcean droplet is mostly installing
Docker on the server:

           terminal — Unit 3 §9.6

--- PDF page 355 ---
ssh root@<droplet-ip>
  curl -fsSL https://get.docker.com | sh                                  # install Docker
  git clone <your-repo-url> app && cd app
  # create .env with real passwords; add <droplet-ip> to DJANGO_ALLOWED_HOSTS
  docker compose up -d --build



In the droplet's firewall allow SSH and the one public port (8080 for the nginx entrance in Unit 3), then open
 http://<droplet-ip>:8080 . On a bare droplet you would install Python, nginx and PostgreSQL by hand (LEC
8: apt install python3-pip nginx , gunicorn notes.wsgi ) and keep them configured. With Compose, the
file is the server setup , and an identical stack runs on the laptop and on the server. A CI-built image can be used
instead of building on the server: set image: ghcr.io/you/imap-django:1.0 in place of build: . , then
 docker compose pull && docker compose up -d .




    5.13 Deployment and security
📚 Sources: Unit 5 Notes §9.3–9.4         LEC 6 (Docker) Block L           Docker Lab L6          Unit 3 Notes §9.3, §11    One-Shot Revision



▸ A production stack
A real deployment adds four things around the app:

    A reverse proxy: nginx is the only service open to the outside and forwards requests to the app.
    Scaling: the app runs as several identical copies (replicas), and nginx spreads requests across them.
    Separate networks: the proxy sits on a frontend network and the database on a backend one, so the proxy
    cannot even reach the database.
    Limits: each copy gets a fixed share of CPU and memory, so one cannot starve the others.


                             frontend network

                                                                                                                                   backend network

                                                                                   web-1
                                                                                                                           db (postgres)
        Internet                   proxy (nginx)                                                                      volume pgdata · healthcheck

       → port 8080                    ports 8080:80
                                                                                   web-2
                                  the ONLY public port

                                                                                                                           cache (redis)
                                                            round-robin
                                                                                   web-3                                   no published port

                                proxy cannot resolve "db"                  256M · 0.5 CPU · read-only




Figure 5.8 — Lab Level 6 production stack: one public entrance, three web replicas on both networks, data services only on the backend network.


           compose.prod.yaml (Lab Level 6, condensed)


  services:
     proxy:
        image: nginx:alpine

--- PDF page 356 ---
ports: ["8080:80"]                         # the ONLY published port
        volumes:
           - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
        networks: [frontend]
        depends_on: [web]


     web:
        build:
           context: .
           dockerfile: Dockerfile.prod
        environment:
           DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
           REDIS_URL: redis://cache:6379/0
        read_only: true                           # immutable filesystem
        tmpfs: [/tmp]                              # gunicorn still needs a writable temp dir
        deploy:
           resources:
             limits: { cpus: "0.50", memory: 256M }
        networks: [frontend, backend]              # no ports: 3 replicas can't all own host port 8000
        depends_on:
           db: { condition: service_healthy }
           cache: { condition: service_started }
        restart: unless-stopped


     db:
        image: postgres:16-alpine
        # environment, volumes and healthcheck exactly as in §5.10
        networks: [backend]


     cache:
        image: redis:7-alpine
        networks: [backend]


  networks:
     frontend:
     backend:


  volumes:
     pgdata:



            nginx/nginx.conf (load-balancing part from the lab + a minimal server block)


  resolver 127.0.0.11 valid=5s;             # Docker's embedded DNS
  upstream campuspulse {
     zone campuspulse 64k;
     server web:8000 resolve;               # "web" resolves to every replica

--- PDF page 357 ---
}
  server {
      listen 80;
      location / {
          proxy_pass http://campuspulse;
          proxy_set_header Host $host;
      }
  }



              terminal — scale to three, then prove the hardening (Lab Level 6)


  $ docker compose -f compose.prod.yaml up -d --build --wait --scale web=3
  $ for i in 1 2 3 4 5 6; do curl -s localhost:8080/api/results; echo; done
  …"served_by":"0d0f1c3404d2"
  …"served_by":"602a7a3e7d14"
  …"served_by":"7a15fbf34bce"
  …"served_by":"0d0f1c3404d2"                       # round-robin
  $ docker compose -f compose.prod.yaml up -d --scale web=5 --no-recreate               # grow without restart‐
  ing
  $ docker compose -f compose.prod.yaml exec web id
  uid=10001(appuser) gid=10001(appuser) groups=10001(appuser)
  $ docker compose -f compose.prod.yaml exec web touch /app/hacked
  touch: cannot touch '/app/hacked': Read-only file system
  $ docker compose -f compose.prod.yaml exec proxy nc -zv db 5432
  nc: bad address 'db'                            # frontend can't see backend
  $ docker stats --no-stream
  pulseprod-web-1         52.06MiB / 256MiB




▸ Threat model: every container shares the host's kernel
Containers are strongly isolated, but not as strongly as virtual machines. A container is a box, not a vault.

      A kernel bug or a misconfiguration can turn "inside the container" into "root on the host".
      --privileged switches off almost every protection. Never use it for apps.

      Mounting /var/run/docker.sock into a container gives it full control of Docker, which is effectively host
      root.
      Being in the docker group = root on that machine.
      Hard multi-tenant isolation still needs VMs (or sandboxes such as gVisor, Kata Containers, Firecracker).


▸ Ten habits of a secure image

 Habit                           How

 Run as non-root                  RUN useradd --create-home --uid 10001 appuser + USER appuser

 Minimal base                    slim or distroless: fewer packages, fewer CVEs

 Pin versions                    Base image, pip packages, CI actions

--- PDF page 358 ---
Habit                             How

 No secrets in images              Not in ENV , ARG or COPY ; supply at run time

  .dockerignore                    Keeps .env , .git and keys out of the build

 Scan every build                   docker scout cves , trivy image ; fail CI on critical findings

 Read-only root filesystem          --read-only + --tmpfs /tmp (Compose: read_only: true )

 Drop capabilities                  --cap-drop ALL , add back only what is needed

 Limit resources                    --memory , --cpus , --pids-limit

 Rebuild regularly                 Picks up security patches in the base image



▸ Secrets: anyone who can pull your image can read its ENV

            terminal — measured with the lab's Dockerfile.broken


  # Dockerfile.broken contains:             ENV DATABASE_PASSWORD=supersecret123
  $ docker inspect pulse:broken --format '{{.Config.Env}}'
  [… DATABASE_PASSWORD=supersecret123 …]
  # BuildKit even warned at build time:
  # SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data



Deleting a secret in a later layer does not help: it is still in the earlier layer, and docker history or
 docker save will show it.

 Method                                                                              Good for

  -e / environment: at run time                                                      Local development

  .env file (git-ignored)                                                            Development and small deployments

 Compose secrets: → mounted as files in /run/secrets/…                               Never visible in env or inspect

  RUN --mount=type=secret                                                            Build-time tokens (private pip or npm)

 Vault / AWS / Azure secret manager                                                  Production



▸ Supply chain: trust what you pull, prove what you push

 Practice               How

 Scan for CVEs           docker scout quickview campuspulse:v1 , docker scout cves campuspulse:v1 ,
                         trivy image campuspulse:v1

 Trusted bases          Prefer Docker Official Images and verified publishers; a random cool-python:latest could contain
                        anything

 SBOM +                  docker buildx build --sbom=true --provenance=true … records every package inside and
 provenance             how the image was built

 Sign images             cosign sign ghcr.io/you/app@sha256:… , then have the cluster refuse unsigned images

--- PDF page 359 ---
▸ Deployment mistakes, grouped by layer (Unit 3 §11)

 Mistake                            Risk                                 Fix

 Keys hard-coded in code /          Leaks through GitHub or the          Environment variables and a .env kept out of Git and out of
 image                              registry                             the image

 Database port open to              Direct attacks                       Do not publish it, or allow only the app
 everyone

  DEBUG = True in                   Exposes secrets and settings          DEBUG = False (from the environment)
 production

 No backups                         Permanent data loss                  Volume backups, pg_dump




     5.14 Limitations of Docker containers
📚 Sources: Not in your files — added from standard references      hints in LEC 6 (Docker) Blocks B, H, L, M   Unit 5 Notes §3, §9.4


     🚨 NOT IN YOUR STUDY MATERIAL · PART OF 10 MARKS · FINAL 2024-25 Q6(B) · GAP G15
     None of your files has a "limitations of Docker" list. They contain scattered hints: containers share one
     kernel so isolation is "not VM-strong" (LEC 6 Block L), Linux containers need a Linux kernel (Block B), the
     writable layer dies with the container (Block H), exec format error on the wrong CPU (Block M). The
     examiner wants a clear list.

     Verdict: MUST LEARN. It is about 3 of the 10 marks in that question, "limitations/disadvantages" is a
     standard sub-part for any technology, and it costs ten minutes because you already know every reason
     from §5.2–5.13. Learn the table below; in the exam write 6–8 of the rows, one or two lines each.


 #     Limitation                  Why it happens                                                How teams work around it

 1     Weaker isolation            All containers share the host kernel. A kernel bug or a       VMs for hard multi-tenancy;
       (security)                  misconfiguration ( --privileged , a mounted dock‐             gVisor/Kata/Firecracker; non-root, --
                                   er.sock) lets a container escape to the host                  cap-drop ALL , rootless Docker

 2     Tied to the host            A container cannot bring its own kernel: no Windows           Use a VM when you need another OS or
       kernel/OS                   app on a Linux host, no different kernel version, no cus‐     kernel
                                   tom kernel modules

 3     Overhead on                 Docker Desktop runs a hidden Linux VM (WSL2 / Apple           Linux servers in production; volumes in‐
       Windows/macOS               Virtualization): extra RAM, slower bind-mount file I/O.       stead of bind mounts for heavy I/O
                                   Near-native only on Linux

 4     CPU architecture            An image built for arm64 (M-series Mac) fails on amd64         docker buildx build --plat‐
       dependence                  servers: exec format error                                    form linux/amd64,linux/arm64

 5     Ephemeral storage           The writable layer is deleted with the container; data is     Named volumes, backups, network/cloud
                                   lost unless it is in a volume, and volumes live on one        storage
                                   host

 6     Stateful apps and data‐     Backups, major-version upgrades, data portability and         Volumes + scheduled backups, or a man‐
       bases need care             disk performance all need planning                            aged database (e.g. RDS) in production

 7     GUI/desktop apps are        Containers are built for server processes and CLIs;           X11/VNC forwarding, or just use a
       awkward                     there is no display                                           VM/native install

--- PDF page 360 ---
#       Limitation                    Why it happens                                             How teams work around it

 8       Networking complexity         NAT and port mapping, "port is already allocated", the     User-defined networks, service names,
                                       localhost trap, multi-host networking needs overlay        Compose
                                       networks

 9       No orchestration at           Docker and Compose manage one host: no automatic           Kubernetes, Docker Swarm, AWS ECS
         scale by itself               failover across machines, auto-scaling or rolling
                                       updates

 10      Root daemon and sup‐           dockerd runs as root and the docker group equals          Rootless Docker/Podman, official images,
         ply-chain risk                root; public images may contain vulnerabilities or mal‐    scanning, signing, run-time secrets
                                       ware; secrets leak through ENV/layers

 11      Monitoring and debug‐         Short-lived containers, logs disappear with docker         Log to stdout + central logging,
         ging are harder               rm , distroless images have no shell, many moving          healthchecks, docker
                                       parts                                                      logs/inspect/exec , metrics tools

 12      Image sprawl and disk         Old images, stopped containers and build cache pile          docker system df , docker
         usage                         up: "no space left on device"                              system prune , slim and multi-stage
                                                                                                  images

 13      Learning curve and            Dockerfiles, YAML, volumes, networks; common mis‐          Templates and the best-practice rules of
         misconfiguration              takes (latest tag, root user, secrets in images)           §5.15



▸ So when is a VM still the better choice?

 Choose a VM when…                                                          Choose containers when…

 You need a different OS or kernel (Windows on Linux)                       You are packaging and shipping your own app

 Untrusted tenants share the hardware (hard isolation)                      You run many small services (microservices) on one host

 A legacy or desktop/GUI application                                        You want identical dev, CI and production environments

 You need kernel modules or full system control                             You need fast start-up and high density


In practice both: VMs isolate customers, containers pack apps (§5.2).


     PYQ       Final 2024-25 · Q6(b)     Re-Exam 2023-24 · Q6(b)                                                                      10 M


  Final 2024-25 Q6(b): How Docker differs from traditional virtualization? Any 3 Docker commands
  dealing with container. Limitations of Docker container?
  Re-Exam 2023-24 Q6(b): Difference between Docker and Virtual Machine? Docker commands dealing
  with images.

     ✓   MODEL ANSWER — WRITE THIS

  Part 1 is common. Then: 2024-25 → Parts 3 and 4 (container commands + limitations). 2023-24 → Part 2 (image commands).


  PART 1 · DOCKER VS TRADITIONAL VIRTUALISATION (VIRTUAL MACHINES)

  Traditional virtualisation uses a hypervisor (Type 1 bare-metal: VMware ESXi, Hyper-V, KVM; Type 2 host‐
  ed: VirtualBox) to divide one physical machine into several virtual machines. Each VM gets virtual CPU,
  RAM, disk and network, and boots a complete guest operating system with its own kernel.

--- PDF page 361 ---
Docker uses OS-level virtualisation (containerisation). Applications run in containers: isolated process‐
  es that share the host OS kernel. The Docker Engine creates them using Linux namespaces (what a
  process can see) and cgroups (what it can use). A container carries only the app and its libraries, not an
  OS.

                 diagram to draw


             VIRTUAL MACHINES                                      DOCKER CONTAINERS
       +-------+-------+-------+                          +-------+-------+-------+
       | App A | App B | App C |                          | App A | App B | App C |
       | Bins/ | Bins/ | Bins/ |                          | Bins/ | Bins/ | Bins/ |
       | libs        | libs     | libs     |              | libs       | libs   | libs    |
       | Guest | Guest | Guest |                          +-------+-------+-------+
       |    OS       |   OS     |    OS    |              |       Docker Engine           |
       +-------+-------+-------+                          +-----------------------+
       |          Hypervisor               |              | Host OS (ONE kernel)          |
       +-----------------------+                          +-----------------------+
       |             Host OS               |              |      Infrastructure           |
       +-----------------------+                          +-----------------------+
       |        Infrastructure             |
       +-----------------------+



    Basis                     Virtual machine (traditional)                      Docker container

    Virtualises               Hardware                                           Operating system (user space)

    Managed by                Hypervisor                                         Docker Engine

    Operating                 Full guest OS + own kernel in every VM             No guest OS; shares the host kernel
    system

    Size                      Gigabytes                                          Megabytes (alpine 12 MB)

    Start-up time             Tens of seconds to minutes (OS boots)              About a second (a process starts)

    Density                   2–3 per laptop                                     Dozens per laptop, hundreds per server

    Resource use              Fixed CPU/RAM reserved per VM                      Uses only what the process needs; limits via cgroups

    Isolation                 Strong, hardware level                             Process level (namespaces); weaker

    OS flexibility            Any OS on any host (Windows on Linux)              Must match the host kernel (Linux containers need
                                                                                 Linux)

    Portability               Heavy VM images, hard to share                     Small layered images shared via registries (Docker Hub)

    Use case                  Different OSes, legacy apps, multi-tenant          Packaging apps, microservices, CI/CD
                              isolation


  Example: running three Django apps needs three VMs, each booting its own OS (gigabytes, minutes), or
  three containers from three images sharing one kernel (megabytes, seconds). Conclusion: VMs give
  stronger isolation; containers give speed, density and portability. In the cloud they are combined: containers
  run inside VMs.

--- PDF page 362 ---
PART 2 · DOCKER COMMANDS DEALING WITH IMAGES (2023-24)

    Command                       Purpose                                       Example

     docker build -t              Build an image from the Dockerfile in the      docker build -t myapp:1.0 .
    name:tag .                    current folder

     docker build --no-           Build without using cached layers              docker build --no-cache -t
    cache                                                                       myapp:1.0 .

     docker images                List all local images                          docker images

     docker pull                  Download an image from Docker Hub              docker pull python:3.12-slim

     docker tag                   Give an image a new name/tag for a registry    docker tag myapp:1.0
                                                                                asha/myapp:1.0

     docker login + docker        Log in and upload the image to a registry      docker push asha/myapp:1.0
    push

     docker search                Search Docker Hub for an image                 docker search nginx

     docker history               Show the layers of an image and their sizes    docker history myapp:1.0

     docker image inspect         Detailed metadata (env, CMD, layers)           docker image inspect myapp:1.0

     docker rmi                   Delete an image                                docker rmi myapp:1.0

     docker image prune           Remove unused (dangling) images                docker image prune -a

     docker save / docker         Export / import an image as a .tar file        docker save -o myapp.tar
    load                                                                        myapp:1.0


              typical image workflow


     docker pull python:3.12-slim                         # get the base image
     docker build -t myapp:1.0 .                          # build from the Dockerfile
     docker images                                        # check it exists
     docker tag myapp:1.0 asha/myapp:1.0                  # name it for Docker Hub
     docker login -u asha && docker push asha/myapp:1.0
     docker rmi myapp:1.0                                 # remove the local copy



  PART 3 · THREE DOCKER COMMANDS DEALING WITH CONTAINERS (2024-25)

  1. docker run — creates a new container from an image and starts it (pulling the image first if needed).
  Syntax: docker run [OPTIONS] IMAGE [COMMAND] . Key options: -d background, --name name,
    -p host:container publish a port, -e environment variable, -v volume, --rm delete on exit, -it in‐
  teractive terminal.

              example


     docker run -d --name web -p 8080:80 nginx:alpine                  # open http://localhost:8080



  2. docker ps — lists running containers with ID, image, status, ports and name; docker ps -a also
  shows stopped (exited) containers.

--- PDF page 363 ---
example


     $ docker ps
     CONTAINER ID       IMAGE             STATUS             PORTS                           NAMES
     3f1c9e0b7a…        nginx:alpine      Up 5 seconds       0.0.0.0:8080->80/tcp            web



  3. docker stop / docker start / docker rm — stop gracefully stops a running container (SIGTERM,
  then SIGKILL after 10 s); start starts an existing stopped container again; rm removes a stopped con‐
  tainer ( rm -f removes a running one).

              example


     docker stop web && docker rm web


  Also worth one line each: docker exec -it web sh (shell inside a running container), docker logs -f web (follow its
  output), docker inspect web (full configuration).


  PART 4 · LIMITATIONS OF DOCKER CONTAINERS (2024-25)

    1. Weaker isolation: all containers share the host kernel, so a kernel vulnerability or misconfiguration
       ( --privileged ) can let a container reach the host; VMs isolate more strongly.
    2. OS/kernel dependence: Linux containers need a Linux kernel; a Windows app cannot run on a Linux
       host; on Windows/macOS Docker Desktop must run a hidden Linux VM, adding overhead.
    3. Ephemeral storage: data written inside a container is lost when it is removed; persistent data needs
       volumes and backups, so databases need extra care.
    4. Platform/architecture issues: an image built for arm64 fails on amd64 ("exec format error") unless built
       for both.
    5. Networking complexity: port mappings, port conflicts, service-name DNS and multi-host networking
       are hard to get right.
    6. No built-in orchestration at scale: Docker alone runs on one host; auto-scaling, failover and rolling
       updates need Kubernetes or Swarm.
    7. Security of images and daemon: the daemon runs as root; public images may contain vulnerabilities;
       secrets put in images can be read with docker inspect .
    8. Not suited to GUI apps, harder monitoring, and disk usage from old images and caches (needs
        docker system prune ).


  🎯 Marking scheme guess: 2024-25: differences with diagram/table 4 M + three container commands with syntax and example 3 M + limi‐
  tations (any 6) 3 M. 2023-24: differences with diagram/table 5 M + image commands 5 M (aim for 8–10 commands with purpose and
  example).




    5.15 Best practice and the debugging playbook
📚 Sources: Unit 5 Notes §10      LEC 6 (Docker) Block M    Unit 3 Notes §11    Docker Lab (setup slide)

--- PDF page 364 ---
▸ Twelve rules worth memorising

 #     Rule                                             Why

 1     Pin a slim base: python:3.12-slim                Small and reproducible; latest moves

 2     Dependencies first, code last                    The slow install layer stays cached (1.0 s vs 5.4 s)

 3     One concern per container                        web, database and cache are separate services you can scale and restart
                                                        independently

 4     Exec-form CMD ["…"]                              The app is PID 1 and receives stop signals

 5     Bind to 0.0.0.0 inside containers                127.0.0.1 refuses traffic from outside the container

 6      .dockerignore everything you do not need        Keeps .env, .git and venv out; faster builds

 7     Configuration via environment variables          One image for dev, test and production

 8     Log to stdout/stderr, not files                  So docker logs can show it

 9     State in volumes, never in the container         The writable layer dies with the container

 10    Non-root USER , read-only filesystem             Limits the damage of a break-in

 11     HEALTHCHECK + depends_on:                       Started is not ready
       service_healthy

 12    Tag immutably; latest is not a version           You always know what is running



▸ "It doesn't work." Check these in order

 1         docker ps -a — is it running? Status and exit code: Exited (1), (137), (127)? Restarting in a loop?


 2         docker logs <c> — what does it say? Read the actual error. About 90% of problems end here.


 3         docker inspect <c> — how is it configured? Ports, env vars, mounts, networks, IP, health status.


 4         docker exec -it <c> sh — look inside. Check env , ls , curl the app from inside.


 5        Network check. Same network? Service name, not localhost? App bound to 0.0.0.0?

 6         docker compose config — see the final YAML after .env substitution.



▸ Errors you will meet, and what they mean

 You see…                                          Cause                                  Fix

  Cannot connect to the Docker daemon              The daemon is not running              Start Docker Desktop (Linux: sudo
                                                                                          systemctl start docker )

  port is already allocated                        Something on the host already           -p 8001:8000 , or stop the other
                                                   uses that port                         container

  pull access denied … does not exist              Typo in the image name, or a pri‐      Check spelling; docker login
                                                   vate repository

  exec format error                                Image built for arm64, running on       buildx --platform
                                                   amd64 (or the reverse)                 linux/amd64,linux/arm64

--- PDF page 365 ---
You see…                                                 Cause                                 Fix

  permission denied … docker.sock                         Your user is not allowed to talk to   Linux: add yourself to the docker group;
                                                          the daemon                            start Docker Desktop

  connection refused to the database                      Using localhost, or the db is not     Use the service name; healthcheck +
                                                          ready yet                             retry

  Exited (137)                                            Out of memory, or killed              Raise --memory ; check
                                                                                                 OOMKilled in docker inspect

  no space left on device                                 Old images, containers and build       docker system df , docker
                                                          cache                                 system prune

  Database is uninitialized and supe‐                     postgres image started with no        Set it (from .env)
 ruser password is not specified                           POSTGRES_PASSWORD

 Changed ./sql files, nothing happened                    Init scripts run only on an empty     Apply with psql, or docker compose
                                                          volume                                down -v (wipes data)

 Admin page unstyled after containerising Django          DEBUG off, static files not served    collectstatic + WhiteNoise (§5.11)



   ✏️ DRILL 8 · DIAGNOSE IT — FIRST COMMAND AND FI X
    1. docker ps -a shows Exited (137) for api , which has --memory 256m .
    2. In docker compose up , the db container stops at once. Its log: "Database is uninitialized and supe‐
       ruser password is not specified".
    3. docker pull postgress:16 → "pull access denied".
    4. Django logs:
        connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused .

    5. An image built on your M2 MacBook fails on the college server with "exec format error".
    6. You changed a value in .env but the container still seems to get the old one. Which command shows
       what Compose is really using?
    7. Laptop warns "no space left on device" after weeks of builds.
    8. The command docker ps prints "Cannot connect to the Docker daemon".

   🔓 Answer key: 1) Out of memory (OOM-killed): docker inspect api → OOMKilled true; raise --memory 2) Set
   POSTGRES_PASSWORD in the db environment (from .env) 3) Typo: postgres:16 4) Localhost trap: HOST must be the service name db
   (and wait with a healthcheck) 5) Wrong CPU architecture:
    docker buildx build --platform linux/amd64,linux/arm64 … --push 6) docker compose config (then
    docker compose up -d to recreate with the new value) 7) docker system df , then docker system prune 8) Start
   Docker Desktop (the daemon is not running)




    5.16 The Docker Lab, level by level
📚 Sources: Docker Lab        LEC 6 (Docker)     Unit 5 Notes


The lab containerises one small app, CampusPulse, a live canteen poll ("Best canteen snack?" Samosa,
Masala Dosa, Maggi, Chole Bhature), one level at a time. The page footer shows which container answered,
where votes are stored and whether Redis is on, so every level visibly changes something. Its behaviour is dri‐
ven only by environment variables:

--- PDF page 366 ---
Environment variable                                                 Effect

 (nothing set)                                                        Votes in a SQLite file at /data/votes.db

  DATABASE_URL                                                        Votes in PostgreSQL instead

  REDIS_URL                                                           Adds a page-view counter in Redis

  POLL_QUESTION / POLL_OPTIONS                                        Change the poll without touching code


            setup check (2 minutes)


  $ docker version --format "{{.Server.Version}}"
  29.3.1
  $ docker compose version
  Docker Compose version v5.1.1
  $ cd docker-lab && ls
  README.md       campuspulse/       challenge/      level1-hello/


Windows: commands are identical in PowerShell and Git Bash unless noted. PowerShell differences: end a continued line with a back‐
tick instead of \ ; ${PWD} instead of $(pwd) ; copy .env.example .env ; no <<'EOF' ; loop with
 1..6 | % { curl.exe -s localhost:8080/api/results } .

 Level              What you did                                  Key commands                                What it teaches (section)

 L0 Warm-up         hello-world; nginx on 8080; a throw-away       run , ps , ps -a , images ,                Architecture flow, lifecycle,
 (10 min)           Ubuntu shell; deleted a container's own        logs , exec -it , stop , rm -              PID 1, hostname = contain‐
                    filesystem; edited nginx's page inside a      f                                           er ID, writable layer (§5.4,
                    container and lost it                                                                     §5.7)

 L1 First image     5-line Dockerfile for hello.py; saw "Linux"    build -t , run --rm , -e                   Dockerfile basics, ENV,
 (15 min)           on a Windows laptop; overrode ENV;            NAME=Priya , build -f , --en‐               CMD vs ENTRYPOINT
                    ENTRYPOINT vs CMD with pinger                 trypoint , history                          (§5.6)

 L2                 Built and ran CampusPulse with guni‐           build -t campuspulse:v1 . ,                Layer cache order, slim
 Containerise       corn; voted; measured cache (1.0 s vs          run -d --name pulse -p                     base, .dockerignore, 0.0.0.0
 (20 min)           5.4 s) and size (235 MB slim vs 1.65 GB       8000:8000 , logs , curl                     (§5.5, §5.6)
                    full)                                         /api/results

 L3 Persist (10     Watched votes vanish on rm ; added a           volume create pulse-data , -               Code in images, data in vol‐
 min)               named volume; votes survived                  v pulse-data:/data , volume                 umes (§5.8)
                                                                  inspect

 L4 Connect (15     Network + Postgres + Redis + web,              network create pulse-net , -               Service discovery, no -p
 min)               wired by hand; same image, now on             -network , -e DATABASE_URL=…                on db, one image many
                    PostgreSQL; DNS by name                       @pulse-db… , exec … gethost‐                configs (§5.9)
                                                                  byname , network inspect

 L5 Compose         Same stack from one YAML; .env;                cp .env.example .env , com‐                Compose anatomy, started
 (25 min)           healthcheck; proved down keeps data           pose up -d --build --wait ,                 ≠ ready, secrets in .env
                    and down -v wipes it; Adminer profile;         compose ps , logs -f web ,                 (§5.10)
                    live reload                                    down / down -v , --profile
                                                                  tools , watch

--- PDF page 367 ---
Level                 What you did                               Key commands                        What it teaches (section)

 L6 Production         Multi-stage non-root image with             -f compose.prod.yaml up --         Multi-stage, hardening,
 (15 min)              healthcheck; nginx proxy, two networks,    scale web=3 , exec web id ,         scaling, registries, CI/CD
                       limits, read-only FS; scaled to 3 and 5;    login , tag , push , buildx -      (§5.6, §5.12, §5.13)
                       pushed to Docker Hub; CI workflow          -platform

 ★ Challenge           Fix Dockerfile.broken (7 prob‐              build output, logs , inspect ,     Everything above (drills 9
 (15 min)              lems) and compose.broken.yaml               run --rm pulse:broken ls / ,       and 10 below)
                       (6 problems)                                whoami



   ✏️ DRILL 9 · LAB CHALLENGE PART A — FI ND T HE 7 PRO BLE MS
   Some problems break the build, some build fine but make the app unreachable, some "work" but are dan‐
   gerous or slow. Fixing one error may reveal the next.

                Dockerfile.broken


     FROM python:latest
     ENV DATABASE_PASSWORD=supersecret123
     COPY . .
     RUN pip install requirements.txt
     EXPOSE 8000
     CMD ["flask", "run"]



   🔓 Answer key:
     1. FROM python:latest — unpinned: latest moved to Python 3.14, where psycopg-binary==3.2.9 has no build, so
         the build fails; it is also the 1.65 GB full image. Fix: python:3.12-slim .
     2. ENV DATABASE_PASSWORD=… — secret baked into the image; anyone can read it with docker inspect / history .
         Fix: delete it; pass it at run time ( -e / .env).
     3. No WORKDIR — the code is copied into / among the system folders ( docker run --rm pulse:broken ls / ). Fix:
          WORKDIR /app .
     4. COPY . . before installing — every code edit re-installs all packages (cache busted). Fix: copy requirements.txt first,
         install, then COPY . . .
     5. pip install requirements.txt — missing -r : pip looks for a package literally named "requirements.txt" and the
         build fails. Fix: pip install --no-cache-dir -r requirements.txt .
     6. CMD ["flask", "run"] — development server, listens on 127.0.0.1:5000: unreachable from outside and not on the
         EXPOSEd 8000. Fix: gunicorn bound to 0.0.0.0:8000 .
     7. Runs as root ( whoami → root) — dangerous. Fix: create a user and USER appuser .

                Dockerfile (fixed)


     FROM python:3.12-slim
     WORKDIR /app
     COPY requirements.txt .
     RUN pip install --no-cache-dir -r requirements.txt
     COPY . .
     RUN useradd --create-home --uid 10001 appuser \
       && mkdir /data && chown appuser /data
     USER appuser

--- PDF page 368 ---
EXPOSE 8000
     CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "app:app"]




   ✏️ DRILL 10 · LAB CHALLENGE PART B — FIND TH E 6 PR OBLEM S
   Done when /api/results returns JSON and votes survive down → up . (Lab marks: 1 per problem
   found and explained, max 8, + 2 for a working stack.)

               compose.broken.yaml


     services:
        web:
             build: .
             ports:
              - "8000:5000"
             environment:
              DATABASE_URL: postgresql://pulse:secret@localhost:5432/campuspulse
              REDIS_URL: redis://cache:6379/0
             depends_on:
              - db
        db:
             image: postgres:16-alpine
             environment:
              POSTGRES_USER: pulse
              POSTGRES_DB: campuspulse
        cache:
             image: redis:7-alpine



   🔓 Answer key:
     1. "8000:5000" — wrong container port: gunicorn listens on 8000 inside. Fix: "8000:8000" .
     2. @localhost:5432 — the localhost trap; inside web, localhost is web itself. Fix: @db:5432 .
     3. db has no POSTGRES_PASSWORD — Postgres refuses to initialise ("superuser password is not specified") and exits. Fix: add
       it.
     4. The password secret is hard-coded in a file that goes into Git. Fix: ${POSTGRES_PASSWORD} from .env .
     5. depends_on: - db only orders the start; web connects before Postgres is ready. Fix: db healthcheck +
        condition: service_healthy .
     6. No volume on db — votes are lost on down → up . Fix: named volume pgdata:/var/lib/postgresql/data + top-
       level volumes: .

   Bonus points: cache missing from depends_on ; no restart: unless-stopped .

               compose.yaml (fixed)


     services:
        web:
             build: .
             ports:
              - "8000:8000"
             environment:

--- PDF page 369 ---
DATABASE_URL: postgresql://pulse:${POSTGRES_PASSWORD}@db:5432/campuspulse
              REDIS_URL: redis://cache:6379/0
           depends_on:
              db:
                condition: service_healthy
              cache:
                condition: service_started
           restart: unless-stopped
        db:
           image: postgres:16-alpine
           environment:
              POSTGRES_USER: pulse
              POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
              POSTGRES_DB: campuspulse
           volumes:
              - pgdata:/var/lib/postgresql/data
           healthcheck:
              test: ["CMD-SHELL", "pg_isready -U pulse -d campuspulse"]
              interval: 5s
              retries: 10
        cache:
           image: redis:7-alpine
     volumes:
        pgdata:




▸ Wrap-up: clean up everything

           terminal — Lab step 31


  $ docker compose down -v
  $ docker compose -f compose.prod.yaml down -v
  $ docker compose -f compose.broken.yaml down -v
  $ docker rm -f pulse pulse-web pulse-db pulse-cache web 2>/dev/null
  $ docker network rm pulse-net
  $ docker volume rm pulse-data pulse-pg
  $ docker system df                # what's left
  $ docker system prune             # stopped containers, unused networks, dangling images
  # docker system prune -a also deletes unused images (keep them to practise offline)

--- PDF page 370 ---
5.17 Master command reference
📚 Sources: Docker Cheatsheet          LEC 6 (Docker) cheat sheets 1–2    Docker Lab   Unit 3 Notes §4.2, §9.5

 One-Shot Revision (appendix)     Complete Revision deck


Every command from the Docker cheat sheet, both lecture cheat-sheet slides, the lab and the revision decks,
grouped the way exam questions ask for them. Syntax pattern:
 docker [object] verb [OPTIONS] target [COMMAND] ; most short forms have a long form ( docker ps =
 docker container ls , docker images = docker image ls , docker rmi = docker image rm ).


▸ A · General and system

 Command                         What it does                             Important flags              Example

  docker version /               Client and server (daemon) versions       --format                     docker version --format
  docker --version                                                                                     "{{.Server.Version}}"

  docker info                    System-wide information: containers,     —                             docker info
                                 images, storage driver

  docker --help                  Help; works on every subcommand          —                             docker run --help

  dockerd (cheat sheet:          Start the daemon. Desktop does it        —                             sudo systemctl start
  docker -d )                    for you                                                               docker

  docker system df               Disk used by images, containers, vol‐     -v                           docker system df
                                 umes, build cache

  docker system                  Remove stopped containers, unused         -a unused images too,        docker system prune -a
 prune                           networks, dangling images, build          --volumes , -f              --volumes (everything unused!)
                                 cache

  docker builder                 Clear the build cache                     -a                           docker builder prune
 prune



▸ B · Images

 Command                 What it does              Important flags                       Example

  docker build           Build an image from         -t , -f , --no-cache , --              docker build -t app:1.0 .
                         a Dockerfile              build-arg , --target , --
                                                   platform

  docker build -         Build without the         —                                        docker build --no-cache -t
 -no-cache               cache                                                           app:1.0 .

  docker build -         Build from a differ‐      —                                        docker build -f Dockerfile.prod
 f                       ently named                                                     -t app:prod .
                         Dockerfile

  docker images          List local images           -a , -q , --filter                     docker images

  docker pull            Download an image           --platform                             docker pull nginx:alpine

--- PDF page 371 ---
Command                What it does                Important flags                Example

  docker tag            Add a name/tag to           —                                  docker tag app:1.0 you/app:1.0
                        an image

  docker push           Upload an image to          —                                  docker push you/app:1.0
                        a registry

  docker rmi            Delete an image             -f                                 docker rmi app:1.0

  docker image          Remove unused               -a , -f                            docker image prune
 prune                  (dangling) images

  docker                Layers, instructions        --no-trunc                         docker history app:1.0
 history                and sizes

  docker image          Image metadata              --format                           docker image inspect app:1.0
 inspect                (JSON)

  docker save /         Image    ⇄ .tar file        -o / -i                            docker load -i app.tar
  docker load

  docker buildx         Multi-architecture          --platform , --push                docker buildx build --platform
 build                  build                                                      linux/amd64,linux/arm64 -t
                                                                                   you/app:1.0 --push .



▸ C · Container lifecycle

 Command                  What it does                   Important flags     Example

  docker run --           Create and run a con‐          —                   docker run --name web nginx:alpine
 name                     tainer with a custom
                          name

  docker run -p           Run and publish con‐           host:container      docker run -p 8080:80 nginx:alpine
                          tainer port(s) to the
                          host

  docker run -d           Run in the background          —                   docker run -d -p 8000:8000 --name web
                                                                             app:1.0

  docker run --rm         Interactive throw-away         —                   docker run --rm -it ubuntu:24.04 bash
 -it                      container

  docker run -e /         Env var / volume /             —                   docker run -d --name db -e
 -v / --network           network                                            POSTGRES_PASSWORD=secret -v
                                                                             pgdata:/var/lib/postgresql/data
                                                                             postgres:16

  docker create           Create without starting        same as run         docker create --name web nginx

  docker start |          Start or stop an exist‐        -t (stop timeout)   docker stop web
  stop                    ing container

  docker restart          Restart / stop immedi‐         —                   docker kill web
 / kill                   ately (SIGKILL)

  docker pause /          Freeze / resume                —                   docker pause web
  unpause

--- PDF page 372 ---
Command                What it does                  Important flags           Example

  docker rm             Remove a stopped               -f running too            docker stop web && docker rm web
                        container

  docker rm -f          Remove ALL                    —                         clean-up
 $(docker ps -          containers
 aq)

  docker ps /           Running containers /           -a , -q , --fil‐          docker ps -a
  docker ps --          all, including stopped        ter
 all                                                  status=exited

  docker contain‐       Remove all stopped             -f                        docker container prune
 er prune               containers



▸ D · Inspect and debug

 Command                               What it does                              Important flags          Example

  docker logs                          Fetch (and follow) a container's logs      -f , --tail              docker logs -f web
                                                                                 50 , -t

  docker exec                          Open a shell / run a command in a          -it , -u , -e            docker exec -it web
                                       running container                                                  sh

  docker inspect                       Inspect a container (IP, env, mounts,      --format                 docker inspect web
                                       health)

  docker stats ( docker con‐           Resource usage stats                       --no-stream              docker stats --no-
 tainer stats )                                                                                           stream

  docker top                           Processes inside a container              —                         docker top web

  docker cp                            Copy files in or out                      —                         docker cp
                                                                                                          web:/app/log.txt .

  docker port                          Port mappings of a container              —                         docker port web



▸ E · Volumes and networks

 Command                                         What it does                  Example

  docker volume create / ls / in‐                Create / list / locate        docker volume create data
 spect                                           volumes

  docker volume rm / prune                       Delete one / all unused       docker volume rm data
                                                 (data lost!)

  docker run -v vol:/path                        Mount a named volume          docker run -v data:/data app

  docker run --mount                             Long, explicit form of -      --mount type=volume,src=data,dst=/data
                                                 v

  docker run -v "$(pwd)":/app                    Bind-mount the current        docker run -v "$(pwd)":/app:ro app
                                                 folder

  docker network create / ls /                   Create / list / inspect       docker network create net
  inspect                                        networks

--- PDF page 373 ---
Command                               What it does                     Example

  docker network connect / dis‐        Attach, detach, delete           docker network connect net web
 connect / rm

  docker run --network                 Start a container on a           docker run --network net --name db
                                       network                          postgres:16-alpine



▸ F · Docker Compose

 Command                          What it does                                 Example

  docker compose up -d --         Build if needed, start the whole stack in         docker compose up -d --build
 build                            the background

  docker compose up --wait        …and block until every healthcheck                docker compose up -d --wait
                                  passes (CI)

  docker compose up --scale       Run several copies of a service                   docker compose up -d --scale
                                                                               web=3

  docker compose up -d            Start just one service (Unit 3: the               docker compose up -d db
 <service>                        database)

  docker compose ps               Status of each service                            docker compose ps

  docker compose logs -f          Follow one service's logs                         docker compose logs -f web

  docker compose exec             Command inside a running service                  docker compose exec db psql -U
                                                                               appuser -d appdb

  docker compose run --rm         One-off command in a fresh container              docker compose run --rm web
                                                                               python seed.py

  docker compose config           Final YAML with variables filled in               docker compose config

  docker compose watch            Live-sync code while developing                   docker compose watch

  docker compose build /          (Re)build images / pull images                    docker compose pull
  pull

  docker compose stop /           Without removing containers                       docker compose restart web
  start / restart

  docker compose down             Remove containers + network, keep                 docker compose down
                                  volumes

  docker compose down -v          …and delete volumes (wipes data)                  docker compose down -v

  -f file / --profile             Other compose file / optional services            docker compose -f com‐
                                                                               pose.prod.yaml up -d



▸ G · Docker Hub, registries and security

 Command                                    What it does                                Example

  docker login -u <username> /              Log in to / out of Docker Hub (or an‐       docker login ghcr.io
  docker logout                             other registry)

  docker search <image_name>                Search Hub for an image                     docker search redis

--- PDF page 374 ---
Command                                           What it does                     Example

  docker pull <image_name>                         Pull an image from Docker Hub    docker pull postgres:16

  docker push                                      Publish an image to Docker Hub   docker push asha/imap-
 <username>/<image_name>                                                            django:1.0

  docker scout quickview / cves                    Vulnerability scan               docker scout cves app:1.0

  trivy image                                      Third-party scanner              trivy image app:1.0

  cosign sign                                      Sign an image by digest          cosign sign
                                                                                    ghcr.io/you/app@sha256:…



  ⚠️ CHEAT-SHEET ERRATA (DO NOT COPY THESE MISTAKES)
        docker -d → today the daemon is dockerd ; Docker Desktop starts it for you.

       The PDF prints –no-cache with a typographic dash; type two hyphens: --no-cache , and put it before
       the dot: docker build --no-cache -t <image_name> .
        docker ps --all = docker ps -a ; docker container stats = docker stats .

       "Docker Desktop is available for Mac, Linux and Windows" is right, but on servers you install Docker
       Engine (Unit 3: curl -fsSL https://get.docker.com | sh ).



   ✏️ DRILL 11 · QUICK-FIRE: WHICH COMMAND?
    1. Show system-wide Docker information.
    2. List every container, including stopped ones.
    3. Watch live CPU/memory of all containers once.
    4. Copy /app/log.txt out of container web into the current folder.
    5. Create a named volume pgdata .
    6. Create a network appnet and start postgres:16 on it named db .
    7. See how much disk Docker is using.
    8. Start the Compose stack and wait until every service is healthy.
    9. Run a one-off python manage.py migrate in a fresh web container.
   10. Search Docker Hub for redis images.

   🔓 Answer key: 1) docker info 2) docker ps -a 3) docker stats --no-stream 4)
    docker cp web:/app/log.txt . 5) docker volume create pgdata 6) docker network create appnet
   then docker run -d --network appnet --name db -e POSTGRES_PASSWORD=secret postgres:16 7)
    docker system df 8) docker compose up -d --wait 9)
    docker compose run --rm web python manage.py migrate 10) docker search redis




    5.18 Likely questions for 2026
📚 Sources: pattern of all three papers   Unit 5 Notes   LEC 6 (Docker)


Docker carried 20 marks in each of the two older papers and none in Final 2025-26, which was scenario-based.
Prepare both the classic theory questions and a hands-on scenario.

--- PDF page 375 ---
#      Likely question                                                              Marks      Answer pointer

 1      Explain Docker architecture with a neat diagram (+ container note /          10         PYQ block end of §5.7: client → REST API →
        commands)                                                                               dockerd → objects     ⇄ registry; docker run
                                                                                                steps

 2      Docker vs virtual machine / traditional virtualisation; limitations of       10         PYQ block end of §5.14: layered diagram + 10-
        containers                                                                              row table + limitations list

 3      Scenario: "Your Django + PostgreSQL project works on your laptop             10         §5.11 Steps 1–6; mention gunicorn, env vars,
        but not on a teammate's. Containerise it: write the Dockerfile and                      HOST = db, migrate at start, WhiteNoise, vol‐
        compose.yaml and explain each line"                                                     ume, healthcheck

 4      Write a Dockerfile for a Python web app and explain each instruction;        6–8        §5.6: CampusPulse Dockerfile + table; layer
        why does instruction order matter?                                                      cache 1.0 s vs 5.4 s; .dockerignore

 5      Differentiate CMD vs ENTRYPOINT, COPY vs ADD, ARG vs ENV, RUN                4–6        §5.6 look-alikes table + pinger example
        vs CMD, EXPOSE vs -p

 6      What is Docker Compose? Write a compose file for web + database              6–10       §5.10 anatomy + key-to-flag table; started ≠
        with a volume and healthcheck. down vs down -v                                          ready; down keeps volumes

 7      Why are containers called disposable? Compare volumes, bind                  4–6        §5.8: writable layer dies; "code in images, data
        mounts and tmpfs                                                                        in volumes"; 3-column table

 8      Scenario: "Django in a container says connection refused to                  4–6        §5.9 localhost trap table + §5.15 playbook (ps
        PostgreSQL" — diagnose                                                                  -a → logs → inspect → exec → network)

 9      List Docker commands for images / containers / volumes / Compose             5–10       §5.17 tables A–G (write purpose + example for
        with examples                                                                           each)

 10     How do you deploy a Docker image? Registries, tagging strategy,              6–10       §5.12 tag → push → pull → run; tag table;
        CI/CD, security best practices                                                          build → test → scan → push → deploy; §5.13
                                                                                                ten habits


Short Q1-style (2–5 M) versions to expect: "What is a Docker image / container / Dockerfile / Docker Hub?", "What is a volume?",
"What does -p 8080:80 mean?", "What is a multi-stage build?" — the definitions in §5.1 and the first paragraph of each section are
sized for these.




      5.19 Last-minute recap
📚 Sources: Unit 5 Notes §11          One-Shot Revision      Complete Revision deck        LEC 6 (Docker)


      Why Docker: Git ships only code; an image ships code + runtime + libraries + OS files + config. "Works on
      my machine" → "works on every machine". Build → Ship → Run.
      Definition: Docker packages an app with everything it needs into a portable image and runs it as an isolat‐
      ed process called a container.
      Containers vs VMs: containers share the host kernel (MB, ~1 s, dozens per laptop, process-level isolation);
      VMs boot a guest OS on a hypervisor (GB, minutes, 2–3, hardware-level isolation). In the cloud: containers
      inside VMs.
      A container is a process: namespaces = what it can see (pid, net, mnt, uts, ipc, user); cgroups = what it
      can use (CPU, memory, PIDs; exit 137 = OOM); layers = what it is made of. OCI makes images run
      anywhere.
      Architecture: client (docker CLI) → REST API → daemon dockerd (→ containerd → runc) → objects (im‐
      ages, containers, volumes, networks)             ⇄ registry (Docker Hub) via pull/push. The client asks, the daemon

--- PDF page 376 ---
works, the registry stores.
    docker run = request → cache lookup → pull → create (layers + writable layer) → network/ports → start as
    PID 1 → detach.
    Images: read-only layers + config + manifest; content-addressed, cached, immutable; only RUN/COPY/ADD
    add size; registry/namespace/repo:tag@digest ; latest is not a version — pin python:3.12-slim (235
    MB vs 1.65 GB).
    Dockerfile: FROM · WORKDIR · COPY · RUN · ENV/ARG · EXPOSE · USER · HEALTHCHECK ·
    CMD/ENTRYPOINT. Dependencies first, code last. .dockerignore . ENTRYPOINT = program, CMD = de‐
    fault args. COPY, not ADD. ARG build-only, ENV runtime, neither for secrets. Multi-stage: AS builder +
     COPY --from=builder .

    Containers: Created → Running      ⇄ Paused → Exited → Removed. Options before the image name.
     -d -it --rm --name -p -e -v --network --restart .

    Storage: code in images, data in volumes. Volume (Docker-managed) · bind mount (your folder) · tmpfs
    (RAM). Postgres data: /var/lib/postgresql/data .
    Networking: -p HOST:CONTAINER = outside:inside; EXPOSE only documents; bind 0.0.0.0; containers find
    each other by name on user-defined networks; laptop → localhost:5432 , container → db:5432 , contain‐
    er → laptop host.docker.internal .
    Compose: one compose.yaml , one docker compose up -d --build ; secrets in .env via ${VAR} ;
    healthcheck + service_healthy ; down keeps volumes, down -v deletes them.
    Django in Docker: gunicorn mysite.wsgi:application --bind 0.0.0.0:8000 ; settings from env; HOST =
     db ; migrate at start-up; collectstatic + WhiteNoise; pin scikit-learn for the .pkl.

    Deploy: tag → push → pull → run; version tags never change; never latest in production; buildx for ar‐
    m64/amd64; CI/CD = build → test → scan → push → deploy.
    Security: no secrets in images ( docker inspect shows ENV); non-root USER; minimal pinned base; .dock‐
    erignore; scan and rebuild; read-only FS; --cap-drop ALL ; limits; never --privileged or a mounted
    docker.sock.
    Limitations: shared-kernel isolation · OS/kernel dependence · Desktop VM overhead · CPU architecture ·
    ephemeral storage · stateful DBs need care · GUI awkward · networking complexity · no orchestration alone ·
    root daemon & supply chain · harder monitoring · disk sprawl.
    Debug order: ps -a → logs → inspect → exec → network check → compose config .

--- PDF page 377 ---
Dockerfile skeleton (memorise)                           compose.yaml skeleton (memorise)


     FROM python:3.12-slim                                    services:
     WORKDIR /app                                               web:
     COPY requirements.txt .                                      build: .
     RUN pip install --no-cache-dir -r require‐                   ports: ["8000:8000"]
     ments.txt                                                    env_file: .env
     COPY . .                                                     environment:
     RUN useradd -m appuser                                           DB_HOST: db
     USER appuser                                                 depends_on:
     EXPOSE 8000                                                      db: { condition: service_healthy }
     # Django: + collectstatic at build, mi‐                    db:
     grate at start (§5.11)                                       image: postgres:16-alpine
     CMD ["gunicorn",                                             environment:
     "mysite.wsgi:application", "--bind",                             POSTGRES_PASSWORD: ${POSTGRES_PASS‐
     "0.0.0.0:8000"]                                          WORD}
                                                                      POSTGRES_DB: ${POSTGRES_DB}
                                                                  volumes:
                                                              ["pgdata:/var/lib/postgresql/data"]
                                                                  healthcheck:
                                                                      test: ["CMD-SHELL", "pg_isready -U
                                                              postgres"]
                                                                      interval: 5s
                                                              volumes:
                                                                pgdata:




 Top 16 commands                                                      One-line meaning

  docker build -t app:1.0 .                                           Build an image from ./Dockerfile

  docker images · docker rmi app:1.0                                  List / delete images

  docker pull postgres:16 · docker push you/app:1.0                   Download / upload

  docker tag app:1.0 you/app:1.0                                      Name it for a registry

  docker run -d --name web -p 8080:80 nginx:alpine                    Create + start, background, named, port-mapped

  docker run --rm -it ubuntu:24.04 bash                               Throw-away interactive shell

  docker ps -a                                                        All containers incl. stopped

  docker logs -f web                                                  Follow output

  docker exec -it web sh                                              Shell inside a running container

  docker inspect web                                                  Full configuration JSON

  docker stop web · docker start web · docker rm web                  Lifecycle

  docker volume create pgdata                                         Persistent storage

  docker network create appnet                                        Network with name DNS

--- PDF page 378 ---
Top 16 commands                              One-line meaning

  docker compose up -d --build                Start the whole stack

  docker compose down · down -v               Stop (keep data) / stop and wipe volumes

  docker system prune                         Clean up unused data