Docker Pocket Book

Docker Pocket Book

Docker Pocket Book — Uplatz

50 deep-dive flashcards • Wide layout • Fewer scrolls • 20+ Interview Q&A • Readable code examples

Section 1 — Fundamentals

1) What is Docker?

Docker is a platform for building, shipping, and running applications in containers. Containers package code, runtime, libraries, and dependencies, ensuring consistent execution across environments. Docker uses OS-level virtualization with isolated processes. Sweet spots: microservices, CI/CD pipelines, reproducible dev setups. Less ideal: persistent-heavy monoliths without orchestration.

# Verify docker version
docker -v
docker info

2) Why Docker? Core Strengths & Tradeoffs

Strengths: portability, reproducibility, faster deployments, isolation, and lightweight vs VMs. Tradeoffs: added complexity, security surface, storage management, networking challenges. Mitigate with orchestration, minimal images, and regular audits.

# Run hello-world
docker run hello-world

3) Docker Architecture

Docker follows client–server architecture. Client CLI → Docker Daemon (dockerd) → Containers & Images. Registry (Docker Hub/Private) stores and distributes images. Daemon exposes REST API for management.

# Check daemon info
systemctl status docker

4) Images vs Containers

Images are read-only blueprints, containers are runtime instances. A container = image + writable layer. Images are layered, built from Dockerfiles. Commit containers for quick snapshots but prefer reproducible builds.

docker images
docker ps -a

5) Docker vs VM

VMs virtualize hardware; containers virtualize OS. Containers are faster and lighter, sharing the host kernel. VMs provide stronger isolation. Use containers for apps/services; VMs for full OS isolation or legacy workloads.

# Run Ubuntu container
docker run -it ubuntu bash

6) Docker CLI Basics

Key commands: docker run, docker ps, docker stop, docker rm, docker logs, docker exec. Add -it for interactive mode; -d for detached.

docker run -d --name web nginx:latest
docker logs web

7) Dockerfile Basics

Dockerfile is declarative: FROM base, RUN commands, COPY files, EXPOSE ports, CMD entrypoint. Layer cache optimizes builds. Keep images small and pinned.

# Dockerfile
FROM python:3.12-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python","app.py"]

8) Docker Hub & Registries

Public registry is Docker Hub. Private registries (Harbor, AWS ECR, GCR) secure enterprise artifacts. Always tag images semantically and avoid :latest in production.

docker login
docker push myrepo/app:1.0.0

9) Volumes

Volumes persist data beyond container lifecycle. Types: anonymous, named, bind mounts. Recommended for DBs and config. Avoid storing important data in container writable layer.

docker volume create app-data
docker run -v app-data:/var/lib/mysql mysql

10) Q&A — “Is Docker replacing VMs?”

Answer: Not entirely. Containers complement VMs. Use containers for app packaging and portability; VMs for OS-level isolation or when running multiple OS types. Many enterprises run Docker inside VMs.

Section 2 — Networking & Services

11) Networking Modes

Docker supports bridge (default), host, none, and custom networks. Bridge provides NAT, host shares host stack, none disables networking. Use custom bridge networks for multi-container apps.

docker network ls
docker network create mynet

12) Port Mapping

Expose container ports via -p host:container. Ensure firewall rules allow access. Avoid mapping sensitive services directly to internet.

docker run -p 8080:80 nginx

13) Docker Compose

Compose orchestrates multi-container apps via YAML. Supports build, networks, volumes, dependencies. Use docker compose up for dev/test. For prod, prefer Swarm or Kubernetes.

# docker-compose.yml
version: "3"
services:
  web: { image: nginx, ports: ["8080:80"] }
  db: { image: postgres, volumes: ["dbdata:/var/lib/postgresql/data"] }

14) Service Discovery

Containers in same custom network resolve each other by service name. DNS-based resolution is automatic. For cross-host networking, use orchestration or overlay networks.

docker run --network=mynet --name=web nginx

15) Environment Variables

Pass envs at runtime with -e or --env-file. Best for secrets/config, but use managers (Vault, AWS SM) for prod.

docker run -e DB_HOST=db -e DB_PASS=secret myapp

16) Health Checks

Define in Dockerfile with HEALTHCHECK or at run time. Mark containers healthy/unhealthy for orchestration decisions.

HEALTHCHECK CMD curl --fail http://localhost:8000/health || exit 1

17) Logs

Docker captures stdout/stderr, logs per container. Drivers: json-file, syslog, fluentd, gelf, awslogs, etc. Centralize logs for production observability.

docker logs -f myapp

18) Exec into Containers

Use docker exec to run commands inside running containers. Combine with -it for interactive shells.

docker exec -it myapp bash

19) Inspect & Stats

docker inspect gives JSON details; docker stats shows live CPU/mem/net usage. Use for debugging and performance checks.

docker inspect myapp
docker stats

20) Q&A — “Why use Compose vs plain Docker?”

Answer: Compose manages multi-container dependencies, networks, and volumes declaratively. Easier for dev/test. For prod scale, orchestration systems handle scheduling and resilience.

Section 3 — Advanced Usage

21) Multi-Stage Builds

Multi-stage Dockerfiles reduce image size by compiling in one stage and copying results to a minimal runtime stage. Improves security and performance.

FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN go build -o app
FROM alpine
COPY --from=build /src/app /app
CMD ["/app"]

22) Resource Limits

Limit CPU/mem per container using --cpus and -m. Prevent noisy neighbors and runaway containers.

docker run -m 512m --cpus=1 myapp

23) Overlay Networks

Enable multi-host networking across Swarm/K8s. Containers communicate seamlessly across nodes. Requires key-value store (Swarm handles automatically).

docker network create -d overlay mynet

24) Secrets Management

Docker Swarm supports secrets natively. K8s has secrets too. Avoid baking secrets into images. Mount secrets at runtime instead.

echo "mypassword" | docker secret create db_pass -

25) Docker Swarm

Swarm is Docker’s native orchestration: clustering, scaling, service discovery, load balancing. Simpler than Kubernetes but less feature-rich.

docker swarm init
docker service create --replicas 3 nginx

26) Docker with Kubernetes

Kubernetes dominates orchestration. Docker images are OCI compliant and run on K8s. Use manifests, Helm charts, or operators for deployments.

kubectl run web --image=nginx

27) CI/CD Integration

Docker integrates into pipelines for builds, tests, deployments. Cache layers smartly, scan images for vulnerabilities, push to registries automatically.

# GitHub Action example
uses: docker/build-push-action@v4

28) Security Best Practices

Use minimal base images, drop root with USER, keep host patched, sign images, and scan with Trivy/Clair. Avoid exposing Docker socket.

# Example user in Dockerfile
RUN adduser -D app
USER app