Docker
Cheatsheet
A quick reference guide for containerisation using Docker — covering containers, images, Dockerfile, volumes, networks, and Docker Compose for DevOps workflows.
What is Docker?
Docker is an open-source platform for building, shipping, and running applications inside containers — lightweight, isolated environments that package an application and all its dependencies together. Created by Docker Inc. in 2013, it has become the industry standard for containerisation.
Containers vs Virtual Machines: VMs virtualise entire hardware stacks including the OS kernel — they are heavy (GBs) and slow to start. Containers share the host OS kernel and only package the application and its libraries — they are lightweight (MBs) and start in milliseconds.
Why use Docker? Eliminates "works on my machine" problems, enables consistent environments from development to production, simplifies microservices deployments, and is the foundation for orchestration platforms like Kubernetes. Essential for modern DevOps, CI/CD pipelines, and cloud deployments.
Docker Container
- Shares host OS kernel
- Starts in milliseconds
- Lightweight (MBs)
- Process isolation
- Portable across any OS
Virtual Machine
- Own full OS kernel
- Starts in minutes
- Heavyweight (GBs)
- Full hardware emulation
- Stronger isolation
1. Basic Commands
Verify installation and explore the Docker environment.
# Check Docker installation docker --version # Docker version docker version # full client + server info docker info # system-wide information # List running containers docker ps # running containers docker ps -a # all containers (including stopped) docker ps -q # only container IDs # List images docker images # all local images docker images -q # only image IDs # System cleanup docker system df # disk usage docker system prune # remove unused resources docker system prune -a # remove ALL unused resources
2. Running Containers
# Basic run docker run nginx # run nginx (foreground) docker run -d nginx # run detached (background) docker run -it ubuntu bash # interactive with TTY docker run --rm ubuntu echo "Hello" # auto-remove on exit # Port mapping -p host:container docker run -d -p 80:80 nginx # map host:80 → container:80 docker run -d -p 8080:80 nginx # map host:8080 → container:80 docker run -d -p 443:443 -p 80:80 nginx # multiple ports # Name containers docker run -d --name webserver nginx # named container # Environment variables docker run -e MYSQL_ROOT_PASSWORD=secret mysql docker run --env-file .env myapp # from file # Volume mount -v host:container docker run -d -v /host/data:/container/data nginx docker run -d -v $(pwd):/app myapp # mount current dir # Resource limits docker run -d --memory="512m" --cpus="1.5" nginx # Network docker run -d --network mynetwork nginx
3. Managing Containers
| Command | Description |
|---|---|
| docker stop <id> | Gracefully stop a running container (SIGTERM → SIGKILL after 10s) |
| docker kill <id> | Force stop immediately (SIGKILL) |
| docker start <id> | Start a stopped container |
| docker restart <id> | Stop then start a container |
| docker pause <id> | Freeze a container (suspend processes) |
| docker unpause <id> | Unfreeze a paused container |
| docker rm <id> | Remove a stopped container |
| docker rm -f <id> | Force remove a running container |
| docker rm $(docker ps -aq) | Remove ALL stopped containers |
| docker rename old new | Rename a container |
| docker inspect <id> | Detailed container metadata (JSON) |
| docker stats | Live CPU/memory/network/disk usage |
| docker logs <id> | View container stdout/stderr logs |
| docker logs -f <id> | Follow container logs live |
| docker exec -it <id> bash | Open interactive shell in running container |
| docker cp <id>:/path ./host | Copy files between container and host |
4. Images
# Pull images from Docker Hub docker pull ubuntu # latest tag docker pull ubuntu:22.04 # specific version docker pull nginx:alpine # alpine (minimal) variant # Build image from Dockerfile docker build -t myapp . # build with tag from current dir docker build -t myapp:1.0 . # specific version tag docker build -t myapp -f Dockerfile.prod . # custom Dockerfile docker build --no-cache -t myapp . # ignore build cache # Tag and push to registry docker tag myapp username/myapp:latest docker push username/myapp:latest # push to Docker Hub # Inspect and manage images docker inspect myapp # image details docker history myapp # layer history docker rmi myapp # remove image docker rmi $(docker images -q) # remove ALL images docker image prune # remove dangling images # Search Docker Hub docker search nginx # search Hub for images # Save/load image as tar docker save myapp > myapp.tar docker load < myapp.tar
5. Dockerfile
A Dockerfile is a text file containing instructions to build a Docker image. Each instruction creates a new layer in the image.
# ── Dockerfile instructions reference ── FROM python:3.11-slim # base image (always first) LABEL maintainer="[email protected]" # metadata WORKDIR /app # set working directory COPY requirements.txt . # copy specific file COPY . . # copy everything ADD https://example.com/file /app/ # ADD also supports URLs + tar RUN pip install -r requirements.txt # run during build RUN apt-get update && apt-get install -y curl \ && rm -rf /var/lib/apt/lists/* # chain to reduce layers ENV APP_ENV=production # set environment variable ENV PORT=8000 EXPOSE 8000 # document the port (informational) VOLUME ["/data"] # declare mount point USER appuser # run as non-root user ENTRYPOINT ["python"] # fixed executable CMD ["app.py"] # default args (overridable) # Healthcheck HEALTHCHECK --interval=30s --timeout=3s \ CMD curl -f http://localhost:8000/health || exit 1
# ── Multi-stage build (reduce final image size) ──
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
# ── .dockerignore — exclude from build context ──
node_modules
.git
.env
*.log
__pycache__
.DS_Store
6. Volumes & Networks
# ── Volumes (persistent storage) ── docker volume create myvol # create named volume docker volume ls # list volumes docker volume inspect myvol # volume details docker volume rm myvol # remove volume docker volume prune # remove unused volumes # Use volumes with containers docker run -d -v myvol:/data nginx # named volume docker run -d -v $(pwd):/app myapp # bind mount (host path) docker run -d --mount type=tmpfs,target=/tmp nginx # tmpfs (in-memory) # ── Networks ── docker network ls # list networks docker network create mynetwork # create bridge network docker network create --driver overlay mynet # overlay (Swarm) docker network inspect mynetwork # network details docker network rm mynetwork # remove network docker network prune # remove unused networks # Connect containers to networks docker network connect mynetwork container1 docker network disconnect mynetwork container1 docker run -d --network mynetwork --name api myapp
7. Docker Compose
Docker Compose defines and runs multi-container applications using a docker-compose.yml file.
# docker-compose.yml — full example
version: '3.9'
services:
web:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:pass@db:5432/mydb
volumes:
- .:/app
depends_on:
- db
restart: unless-stopped
db:
image: postgres:15-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- web
volumes:
pgdata:
# Docker Compose CLI commands docker compose up # start all services docker compose up -d # detached mode docker compose up --build # rebuild images first docker compose down # stop and remove containers docker compose down -v # also remove volumes docker compose stop # stop without removing docker compose restart # restart all services docker compose ps # list compose containers docker compose logs -f # follow all logs docker compose logs -f web # follow specific service docker compose exec web bash # shell in service docker compose build # build/rebuild services docker compose pull # pull latest images docker compose config # validate compose file
8. Registry & Docker Hub
# Docker Hub login docker login # login to Docker Hub docker login registry.example.com # private registry docker logout # Tag and push to Docker Hub docker build -t myapp . docker tag myapp username/myapp:latest docker tag myapp username/myapp:1.0.0 docker push username/myapp:latest # Pull from Docker Hub docker pull username/myapp:latest # Push to GitHub Container Registry (GHCR) docker tag myapp ghcr.io/username/myapp:latest docker push ghcr.io/username/myapp:latest # Run local registry docker run -d -p 5000:5000 --name registry registry:2 docker tag myapp localhost:5000/myapp docker push localhost:5000/myapp