Docker & Containers

What containers are (namespaces, cgroups, layered images), images vs containers, writing good Dockerfiles with multi-stage builds and layer caching, volumes and networking, Docker Compose, registries, and container security.

Intermediate 4 min readLesson 3 of 9 Interview Q&A

A container packages an application with everything it needs — runtime, libraries, config — into a standard unit that runs the same on a laptop, a CI runner and production. "Works on my machine" becomes "ships as my machine".

Containers vs virtual machines

Virtual machines
  • Each VM runs a full guest OS kernel on a hypervisor.
  • Strong isolation (hardware virtualisation).
  • Boot in tens of seconds; GBs of disk.
  • Run any OS (Windows guest on a Linux host).
Containers
  • Containers share the host kernel; each is an isolated process tree.
  • Isolation via kernel features — weaker than VMs.
  • Start in milliseconds; MBs of disk.
  • Linux containers need a Linux kernel (Docker Desktop runs a small VM on macOS/Windows).

Under the hood a container is an ordinary process with (Virtualization and containers):

  • Namespaces — what it can see: its own PIDs, network interfaces, mount points, hostname, users.
  • cgroups — what it can use: CPU, memory, I/O limits.
  • A layered filesystem (OverlayFS) built from the image, plus seccomp/capabilities restrictions.

Images and containers

  • An image is a read-only template: a stack of filesystem layers plus metadata (entrypoint, env, ports). Images follow the OCI standard, so Docker, Podman, containerd and Kubernetes all use them.
  • A container is a running instance of an image with a thin writable layer on top. Delete the container and that layer is gone — store data in volumes.
Shell
docker run -d --name web -p 8080:80 nginx:1.27     # run detached, map host 8080 → container 80
docker ps                                          # running containers
docker logs -f web                                 # follow logs
docker exec -it web sh                             # shell inside the container
docker stop web && docker rm web
docker images                                      # local images
docker pull postgres:17   docker push registry.example.com/app:1.4.2

Writing a Dockerfile

Dockerfile
# syntax=docker/dockerfile:1
FROM node:22-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./      # copy manifests first…
RUN npm ci                                   # …so this layer is cached until dependencies change

FROM node:22-slim AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build && npm prune --omit=dev

FROM gcr.io/distroless/nodejs22-debian12 AS runtime   # minimal final image
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
USER nonroot
EXPOSE 3000
CMD ["dist/server.js"]

Layer caching

Each instruction creates a layer; Docker reuses cached layers until an instruction or its inputs change — and then rebuilds everything after it. So order instructions from least to most frequently changing: base image → system packages → dependency manifests → install → source code.

Multi-stage builds

Build tools (compilers, dev dependencies) stay in earlier stages; only the artefacts are copied to the final image. A Go or Rust service can ship as a single static binary in a scratch or distroless image of a few MB:

Dockerfile
FROM golang:1.23 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/api ./cmd/api

FROM gcr.io/distroless/static
COPY --from=build /out/api /api
USER nonroot
ENTRYPOINT ["/api"]

Dockerfile best practices

PracticeWhy
Small base images (-slim, alpine, distroless)Fewer vulnerabilities, faster pulls
Pin versions (node:22.11-slim, or a digest)Reproducible builds
.dockerignore (node_modules, .git, .env)Smaller build context; no leaked secrets
Run as a non-root USERLimits damage from a compromise
One process per container; log to stdout/stderrOrchestrators manage lifecycle and logs
Exec-form CMD ["node", "server.js"]The app receives SIGTERM directly (PID 1) for graceful shutdown
Combine apt-get update && apt-get install … && rm -rf /var/lib/apt/lists/*Smaller layers
Never bake secrets into imagesLayers are readable by anyone with the image; use build secrets (--mount=type=secret) and runtime env/secret stores

CMD sets the default command (overridable); ENTRYPOINT sets the fixed executable. ARG is build-time; ENV persists into the container.

Data: volumes and bind mounts

Shell
docker volume create pgdata
docker run -d -v pgdata:/var/lib/postgresql/data postgres:17   # named volume: managed by Docker, persists
docker run -v "$PWD":/app -w /app node:22 npm test             # bind mount: host directory (dev workflows)
docker run --tmpfs /tmp myapp                                  # in-memory

Networking

  • Containers on the same user-defined bridge network reach each other by container name (built-in DNS).
  • -p host:container publishes a port on the host.
  • --network host shares the host's network stack (Linux only).

Docker Compose

Define a multi-container development environment in one file:

YAML
# compose.yaml
services:
  api:
    build: .
    ports: ["3000:3000"]
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app
      REDIS_URL: redis://cache:6379
    depends_on:
      db: { condition: service_healthy }
  db:
    image: postgres:17
    environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: secret, POSTGRES_DB: app }
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
  cache:
    image: redis:7
volumes:
  pgdata:
Shell
docker compose up -d --build     # start everything
docker compose logs -f api
docker compose down -v           # stop and remove (‑v also removes volumes)

Compose is ideal for local development and simple single-host deployments; production clusters use an orchestrator like Kubernetes.

Registries and tags

Images are stored in registries: Docker Hub, GitHub Container Registry, AWS ECR, Google Artifact Registry. Tag images immutably (git SHA or semantic version: app:1.4.2, app:sha-3f9c2a1) — latest is mutable and makes deployments ambiguous. Deploy by digest (app@sha256:…) for exact reproducibility.

Container security

  • Scan images for known CVEs (Trivy, Grype, Docker Scout) in CI; rebuild regularly for base-image patches.
  • Non-root user, read-only root filesystem, drop Linux capabilities, no --privileged.
  • Never mount the Docker socket into containers (it's root on the host).
  • Sign images and verify provenance (Sigstore/cosign, SBOMs) — supply-chain security.
  • Remember containers share the kernel: for untrusted multi-tenant workloads, use sandboxed runtimes (gVisor, Kata Containers, Firecracker microVMs).
Key takeaways
  • Containers are isolated processes (namespaces + cgroups) sharing the host kernel; lighter than VMs, with weaker isolation.
  • Images are layered, read-only OCI templates; containers add a writable layer.
  • Order Dockerfile instructions for layer caching; use multi-stage builds and small base images.
  • Run as non-root, use exec-form CMD, keep secrets out of images, add a .dockerignore.
  • Volumes persist data; user-defined networks give DNS by container name; Compose runs multi-container dev setups.
  • Tag immutably, scan images, and sign them.
Interview questions
QWhat is the difference between a container and a virtual machine?easy

A VM virtualises hardware: a hypervisor runs full guest operating systems, each with its own kernel, giving strong isolation at the cost of size and boot time. A container virtualises the operating system: it's a process (or group) on the host kernel, isolated with namespaces and limited with cgroups, using a layered image filesystem. Containers start in milliseconds and are much smaller, but share the kernel, so their isolation is weaker.

QHow do you make Docker builds faster and images smaller?medium

Order instructions so rarely changing layers come first — copy dependency manifests and install dependencies before copying source code — to maximise cache hits. Use a .dockerignore to shrink the build context. Use multi-stage builds so compilers and dev dependencies never reach the final image, and use slim, alpine, distroless or scratch base images. Clean package caches in the same RUN instruction, and use BuildKit cache mounts for package managers.