Learning state
Track this guide
Saved in this browser only. No account required.
Docker Commands Master Class
Engineering-Grade Reference Manual for Docker
A comprehensive guide to Docker commands with real-world examples and production patterns
Table of Contents
- Core Commands
- Intermediate & Advanced Commands
- Docker Compose Mastery
- Troubleshooting & Best Practices
Core Commands
๐น Command: docker run
โ๏ธ What It Does
Creates and starts a new container from an image. This is the most fundamental Docker command that combines image pulling, container creation, and startup into one operation.
โ๏ธ Syntax Examples
# Basic: Run a simple container
docker run nginx
# Real-world: Run with port mapping and detached mode
docker run -d -p 8080:80 --name my-nginx nginx
# Production: Run with resource limits, restart policy, and environment variables
docker run -d \
--name production-app \
-p 443:443 \
-e DATABASE_URL=postgres://db:5432 \
--restart unless-stopped \
--memory="512m" \
--cpus="1.0" \
-v /data:/app/data \
myapp:v1.2.3
โ๏ธ Notes, Tips & Common Mistakes
- Use
-d(detached) for background processes; omit for interactive sessions - Always name containers with
--namefor easier management - Port format:
-p HOST:CONTAINER(e.g.,-p 8080:80) - Use
--rmfor temporary containers that auto-delete after exit - Combine
-itfor interactive terminal sessions
๐น Command: docker pull
โ๏ธ What It Does
Downloads a Docker image from a registry (Docker Hub by default) without running it. Useful for pre-fetching images or updating to latest versions.
โ๏ธ Syntax Examples
# Basic: Pull latest version
docker pull nginx
# Real-world: Pull specific version
docker pull postgres:15.2-alpine
# Production: Pull from private registry
docker pull myregistry.azurecr.io/myapp:v2.1.0
โ๏ธ Notes, Tips & Common Mistakes
- Always specify version tags in production (avoid
:latest) - Use
--platformfor multi-architecture images - Images are cached locally; re-pulling only downloads changed layers
- Check image size before pulling large images
๐น Command: docker ps
โ๏ธ What It Does
Lists running containers. Add -a to see all containers including stopped ones.
โ๏ธ Syntax Examples
# Basic: Show running containers
docker ps
# Real-world: Show all containers with custom formatting
docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# Production: Filter and monitor specific containers
docker ps --filter "status=running" --filter "name=prod-*"
โ๏ธ Notes, Tips & Common Mistakes
- Use
-qto get only container IDs (useful for scripting) --no-truncshows full container IDs and commands- Combine with
grepfor quick filtering:docker ps | grep nginx
๐น Command: docker logs
โ๏ธ What It Does
Retrieves logs from a container's stdout/stderr. Essential for debugging and monitoring.
โ๏ธ Syntax Examples
# Basic: View all logs
docker logs my-container
# Real-world: Follow logs in real-time with timestamps
docker logs -f --timestamps my-app
# Production: View last 100 lines and follow
docker logs --tail 100 -f production-api
โ๏ธ Notes, Tips & Common Mistakes
- Use
-f(follow) to stream logs liketail -f --sinceand--untilfilter by time:--since 1h- Logs are stored until container is removed (can grow large)
- Use log drivers for production (json-file, syslog, fluentd)
๐น Command: docker exec
โ๏ธ What It Does
Executes a command inside a running container. Perfect for debugging, running maintenance tasks, or accessing a shell.
โ๏ธ Syntax Examples
# Basic: Run a single command
docker exec my-container ls /app
# Real-world: Interactive shell access
docker exec -it my-container /bin/bash
# Production: Run database backup
docker exec postgres-db pg_dump -U postgres mydb > backup.sql
โ๏ธ Notes, Tips & Common Mistakes
- Always use
-itfor interactive sessions - Use
/bin/shif/bin/bashis not available (Alpine images) - Cannot exec into stopped containers (use
docker startfirst) - Runs as root by default; use
-uto specify user
๐น Command: docker build
โ๏ธ What It Does
Builds a Docker image from a Dockerfile. This is how you create custom images for your applications.
โ๏ธ Syntax Examples
# Basic: Build from current directory
docker build -t myapp:latest .
# Real-world: Build with build arguments
docker build -t myapp:v1.0 --build-arg NODE_ENV=production .
# Production: Multi-platform build with cache optimization
docker build \
-t myregistry.io/myapp:v2.0.1 \
--platform linux/amd64,linux/arm64 \
--build-arg VERSION=2.0.1 \
--no-cache \
-f Dockerfile.prod \
.
โ๏ธ Notes, Tips & Common Mistakes
- Use
.dockerignoreto exclude unnecessary files - Tag images with meaningful versions, not just
:latest --no-cacheforces fresh build (useful for debugging)- Use
-fto specify alternate Dockerfile names - Build context is the final argument (usually
.)
๐น Command: docker stop / docker start / docker restart
โ๏ธ What It Does
stop: Gracefully stops a running container (SIGTERM, then SIGKILL after timeout)start: Starts a stopped containerrestart: Stops and starts a container
โ๏ธ Syntax Examples
# Basic: Stop a container
docker stop my-container
# Real-world: Stop with custom timeout (default 10s)
docker stop -t 30 my-app
# Production: Restart multiple containers
docker restart $(docker ps -q --filter "name=prod-")
โ๏ธ Notes, Tips & Common Mistakes
stopwaits for graceful shutdown; usekillfor immediate termination- Stopped containers retain their state and can be restarted
- Use
restartfor applying configuration changes that don't require rebuild
๐น Command: docker rm / docker rmi
โ๏ธ What It Does
docker rm: Removes one or more containersdocker rmi: Removes one or more images
โ๏ธ Syntax Examples
# Basic: Remove a stopped container
docker rm my-container
# Real-world: Force remove running container
docker rm -f my-container
# Production: Remove all stopped containers
docker rm $(docker ps -aq -f status=exited)
# Remove unused images
docker rmi $(docker images -f "dangling=true" -q)
โ๏ธ Notes, Tips & Common Mistakes
- Cannot remove running containers without
-f(force) - Cannot remove images used by containers
- Use
docker container prunefor safer cleanup -vflag removes associated anonymous volumes
๐น Command: docker volume
โ๏ธ What It Does
Manages Docker volumes for persistent data storage. Volumes outlive containers and can be shared between containers.
โ๏ธ Syntax Examples
# Basic: Create a volume
docker volume create my-data
# Real-world: List and inspect volumes
docker volume ls
docker volume inspect my-data
# Production: Create and use volume with container
docker run -d \
--name postgres \
-v pgdata:/var/lib/postgresql/data \
postgres:15
# Cleanup unused volumes
docker volume prune
โ๏ธ Notes, Tips & Common Mistakes
- Named volumes persist after container deletion
- Anonymous volumes (no name) are harder to manage
- Use volumes for databases, not bind mounts
- Backup volumes with
docker run --rm -v
๐น Command: docker network
โ๏ธ What It Does
Manages Docker networks for container communication. Containers on the same network can communicate using container names as hostnames.
โ๏ธ Syntax Examples
# Basic: Create a network
docker network create my-network
# Real-world: Create with specific driver and subnet
docker network create --driver bridge --subnet 172.20.0.0/16 app-network
# Production: Connect containers to network
docker network connect app-network my-container
# Inspect network details
docker network inspect app-network
โ๏ธ Notes, Tips & Common Mistakes
- Default bridge network doesn't support DNS resolution
- Custom networks enable container name-based communication
- Use
hostnetwork for maximum performance (loses isolation) overlaynetworks for Docker Swarm multi-host setups
Intermediate & Advanced Commands
๐น Multi-Stage Builds
โ๏ธ What It Does
Optimizes image size by using multiple FROM statements, keeping only necessary artifacts in the final image.
โ๏ธ Example Dockerfile
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]
โ๏ธ Benefits
- Smaller final images (exclude build tools)
- Faster deployments
- Better security (fewer attack surfaces)
๐น Cleanup Commands
โ๏ธ System Prune
# Remove all unused data (containers, networks, images, cache)
docker system prune -a
# Prune with volume cleanup
docker system prune -a --volumes
# Show what would be removed
docker system df
โ๏ธ Targeted Cleanup
# Remove unused images
docker image prune -a
# Remove build cache
docker builder prune
# Remove stopped containers
docker container prune
# Remove unused volumes
docker volume prune
โ๏ธ Notes
- Run cleanup regularly in CI/CD environments
- Use
--filterfor selective cleanup:--filter "until=24h" - Always review before pruning in production
๐น Container Inspection & Debugging
# View detailed container information
docker inspect my-container
# Check resource usage in real-time
docker stats
# View container processes
docker top my-container
# Monitor events
docker events --filter container=my-container
# Export container filesystem
docker export my-container > container.tar
๐น Image Management
# Tag an image
docker tag myapp:latest myregistry.io/myapp:v1.0.0
# Push to registry
docker push myregistry.io/myapp:v1.0.0
# Save image to tar file
docker save myapp:latest > myapp.tar
# Load image from tar file
docker load < myapp.tar
# View image history and layers
docker history myapp:latest
๐น Copy Files
# Copy from container to host
docker cp my-container:/app/logs/app.log ./local-logs/
# Copy from host to container
docker cp ./config.json my-container:/app/config/
# Copy entire directory
docker cp my-container:/app/data ./backup/
Docker Compose Mastery
๐น Command: docker compose up
โ๏ธ What It Does
Starts all services defined in docker-compose.yml. Creates networks, volumes, and containers as needed.
โ๏ธ Syntax Examples
# Basic: Start all services
docker compose up
# Real-world: Detached mode with build
docker compose up -d --build
# Production: Specific services with scaling
docker compose up -d --scale worker=3 api worker
โ๏ธ Example docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=postgres://db:5432/myapp
depends_on:
- db
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
db:
image: postgres:15-alpine
volumes:
- pgdata:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=${DB_PASSWORD}
restart: unless-stopped
volumes:
pgdata:
๐น Command: docker compose down
โ๏ธ What It Does
Stops and removes containers, networks created by up. Volumes persist unless specified.
# Basic: Stop and remove containers
docker compose down
# Remove volumes too
docker compose down -v
# Remove images as well
docker compose down --rmi all
๐น Command: docker compose logs
# View all service logs
docker compose logs
# Follow specific service
docker compose logs -f web
# Last 100 lines from all services
docker compose logs --tail=100
๐น Command: docker compose build
# Build all services
docker compose build
# Build without cache
docker compose build --no-cache
# Build specific service
docker compose build web
๐น Environment Variables & .env Files
โ๏ธ .env File Example
NODE_ENV=production
DB_PASSWORD=secure_password_here
API_KEY=your_api_key
PORT=3000
โ๏ธ Usage in docker-compose.yml
services:
app:
environment:
- NODE_ENV=${NODE_ENV}
- DB_PASSWORD=${DB_PASSWORD}
ports:
- "${PORT}:3000"
๐น Production Best Practices
โ๏ธ Healthchecks
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
โ๏ธ Resource Limits
services:
web:
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
โ๏ธ Logging Configuration
services:
web:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
Troubleshooting & Best Practices
Common Issues & Solutions
Container won't start
# Check logs
docker logs container-name
# Inspect container config
docker inspect container-name
# Check if port is already in use
netstat -an | grep PORT_NUMBER
Out of disk space
# Check Docker disk usage
docker system df
# Clean up
docker system prune -a --volumes
Network connectivity issues
# Inspect network
docker network inspect network-name
# Test connectivity between containers
docker exec container1 ping container2
Security Best Practices
- Never run as root in production
- Use specific image tags, not
:latest - Scan images for vulnerabilities:
docker scan myimage:tag - Use secrets management for sensitive data
- Limit container resources
- Keep images updated regularly
- Use multi-stage builds to reduce attack surface
Performance Optimization
- Use
.dockerignoreto reduce build context - Order Dockerfile commands by change frequency
- Leverage build cache effectively
- Use Alpine-based images when possible
- Combine RUN commands to reduce layers
- Use volumes for I/O intensive operations
๐ Master Class Complete
This reference covers essential Docker commands for enterprise-level engineering. Bookmark this guide and refer to it as your Docker knowledge base.