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), thensudo usermod -aG docker $USERand 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 thedockergroup.
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 . .beforenpm install— every code change invalidates the cache and reinstalls all packages. Copypackage*.jsonand 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 -vordocker volume prunedeletes 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_ononly waits for the container to start, not for the database to be ready. Add retries in your app, or ahealthcheckwithdepends_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
ENTRYPOINTvsCMD:ENTRYPOINTis the fixed executable;CMDprovides default arguments thatdocker runcan override.- Build arguments:
ARG NODE_VERSION=22thenFROM node:${NODE_VERSION}-alpine. - BuildKit features:
RUN --mount=type=cache,target=/root/.npm npm cispeeds 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
- Run nginx on port 8080 and replace its welcome page with your own
index.htmlusing a bind mount. - Write a Dockerfile for a Node.js/Express API; make the image smaller with an alpine base and
.dockerignore. - Run PostgreSQL with a named volume; delete and recreate the container and confirm the data survived.
- Create a user-defined network and connect an API container to a MongoDB container by name.
- Write a
compose.yamlfor your MERN app (React build served by nginx, API, MongoDB). - Convert a front-end Dockerfile to a multi-stage build and compare image sizes with
docker images. - Add a
HEALTHCHECKto your API image and watchdocker psshowhealthy. - 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