Docker logoDockerv29INTERMEDIATE

Docker

Docker cheat sheet with essential commands for containers, images, volumes, networks, Docker Compose, and orchestration examples.

10 min read
dockercontainersdevopsdeploymentvirtualization

Sign in to mark items as known and track your progress.

Sign in

Container Management

Running Containers

Start and run Docker containers with various options

bash
# Run container
docker run nginx
docker run -d nginx                     # Detached mode
docker run -it ubuntu bash              # Interactive
docker run --name web nginx             # Named container

# Port mapping
docker run -p 8080:80 nginx            # Host:Container
docker run -P nginx                     # Random ports

# Volume mounting
docker run -v /host:/container nginx   # Bind mount
docker run -v myvolume:/data nginx     # Named volume

# Environment
docker run -e NODE_ENV=prod node       # Single var
docker run --env-file .env node        # From file
💡 Use -d for background containers
⚠️ Always name containers for easier management
📌 Use --rm for temporary containers
✅ Set resource limits in production

Container State Management

Control container lifecycle - start, stop, restart, and remove

bash
# List containers
docker ps                    # Running only
docker ps -a                 # All containers
docker ps -q                 # Only IDs

# Start/Stop/Restart
docker start container_name
docker stop container_name
docker restart container_name

# Remove containers
docker rm container_name
docker rm -f container_name  # Force remove

# Clean up
docker container prune       # Remove stopped
💡 docker ps -a shows stopped containers too
⚠️ Use -f flag carefully to force remove
📌 Container prune removes all stopped containers
✅ Always stop before removing unless using -f

Container Inspection & Logs

Debug and inspect running containers for troubleshooting

bash
# View logs
docker logs container_name
docker logs -f container_name           # Follow
docker logs --tail 50 container_name    # Last 50 lines

# Execute commands
docker exec container_name ls
docker exec -it container_name bash

# Inspect container
docker inspect container_name

# Copy files
docker cp container:/path/file local/path
docker cp local/file container:/path/
💡 Use -f to follow logs in real-time
📌 docker exec -it for interactive sessions
⚡ Inspect with --format for specific fields
✅ Copy files without stopping container

Executing Commands in Containers

Run commands inside running containers with docker exec and copy files with docker cp

bash
# Run a command in a running container
docker exec my-container ls /app

# Open an interactive shell
docker exec -it my-container sh
docker exec -it my-container bash

# Copy files between host and container
docker cp my-container:/app/logs ./logs
docker cp ./config.yml my-container:/app/config.yml
💡 docker exec -it opens an interactive terminal — use sh for Alpine, bash for Debian/Ubuntu
⚡ Use docker cp to quickly grab log files or inject config without rebuilding
📌 docker stats shows live resource usage — essential for debugging memory/CPU issues
🟢 docker exec -d runs the command in the background without attaching to it
execcpdebug

Image Management

Building Images

Build Docker images from Dockerfiles with various options

bash
# Build image
docker build -t myapp .
docker build -t myapp:v1 .
docker build -f Dockerfile.dev -t myapp:dev .

# Build arguments
docker build --build-arg VERSION=1.0 -t myapp .

# Build options
docker build --no-cache -t myapp .
docker build --pull -t myapp .
💡 Use .dockerignore to exclude files
⚡ BuildKit provides advanced features
📌 Multi-stage builds reduce image size
✅ Always tag images with versions

Image Operations

Manage Docker images - pull, push, tag, and remove

bash
# List images
docker images
docker image ls

# Pull images
docker pull nginx
docker pull nginx:alpine

# Push images
docker push myregistry/myapp:v1

# Tag images
docker tag myapp:latest myapp:v1.0
docker tag myapp registry/myapp:latest

# Remove images
docker rmi image_name
docker image prune              # Dangling images
💡 Use specific tags instead of latest
⚠️ Prune regularly to save disk space
📌 Save images for offline transfer
✅ Always login before pushing

Image Registry

Work with Docker registries and manage image distribution

bash
# Login to registry
docker login
docker login docker.io
docker login -u user -p pass registry.io

# Logout
docker logout
docker logout registry.io

# Search images
docker search nginx
docker search --limit 10 nginx
docker search --filter stars=100 nginx

# Registry operations
docker pull registry.io/namespace/image:tag
docker push registry.io/namespace/image:tag

# Local registry
docker run -d -p 5000:5000 --name registry registry:2
docker tag myapp localhost:5000/myapp
docker push localhost:5000/myapp
🔒 Always use HTTPS for production registries
💡 Tag images with registry URL
📌 Local registry useful for testing
✅ Implement authentication for private registries

