Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Docker Documentation

Package an app with everything it needs into a container that runs the same everywhere.

Docker packages an application with everything it needs — runtime, libraries, system tools, config — into a container that runs the same on your laptop, a teammate's machine and the cloud. No more "it works on my machine". Containers start in seconds and are much lighter than virtual machines because they share the host's kernel.

1. Introduction & Installation

  • Windows / macOS: install Docker Desktop (on Windows it uses WSL 2).
  • Linux: install Docker Engine (curl -fsSL https://get.docker.com | sh), then sudo usermod -aG docker $USER and log out/in.
docker --version
docker run hello-world

Output (last lines):

Hello from Docker!
This message shows that your installation appears to be working correctly.

Key terms:

Term Meaning
Image a read-only template (layers) — like a class
Container a running instance of an image — like an object
Dockerfile the recipe to build an image
Registry a store of images (Docker Hub, GitHub Container Registry, AWS ECR)
Volume persistent storage that outlives containers
Network lets containers talk to each other by name

⚠️ Common error: Cannot connect to the Docker daemon / error during connect — Docker Desktop isn't running (start it), or on Linux your user isn't in the docker group.

2. Running Containers

docker run -d --name web -p 8080:80 nginx:1.27      # detached, host port 8080 → container port 80
docker ps                                           # running containers
docker logs -f web                                  # follow logs (Ctrl + C to stop following)
docker exec -it web sh                              # open a shell inside the container
docker stop web && docker rm web                    # stop and remove

Open http://localhost:8080 and you'll see the nginx welcome page.

docker run --rm alpine:3.20 echo "Hello, Codify!"   # --rm deletes the container when it exits

Output:

Hello, Codify!

Useful flags: -e KEY=value (environment variable), --env-file .env, -v (volume), --network, --restart unless-stopped, -it (interactive terminal), --memory 512m --cpus 1 (limits).

⚠️ Common error: Bind for 0.0.0.0:8080 failed: port is already allocated — another process/container uses that host port. Pick another (-p 8081:80) or stop the other one.

3. Images

docker pull node:22-alpine          # download an image
docker images                       # list local images
docker image inspect node:22-alpine # details (env, entrypoint, layers)
docker rmi node:22-alpine           # remove an image
docker image prune                  # remove dangling images

Image names: registry/namespace/name:tag — e.g. ghcr.io/asha/codify-api:1.2.0. Without a registry it means Docker Hub; without a tag it means :latest (avoid latest in production — pin versions).

Official images to know: node, python, openjdk/eclipse-temurin, nginx, postgres, mysql, mongo, redis, alpine (5 MB base), ubuntu.

4. Writing a Dockerfile

A Dockerfile describes how to build your image, layer by layer:

# Dockerfile for a Node.js API
FROM node:22-alpine

WORKDIR /app

# copy dependency files first so this layer is cached between builds
COPY package*.json ./
RUN npm ci --omit=dev

# then copy the source code
COPY . .

ENV NODE_ENV=production
EXPOSE 5000
USER node

CMD ["node", "src/index.js"]
docker build -t codify-api:1.0 .
docker run -d -p 5000:5000 --env-file .env --name api codify-api:1.0
Instruction Purpose
FROM base image
WORKDIR working directory for the next instructions
COPY / ADD copy files into the image (ADD can also unpack archives/URLs)
RUN run a command at build time (creates a layer)
ENV / ARG environment variables / build-time arguments
EXPOSE documents the port the app listens on
USER run as a non-root user
CMD / ENTRYPOINT what runs when the container starts
HEALTHCHECK command Docker uses to check the app is healthy

Add a .dockerignore so junk and secrets never enter the image:

node_modules
.git
.env
dist
*.log

⚠️ Common error: COPY . . before npm install — every code change invalidates the cache and reinstalls all packages. Copy package*.json and install first.

5. Layers & Caching

Each RUN, COPY and ADD creates a cached layer. When a layer changes, every layer after it is rebuilt. So order instructions from least to most frequently changing.

docker history codify-api:1.0        # see layers and their sizes
docker build --no-cache -t app .     # force a full rebuild

Tips for small, fast images:

  • Use slim bases (-alpine, -slim, or distroless).
  • Combine related commands and clean up in the same layer: RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*.
  • Use multi-stage builds (section 10) so build tools don't end up in the final image.

6. Volumes & Persistent Data

Containers are disposable — anything written inside is lost when the container is removed. Use volumes for data that must survive:

docker volume create pgdata
docker run -d --name db \
  -e POSTGRES_PASSWORD=secret \
  -v pgdata:/var/lib/postgresql/data \
  -p 5432:5432 postgres:16
docker volume ls

Bind mounts map a host folder into the container — perfect for development (live code reload):

docker run --rm -it -v "$(pwd)":/app -w /app -p 5173:5173 node:22-alpine sh -c "npm install && npm run dev -- --host"

⚠️ Common error: docker rm -v or docker volume prune deletes volume data permanently. Back up databases first (docker exec db pg_dump ...).

7. Networking

Containers on the same user-defined network reach each other by container name:

docker network create appnet
docker run -d --name mongo --network appnet mongo:7
docker run -d --name api --network appnet -p 5000:5000 \
  -e MONGO_URI=mongodb://mongo:27017/codify codify-api:1.0

Inside api, the hostname mongo resolves to the database container. localhost inside a container means the container itself, not your computer — use host.docker.internal (Docker Desktop) to reach services on the host.

8. Docker Compose

Compose defines a multi-container app in one YAML file — the usual way to run a full stack locally:

# compose.yaml — MERN API + MongoDB + Redis
services:
  api:
    build: ./server
    ports:
      - "5000:5000"
    env_file: ./server/.env
    environment:
      MONGO_URI: mongodb://mongo:27017/codify
      REDIS_URL: redis://redis:6379
    depends_on:
      - mongo
      - redis
    restart: unless-stopped

  mongo:
    image: mongo:7
    volumes:
      - mongo-data:/data/db

  redis:
    image: redis:7-alpine

volumes:
  mongo-data:
docker compose up -d --build     # build and start everything
docker compose ps
docker compose logs -f api
docker compose exec api sh
docker compose down              # stop and remove containers (add -v to delete volumes)

⚠️ Common error: depends_on only waits for the container to start, not for the database to be ready. Add retries in your app, or a healthcheck with depends_on: condition: service_healthy.

9. Registries & Deployment

docker login                                   # Docker Hub (or: docker login ghcr.io)
docker tag codify-api:1.0 asha/codify-api:1.0
docker push asha/codify-api:1.0
docker pull asha/codify-api:1.0                # on the server

Where containers run in production: Render, Railway and Fly.io (deploy straight from a Dockerfile), AWS ECS/Fargate, Google Cloud Run, Azure Container Apps, and Kubernetes for large systems. CI pipelines (GitHub Actions) usually build, test and push the image on every merge.

Security basics: don't run as root (USER), never bake secrets into images (use env vars/secret managers), pin image versions, scan images (docker scout cves myimage), and keep base images updated.

10. Advanced Concepts

Multi-stage builds — build with full tooling, ship only the result:

# Stage 1: build the React front-end
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: serve the static files with nginx (final image ~25 MB)
FROM nginx:1.27-alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Health checks:

HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget -qO- http://localhost:5000/api/health || exit 1

Other topics

  • ENTRYPOINT vs CMD: ENTRYPOINT is the fixed executable; CMD provides default arguments that docker run can override.
  • Build arguments: ARG NODE_VERSION=22 then FROM node:${NODE_VERSION}-alpine.
  • BuildKit features: RUN --mount=type=cache,target=/root/.npm npm ci speeds up rebuilds.
  • Multi-platform images: docker buildx build --platform linux/amd64,linux/arm64.
  • Resource usage: docker stats; cleanup everything unused: docker system prune -a (careful!).
  • Containers vs VMs: containers share the host kernel (isolated with namespaces and cgroups); VMs run a full guest OS on a hypervisor.

11. Examples with Output

Example 1 — Run Python without installing it

docker run --rm python:3.12-alpine python -c "print(sum(range(1, 101)))"
5050

Example 2 — Pass an environment variable

docker run --rm -e GREETING="Namaste" alpine:3.20 sh -c 'echo "$GREETING from a container"'
Namaste from a container

Example 3 — Check which OS a container sees

docker run --rm alpine:3.20 cat /etc/os-release | head -1
NAME="Alpine Linux"

12. Practice Problems

  1. Run nginx on port 8080 and replace its welcome page with your own index.html using a bind mount.
  2. Write a Dockerfile for a Node.js/Express API; make the image smaller with an alpine base and .dockerignore.
  3. Run PostgreSQL with a named volume; delete and recreate the container and confirm the data survived.
  4. Create a user-defined network and connect an API container to a MongoDB container by name.
  5. Write a compose.yaml for your MERN app (React build served by nginx, API, MongoDB).
  6. Convert a front-end Dockerfile to a multi-stage build and compare image sizes with docker images.
  7. Add a HEALTHCHECK to your API image and watch docker ps show healthy.
  8. Push your image to Docker Hub or GHCR and deploy it on Render from the image.

13. Interview Questions

1. Container vs virtual machine? Containers share the host OS kernel and isolate processes (lightweight, start in seconds); VMs virtualise hardware and run a full guest OS (heavier, stronger isolation).

2. Image vs container? An image is a read-only template made of layers; a container is a running (or stopped) instance of an image with its own writable layer.

3. CMD vs ENTRYPOINT? ENTRYPOINT sets the executable that always runs; CMD sets default arguments (or the default command) that docker run can override.

4. COPY vs ADD? Both copy files; ADD can also download URLs and auto-extract tar archives. Prefer COPY for clarity.

5. How does layer caching work? Each instruction creates a layer that's reused if the instruction and its inputs are unchanged; a change invalidates that layer and all following ones.

6. Volumes vs bind mounts? Volumes are managed by Docker (best for persistent data); bind mounts map a specific host path (best for development).

7. What is Docker Compose? A tool to define and run multi-container applications from a YAML file with one command.

8. What is a multi-stage build? Using several FROM stages in one Dockerfile so the final image contains only the runtime artefacts, not build tools — smaller and safer.

9. How do containers communicate? Through Docker networks — on a user-defined bridge network they resolve each other by container/service name.

10. How do you keep images secure? Use minimal, pinned base images, run as non-root, don't store secrets in images, scan for vulnerabilities, and rebuild regularly with updates.

14. Cheat Sheet & References

Containers

# run and manage containers
docker run -d --name app -p 8080:80 nginx
docker run --rm -it ubuntu bash
docker ps -a
docker logs -f app
docker exec -it app sh
docker stop app && docker rm app
docker stats

Images

docker build -t myapp:1.0 .
docker images
docker pull node:22-alpine
docker tag myapp:1.0 user/myapp:1.0
docker push user/myapp:1.0
docker rmi myapp:1.0
docker history myapp:1.0

Dockerfile

# typical instructions
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 5000
USER node
CMD ["node", "server.js"]

Volumes and networks

docker volume create data
docker run -v data:/var/lib/data image
docker run -v "$(pwd)":/app image
docker network create net
docker run --network net --name db postgres:16

Compose and cleanup

docker compose up -d --build
docker compose logs -f
docker compose down
docker system df
docker system prune

Official documentation