Docker - Cheat Sheet

development docker containers cheatsheet


What Are Containers?

A container is a lightweight, isolated environment that packages an application with everything it needs to run — code, runtime, libraries, and system tools. Unlike virtual machines, containers share the host OS kernel, making them fast to start and efficient with resources.

Key concepts:

  • Image — A read-only template (blueprint) for creating containers. Built from a Dockerfile.
  • Container — A running instance of an image. You can run many containers from the same image.
  • Registry — Where images are stored and shared (Docker Hub, GitHub Container Registry, etc.)

Containers vs VMs

ContainersVirtual Machines
IsolationProcess-level (shared kernel)Full OS (own kernel)
StartupSecondsMinutes
SizeMBsGBs
PerformanceNear-nativeHypervisor overhead
Use caseApp packaging & deploymentFull OS isolation, different OS kernels

Installation

Linux (Ubuntu/Debian)

# Add Docker's official GPG key and repo
sudo apt update
sudo apt install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
 
# Add the repository
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
 
# Install
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-compose-plugin
 
# Run without sudo
sudo usermod -aG docker $USER
newgrp docker

WSL2

Install Docker Desktop for Windows and enable WSL2 integration in Settings > Resources > WSL Integration. Docker commands then work directly in your WSL terminal.


Core Commands

Images

CommandDescription
docker pull <image>Download image from registry
docker pull <image>:<tag>Download specific version (e.g., python:3.12-slim)
docker imagesList local images
docker build -t <name> .Build image from Dockerfile in current dir
docker build -t <name>:<tag> .Build with specific tag
docker rmi <image>Remove an image
docker tag <image> <new_name>:<tag>Tag an image (for pushing to registry)
docker push <image>:<tag>Push image to registry
docker image pruneRemove unused images

Containers

CommandDescription
docker run <image>Create and start a container
docker run -d <image>Run in detached (background) mode
docker run -it <image> bashRun interactive with terminal
docker run --name myapp <image>Run with a custom name
docker run -p 8080:80 <image>Map host port 8080 to container port 80
docker run -v /host/path:/container/path <image>Bind mount a directory
docker run --rm <image>Auto-remove container when it exits
docker run -e VAR=value <image>Set environment variable
docker psList running containers
docker ps -aList all containers (including stopped)
docker stop <container>Stop a running container
docker start <container>Start a stopped container
docker restart <container>Restart a container
docker rm <container>Remove a stopped container
docker exec -it <container> bashOpen shell in running container
docker exec <container> <command>Run a command in running container
docker logs <container>View container logs
docker logs -f <container>Follow logs (tail -f style)
docker inspect <container>Detailed container info (JSON)
docker cp <container>:/path /host/pathCopy file from container to host

Volumes

CommandDescription
docker volume create <name>Create a named volume
docker volume lsList volumes
docker volume inspect <name>Volume details
docker volume rm <name>Remove a volume
docker volume pruneRemove unused volumes
docker run -v mydata:/app/data <image>Mount named volume

Networks

CommandDescription
docker network create <name>Create a network
docker network lsList networks
docker network inspect <name>Network details
docker network connect <net> <container>Connect container to network
docker run --network <name> <image>Run container on specific network

Dockerfile Reference

A Dockerfile is a text file with instructions to build an image, executed top to bottom.

Common Instructions

InstructionPurposeExample
FROMBase image (required, must be first)FROM python:3.12-slim
WORKDIRSet working directoryWORKDIR /app
COPYCopy files from host to imageCOPY . .
ADDLike COPY but handles URLs and tar extractionADD archive.tar.gz /app
RUNExecute command during buildRUN pip install -r requirements.txt
ENVSet environment variableENV APP_ENV=production
EXPOSEDocument which port the app usesEXPOSE 8000
CMDDefault command when container startsCMD ["python", "app.py"]
ENTRYPOINTFixed command (CMD becomes arguments)ENTRYPOINT ["python"]
ARGBuild-time variableARG VERSION=latest

CMD vs ENTRYPOINT

  • CMD — Default command, can be overridden at docker run
  • ENTRYPOINT — Fixed command, docker run args are appended to it
  • Use together: ENTRYPOINT ["python"] + CMD ["app.py"] → user can override the script but not the runtime

Example Dockerfile

FROM python:3.12-slim
 
WORKDIR /app
 
# Install dependencies first (layer caching)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
 
# Copy application code
COPY . .
 
EXPOSE 8000
 
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Layer caching tip: Copy and install dependencies before copying source code. Dependencies change less often, so Docker can reuse the cached layer and skip reinstalling on every code change.


Docker Compose

Compose lets you define and run multi-container applications with a single YAML file. Instead of long docker run commands, you describe your entire stack declaratively.

Example docker-compose.yml

services:
  web:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - .:/app
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/mydb
    depends_on:
      - db
 
  db:
    image: postgres:16
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=mydb
 
volumes:
  pgdata:

Compose Commands

CommandDescription
docker compose upStart all services
docker compose up -dStart in background
docker compose up --buildRebuild images then start
docker compose downStop and remove containers
docker compose down -vStop and remove containers + volumes
docker compose logsView logs from all services
docker compose logs -f <service>Follow logs for one service
docker compose psList running services
docker compose exec <service> bashShell into a running service
docker compose buildBuild/rebuild images
docker compose pullPull latest images

Common Patterns

Multi-Stage Build

Keeps final image small by separating build and runtime stages:

# Stage 1: Build
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
 
# Stage 2: Production
FROM node:20-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/index.js"]

.dockerignore

Prevents unnecessary files from being sent to the build context:

node_modules
.git
.env
__pycache__
*.pyc
.vscode

Bind Mounts vs Volumes

Bind MountNamed Volume
Syntax-v /host/path:/container/path-v myvolume:/container/path
Managed byYou (host filesystem)Docker
Use caseDevelopment (live code reload)Persistent data (databases)
PortabilityTied to host pathsPortable across hosts

Environment Variables

# Inline
docker run -e API_KEY=abc123 myapp
 
# From file
docker run --env-file .env myapp
 
# In docker-compose.yml
environment:
  - API_KEY=abc123
# or
env_file:
  - .env

Useful One-Liners

# Remove all stopped containers
docker container prune
 
# Remove all unused images, containers, networks
docker system prune
 
# Nuclear option: remove everything including volumes
docker system prune -a --volumes
 
# Show disk usage
docker system df
 
# Get container IP address
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container>
 
# Export container filesystem as tar
docker export <container> > backup.tar
 
# Run a quick throwaway container
docker run --rm -it ubuntu bash
 
# Quick Python environment
docker run --rm -it -v $(pwd):/app -w /app python:3.12 python script.py