Dockerfile

Write Dockerfiles to build custom images with all the key instructions

Dockerfile Instructions

The essential Dockerfile commands for building images

dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "server.js"]
💡 Always use specific image tags (node:22-alpine) not "latest" — reproducible builds
⚡ Copy package.json first, then npm install, then copy source — maximizes Docker layer cache
📌 ARG is build-time only; ENV persists into the running container — know the difference
🟢 Run as a non-root USER in production — it only takes 2 lines and prevents privilege escalation
dockerfilebuildinstructions

Multi-Stage Builds

Use multiple FROM stages to create small, optimized production images

dockerfile
# Build stage
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Production stage — only the output
FROM node:22-alpine AS production
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]
💡 Multi-stage builds keep dev tools (compilers, build deps) out of the final image
⚡ Go apps can use FROM scratch for the final stage — just the binary, ~10MB total
📌 COPY --from=stagename copies files from a previous stage into the current one
🟢 Use --target to build a specific stage: docker build --target build .
multi-stagebuildoptimization

.dockerignore

Exclude files from the build context to speed up builds and avoid leaking secrets

bash
# .dockerignore
node_modules
.git
.env
*.md
dist
.DS_Store
💡 Without .dockerignore, Docker sends EVERYTHING in the directory to the build daemon
⚡ Always ignore node_modules — they get reinstalled with npm ci inside the image
📌 Ignore .env files to prevent secrets from being baked into the image
🟢 Same syntax as .gitignore — supports wildcards, negation (!important.md), and comments
dockerignorebuildsecurity

Volumes & Networks

Volume Management

Create and manage Docker volumes for persistent data storage

bash
# Volume operations
docker volume create myvolume
docker volume ls
docker volume inspect myvolume
docker volume rm myvolume
docker volume prune

# Use volumes
docker run -v myvolume:/data nginx
docker run -v /host/path:/container/path nginx
💡 Named volumes persist data between containers
📌 Bind mounts for development, volumes for production
⚠️ Prune removes all unused volumes
✅ Backup important volumes regularly

Network Management

Configure Docker networks for container communication

bash
# Network operations
docker network create mynetwork
docker network ls
docker network inspect bridge
docker network rm mynetwork
docker network prune

# Container networking
docker run --network=mynetwork nginx
docker network connect mynetwork container
docker network disconnect mynetwork container
💡 Containers on same network can communicate by name
🔒 Use internal networks for security
📌 Bridge is default, overlay for Swarm
✅ Custom networks provide better isolation

Docker Compose

Compose Basics

Essential Docker Compose commands for multi-container applications

bash
# Start services
docker compose up
docker compose up -d            # Detached
docker compose up --build       # Rebuild

# Stop services
docker compose down
docker compose down -v          # Remove volumes
docker compose stop

# Logs and status
docker compose ps
docker compose logs
docker compose logs -f service

# Execute commands
docker compose exec service bash
docker compose run service command
💡 Use -d for background operation
⚡ --scale for horizontal scaling
📌 -f to specify custom compose files
✅ Always use down -v to clean volumes

Compose Configuration

Full compose.yml reference with depends_on, healthcheck, profiles, watch, and more

yaml
services:
  app:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://user:pass@db:5432/mydb

  db:
    image: postgres:17-alpine
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  db-data:
💡 depends_on with condition: service_healthy waits until the dependency passes its healthcheck
⚡ Compose Watch syncs files without rebuilding — use action: sync for source, action: rebuild for deps
📌 Profiles let you define optional services (debug tools, admin panels) that only start when requested
🟢 Use env_file to load .env files — keeps secrets out of compose.yml and version control

System & Cleanup

System Management

Monitor and manage Docker system resources and information

bash
# System info
docker info
docker version
docker system df

# Cleanup
docker system prune
docker system prune -a
docker container prune
docker image prune
docker volume prune
docker network prune

# Stats
docker stats
docker stats --no-stream
💡 Regular pruning prevents disk issues
⚠️ Prune -a removes all unused images
📌 Use filters to control what gets pruned
✅ Monitor disk usage with system df

Debugging & Troubleshooting

Debug containers and resolve common Docker issues

bash
# Debug running container
docker logs container_name
docker logs -f --tail 50 container_name
docker exec -it container_name sh

# Inspect details
docker inspect container_name
docker inspect image_name

# Debug build
docker build --no-cache --progress=plain .

# Check processes
docker top container_name

# File changes
docker diff container_name
💡 nicolaka/netshoot has many network tools
🔍 Use --progress=plain for detailed build output
📌 Override entrypoint to debug failed containers
✅ Always check logs first when debugging