Docker Commands - Complete Cheatsheet
Updated against the current Docker Docs structure across Get started, Manuals, Guides, and Reference.
Practice these commands with Docker containers and images, Docker Compose v2, Buildx/BuildKit, Docker Scout, Docker Debug, Docker Init, and the newer Docker docs surfaces around AI workflows, Build Cloud, Offload, Hardened Images, and Testcontainers.
1. Docker Information Commands
Command 1: Check Docker version
docker versionCommand 2: Display system-wide information
docker infoCommand 3: Check Docker disk usage
docker system dfCommand 4: Show detailed disk usage
docker system df -vCommand 5: Display real-time events from server
docker eventsCommand 6: Show running processes of container
docker top <container>2. Container Lifecycle Commands
Command 7: Run a container
docker run nginxCommand 8: Run container in detached mode
docker run -d nginxCommand 9: Run container with name
docker run -d --name my-nginx nginxCommand 10: Run container with port mapping
docker run -d -p 8080:80 nginxCommand 11: Run container with environment variables
docker run -d -e ENV=production -e DB_HOST=localhost nginxCommand 12: Run container with volume mount
docker run -d --mount type=bind,src=/host/path,dst=/container/path nginxCommand 13: Run container with interactive terminal
docker run -it ubuntu /bin/bashCommand 14: Run container and remove after exit
docker run --rm -it ubuntu /bin/bashCommand 15: Start a stopped container
docker start <container>Command 16: Stop a running container
docker stop <container>Command 17: Restart a container
docker restart <container>Command 18: Pause a container
docker pause <container>Command 19: Unpause a container
docker unpause <container>Command 20: Kill a container
docker kill <container>Command 21: Remove a container
docker rm <container>Command 22: Force remove a running container
docker rm -f <container>3. Container Inspection Commands
Command 23: List running containers
docker psCommand 24: List all containers (including stopped)
docker ps -aCommand 25: List containers with size
docker ps -sCommand 26: List only container IDs
docker ps -qCommand 27: Inspect container details
docker inspect <container>Command 28: View container logs
docker logs <container>Command 29: Follow container logs (stream)
docker logs -f <container>Command 30: Show last N lines of logs
docker logs --tail 50 <container>Command 31: Show logs with timestamps
docker logs -t <container>Command 32: Show logs since specific time
docker logs --since 30m <container>Command 33: View container resource usage stats
docker statsCommand 34: View stats for specific container
docker stats <container>Command 35: View port mappings
docker port <container>4. Container Execution Commands
Command 36: Execute command in running container
docker exec <container> ls -laCommand 37: Get interactive shell in container
docker exec -it <container> /bin/bashCommand 38: Execute command as specific user
docker exec -u root <container> whoamiCommand 39: Attach to running container
docker attach <container>5. Image Commands
Command 40: List images
docker imagesCommand 41: List all images (including intermediates)
docker images -aCommand 42: Pull image from registry
docker pull nginx:latestCommand 43: Pull specific tag
docker pull nginx:1.21Command 44: Search for image on Docker Hub
docker search nginxCommand 45: Build image from Dockerfile
docker build -t myapp:1.0 .Command 46: Build with no cache
docker build --no-cache -t myapp:1.0 .Command 47: Build from specific Dockerfile
docker build -f Dockerfile.prod -t myapp:prod .Command 48: Build with build arguments
docker build --build-arg VERSION=1.0 -t myapp:1.0 .Command 49: Tag an image
docker tag myapp:1.0 myregistry.com/myapp:1.0Command 50: Push image to registry
docker push myregistry.com/myapp:1.0Command 51: Remove an image
docker rmi nginx:latestCommand 52: Force remove an image
docker rmi -f nginx:latestCommand 53: Remove all unused images
docker image pruneCommand 54: Remove all images
docker rmi $(docker images -q)Command 55: Inspect image details
docker inspect nginx:latestCommand 56: Show image history
docker history nginx:latestCommand 57: Save image to tar archive
docker save -o nginx.tar nginx:latestCommand 58: Load image from tar archive
docker load -i nginx.tar6. Volume Commands
Command 59: List volumes
docker volume lsCommand 60: Create a volume
docker volume create my-volumeCommand 61: Inspect volume
docker volume inspect my-volumeCommand 62: Remove a volume
docker volume rm my-volumeCommand 63: Remove all unused volumes
docker volume pruneCommand 64: Run container with named volume
docker run -d --mount type=volume,src=my-volume,dst=/data nginxCommand 65: Run container with bind mount
docker run -d --mount type=bind,src="$(pwd)",dst=/app nginxCommand 66: Run container with read-only volume
docker run -d --mount type=volume,src=my-volume,dst=/data,readonly nginx7. Network Commands
Command 67: List networks
docker network lsCommand 68: Create a network
docker network create my-networkCommand 69: Create bridge network
docker network create --driver bridge my-bridgeCommand 70: Inspect network
docker network inspect my-networkCommand 71: Connect container to network
docker network connect my-network <container>Command 72: Disconnect container from network
docker network disconnect my-network <container>Command 73: Remove a network
docker network rm my-networkCommand 74: Remove all unused networks
docker network pruneCommand 75: Run container on specific network
docker run -d --network my-network nginx8. Docker Compose Commands
Command 76: Start services
docker compose upCommand 77: Start services in detached mode
docker compose up -dCommand 78: Build and start services
docker compose up --buildCommand 79: Stop services
docker compose downCommand 80: Stop services and remove volumes
docker compose down -vCommand 81: List running services
docker compose psCommand 82: View service logs
docker compose logsCommand 83: Follow service logs
docker compose logs -fCommand 84: View logs for specific service
docker compose logs <service>Command 85: Execute command in service
docker compose exec <service> /bin/bashCommand 86: Scale a service
docker compose up -d --scale web=3Command 87: Build or rebuild services
docker compose buildCommand 88: Restart services
docker compose restartCommand 89: Watch files and rebuild or refresh on changes
docker compose watchCommand 90: Start services with watch enabled
docker compose up --watchCommand 91: Validate compose file
docker compose configCommand 92: Pull service images
docker compose pull9. Registry & Repository Commands
Command 93: Login to Docker registry
docker loginCommand 94: Login to specific registry
docker login myregistry.comCommand 95: Logout from registry
docker logoutCommand 96: Tag image for registry
docker tag myapp:1.0 myregistry.com/myapp:1.0Command 97: Push to registry
docker push myregistry.com/myapp:1.010. Container Copy Commands
Command 98: Copy file from container to host
docker cp <container>:/path/to/file /host/pathCommand 99: Copy file from host to container
docker cp /host/path <container>:/path/to/fileCommand 100: Copy directory from container
docker cp <container>:/path/to/directory /host/path11. System Cleanup Commands
Command 101: Remove stopped containers
docker container pruneCommand 102: Remove unused images
docker image pruneCommand 103: Remove unused volumes
docker volume pruneCommand 104: Remove unused networks
docker network pruneCommand 105: Remove all unused objects
docker system pruneCommand 106: Remove all unused objects including volumes
docker system prune -a --volumesCommand 107: Stop all running containers
docker stop $(docker ps -q)Command 108: Remove all containers
docker rm $(docker ps -a -q)Command 109: Remove all images
docker rmi $(docker images -q)12. Docker Export/Import Commands
Command 110: Export container filesystem
docker export <container> -o container.tarCommand 111: Import container filesystem as image
docker import container.tar myimage:latestCommand 112: Create image from container
docker commit <container> myimage:latestCommand 113: Create image with commit message
docker commit -m "Added feature" <container> myimage:1.013. Advanced Run Options
Command 114: Run with resource limits (memory)
docker run -d --memory="512m" nginxCommand 115: Run with CPU limits
docker run -d --cpus="1.5" nginxCommand 116: Run with restart policy
docker run -d --restart=always nginxCommand 117: Run with restart policy (on-failure)
docker run -d --restart=on-failure:3 nginxCommand 118: Run with hostname
docker run -d --hostname myhost nginxCommand 119: Run with DNS settings
docker run -d --dns 8.8.8.8 nginxCommand 120: Run with add host entry
docker run -d --add-host myhost:192.168.1.100 nginxCommand 121: Run with working directory
docker run -d -w /app nginxCommand 122: Run with user
docker run -d --user 1000:1000 nginxCommand 123: Run in privileged mode
docker run -d --privileged nginx14. Docker Context Commands
Command 124: List contexts
docker context lsCommand 125: Create context
docker context create mycontextCommand 126: Use context
docker context use mycontextCommand 127: Inspect context
docker context inspect mycontextCommand 128: Remove context
docker context rm mycontext15. Health Check Commands
Command 129: Run with health check
docker run -d --health-cmd="curl -f http://localhost/" --health-interval=30s nginxCommand 130: Check container health status
docker inspect --format='{{.State.Health.Status}}' <container>16. Multi-Stage Build Commands
Command 131: Build with specific target stage
docker build --target=builder -t myapp:builder .Command 132: Build final stage from multi-stage Dockerfile
docker build --target=production -t myapp:prod .Multi-stage Dockerfile Example:
# Stage 1: Build
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
# Stage 2: Production
FROM node:18-slim AS production
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
CMD ["node", "app.js"]17. Docker Scout, Debug, and Runtime Security Commands
Current Docker docs emphasize Docker Scout for image analysis, Docker Debug for shell-less containers and images, and Docker Init for project bootstrapping.
Command 133: Analyze image vulnerabilities with Docker Scout
docker scout cves nginx:latestCommand 134: Get image improvement recommendations with Docker Scout
docker scout recommendations nginx:latestCommand 135: Open a debug shell into a running container
docker debug <container>Command 136: Debug an image directly, even if it has no shell
docker debug nginx:latestCommand 137: Bootstrap Docker files for an application
docker initCommand 138: Run containers as a non-root user with a read-only filesystem
docker run -d --user 1001:1001 --read-only nginxCommand 139: Add no-new-privileges for runtime hardening
docker run -d --security-opt=no-new-privileges nginxCommand 140: Drop all capabilities and add back only what you need
docker run -d --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx18. BuildKit & Advanced Build (Latest Features)
On current Docker Desktop and modern Docker installations, BuildKit is the standard build engine. Use docker buildx build when you need multi-platform output, advanced cache backends, attestations, or alternate export targets.
Basic BuildKit Commands
Command 141: Build with Buildx and load the result locally
docker buildx build -t myapp:latest --load .Command 142: Build with build cache from registry
docker buildx build --cache-from myregistry.com/myapp:latest -t myapp:latest --load .Command 143: Build with inline cache
docker buildx build --build-arg BUILDKIT_INLINE_CACHE=1 -t myapp:latest --push .Buildx Builder Management
Command 144: Create new buildx builder with docker-container driver
docker buildx create --name mybuilder --driver docker-container --useCommand 145: Create builder with specific configuration
docker buildx create --name mybuilder \
--driver docker-container \
--driver-opt network=host \
--buildkitd-flags '--allow-insecure-entitlement security.insecure' \
--useCommand 146: Create builder from config file
docker buildx create --name mybuilder --config buildkitd.tomlCommand 147: Create builder with multiple nodes
docker buildx create --name mybuilder --node mybuilder-0 --driver docker-container
docker buildx create --name mybuilder --append --node mybuilder-1 --driver docker-containerCommand 148: List buildx builders
docker buildx lsCommand 149: Inspect builder
docker buildx inspect mybuilderCommand 150: Bootstrap builder (start without building)
docker buildx inspect mybuilder --bootstrapCommand 151: Use specific builder
docker buildx use mybuilderCommand 152: Remove builder
docker buildx rm mybuilderCommand 153: Stop builder instance
docker buildx stop mybuilderMulti-Platform Builds
Command 154: Build for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 \
-t myregistry.com/myapp:latest --push .Command 155: Build for specific platform only
docker buildx build --platform linux/arm64 -t myapp:arm64 --load .Command 156: Build for all common platforms
docker buildx build \
--platform linux/amd64,linux/arm64,linux/arm/v7,linux/ppc64le,linux/s390x \
-t myapp:latest --push .Advanced Cache Options
Command 157: Use registry cache
docker buildx build \
--cache-from type=registry,ref=myregistry.com/myapp:cache \
--cache-to type=registry,ref=myregistry.com/myapp:cache,mode=max \
-t myapp:latest .Command 158: Use local cache directory
docker buildx build \
--cache-from type=local,src=/tmp/cache \
--cache-to type=local,dest=/tmp/cache,mode=max \
-t myapp:latest .Command 159: Use GitHub Actions cache
docker buildx build \
--cache-from type=gha \
--cache-to type=gha,mode=max \
-t myapp:latest .Command 160: Use inline cache (embedded in image)
docker buildx build \
--cache-to type=inline \
-t myapp:latest --push .Command 161: Use S3 cache backend
docker buildx build \
--cache-from type=s3,region=us-east-1,bucket=mybucket,name=mycache \
--cache-to type=s3,region=us-east-1,bucket=mybucket,name=mycache,mode=max \
-t myapp:latest .Multiple Output Formats
Command 162: Push directly to registry
docker buildx build -t myregistry.com/myapp:latest --push .Command 163: Load image to local Docker
docker buildx build -t myapp:latest --load .Command 164: Export to OCI tar
docker buildx build -o type=oci,dest=image.tar .Command 165: Export to Docker tar
docker buildx build -o type=docker,dest=image.tar .Command 166: Export to local directory
docker buildx build -o type=local,dest=./output .Command 167: Multiple outputs
docker buildx build \
-t myapp:latest \
--output type=image,push=true \
--output type=docker,dest=image.tar \
.Buildx Bake (Advanced Multi-Build)
Command 168: Build using bake file
docker buildx bakeCommand 169: Build specific target from bake file
docker buildx bake frontend backendCommand 170: Bake with override
docker buildx bake --set "*.platform=linux/amd64,linux/arm64"Command 171: Bake with file
docker buildx bake -f docker-bake.hclCommand 172: Print bake plan without building
docker buildx bake --printExample docker-bake.hcl:
group "default" {
targets = ["frontend", "backend"]
}
target "frontend" {
context = "./frontend"
dockerfile = "Dockerfile"
tags = ["myapp/frontend:latest"]
platforms = ["linux/amd64", "linux/arm64"]
}
target "backend" {
context = "./backend"
dockerfile = "Dockerfile"
tags = ["myapp/backend:latest"]
platforms = ["linux/amd64", "linux/arm64"]
}Secrets & SSH in Builds
Command 173: Build with secret from file
docker buildx build --secret id=mysecret,src=/path/to/secret -t myapp:latest .Command 174: Build with secret from environment
docker buildx build --secret id=aws,env=AWS_SECRET_ACCESS_KEY -t myapp:latest .Command 175: Build with SSH agent forwarding
docker buildx build --ssh default -t myapp:latest .Command 176: Build with specific SSH key
docker buildx build --ssh default=/path/to/key -t myapp:latest .Using secrets in Dockerfile:
# syntax=docker/dockerfile:1
FROM alpine
RUN --mount=type=secret,id=mysecret \
cat /run/secrets/mysecret > /app/configAttestations & SBOM (Software Bill of Materials)
Command 177: Build with SBOM attestation
docker buildx build --sbom=true -t myapp:latest --push .Command 178: Build with provenance attestation
docker buildx build --provenance=true -t myapp:latest --push .Command 179: Build with both SBOM and provenance
docker buildx build --sbom=true --provenance=true -t myapp:latest --push .Command 180: Disable attestations
docker buildx build --provenance=false --sbom=false -t myapp:latest --push .Buildx ImageTools (Manifest Management)
Command 181: Inspect remote image
docker buildx imagetools inspect myregistry.com/myapp:latestCommand 182: Create multi-platform manifest
docker buildx imagetools create -t myapp:latest \
myapp:amd64 \
myapp:arm64Command 183: Annotate manifest
docker buildx imagetools create -t myapp:latest \
--annotation "index:org.opencontainers.image.description=My Application"Command 184: Create manifest from different sources
docker buildx imagetools create -t myregistry.com/myapp:latest \
myregistry.com/myapp:amd64 \
otherregistry.com/myapp:arm64Build Cache Management
Command 185: Show disk usage by builder
docker buildx duCommand 186: Show verbose cache details
docker buildx du --verboseCommand 187: Prune build cache
docker buildx pruneCommand 188: Prune all build cache
docker buildx prune -aCommand 189: Prune with filter
docker buildx prune --filter until=24hCommand 190: Force prune without confirmation
docker buildx prune -fAdvanced Build Options
Command 191: Build with custom network mode
docker buildx build --network=host -t myapp:latest .Command 192: Build with build arguments
docker buildx build \
--build-arg VERSION=1.0 \
--build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
-t myapp:latest .Command 193: Build with specific target stage
docker buildx build --target production -t myapp:prod .Command 194: Build with metadata output
docker buildx build \
--metadata-file metadata.json \
-t myapp:latest .Command 195: Build with ulimits
docker buildx build --ulimit nofile=1024:1024 -t myapp:latest .Command 196: Build with shm-size
docker buildx build --shm-size=2g -t myapp:latest .Command 197: Build with progress output
docker buildx build --progress=plain -t myapp:latest .Command 198: Build with no cache and pull latest base
docker buildx build --no-cache --pull -t myapp:latest .Remote Builders (Cloud/Kubernetes)
Command 199: Create Kubernetes builder
docker buildx create --name k8s-builder \
--driver kubernetes \
--driver-opt namespace=buildkit \
--useCommand 200: Create remote builder
docker buildx create --name remote-builder \
--driver remote \
tcp://remote-host:123419. Troubleshooting & Debugging
Command 149: Inspect image layers and sizes
docker history <image>Command 150: Show only layer sizes
docker history --no-trunc --format "{{.Size}}\t{{.CreatedBy}}" <image>Command 151: Run container with all logs to stdout
docker run -d --log-driver json-file --log-opt max-size=10m nginxCommand 152: Check why container exited
docker inspect --format='{{.State.ExitCode}} {{.State.Error}}' <container>Command 153: View container changes in filesystem
docker diff <container>Command 154: Attach to container STDOUT/STDERR
docker attach --sig-proxy=false <container>Command 155: Run with specific entrypoint override
docker run -it --entrypoint /bin/sh nginxCommand 156: Debug failed build by running intermediate image
docker run -it <intermediate_image_id> /bin/bashCommand 157: Check container resource limits
docker inspect --format='{{.HostConfig.Memory}} {{.HostConfig.CpuShares}}' <container>Command 158: View detailed error logs
docker events --filter 'event=die' --filter 'event=oom'Command 159: Test container networking
docker run --rm --network container:<container> nicolaka/netshoot20. Logging & Monitoring
Command 160: Configure logging driver for container
docker run -d --log-driver=syslog nginxCommand 161: Set log rotation
docker run -d --log-opt max-size=10m --log-opt max-file=3 nginxCommand 162: View Docker daemon logs (systemd)
journalctl -u docker.service -fCommand 163: Enable debug mode for Docker daemon
dockerd --debugCommand 164: Get real-time events
docker events --since '1h' --filter 'type=container'Command 165: Check container exit code
docker inspect --format='{{.State.ExitCode}}' <container>21. Performance Tuning
Command 166: Limit container memory with swap
docker run -d --memory="512m" --memory-swap="1g" nginxCommand 167: Set CPU shares (relative weight)
docker run -d --cpu-shares=512 nginxCommand 168: Pin container to specific CPUs
docker run -d --cpuset-cpus="0,1" nginxCommand 169: Set I/O weight
docker run -d --blkio-weight=500 nginxCommand 170: Limit disk write rate
docker run -d --device-write-bps /dev/sda:1mb nginxCommand 171: Set PID limit
docker run -d --pids-limit=100 nginxCommand 172: Use tmpfs mount for performance
docker run -d --tmpfs /app/cache:rw,noexec,nosuid,size=100m nginx22. Docker Swarm Basics
Command 173: Initialize Docker Swarm
docker swarm initCommand 174: Join swarm as worker
docker swarm join --token <token> <manager-ip>:2377Command 175: List swarm nodes
docker node lsCommand 176: Deploy stack from compose file
docker stack deploy -c docker-compose.yml mystackCommand 177: List services in stack
docker stack services mystackCommand 178: Scale service
docker service scale mystack_web=5Command 179: List service tasks
docker service ps mystack_webCommand 180: Remove stack
docker stack rm mystack23. Container Signals & Lifecycle
Command 181: Send SIGTERM to container
docker kill --signal=SIGTERM <container>Command 182: Send custom signal
docker kill --signal=SIGUSR1 <container>Command 183: Stop with custom timeout
docker stop -t 30 <container>Command 184: Graceful shutdown with timeout
docker stop --time=60 <container>Command 185: Wait for container to stop
docker wait <container>Command 186: Rename a container
docker rename old-name new-name24. Advanced Image Operations
Command 187: Flatten image (export/import)
docker export <container> | docker import - myimage:flatCommand 188: Inspect specific layer
docker image inspect --format='{{json .RootFS.Layers}}' <image> | jqCommand 189: Show image manifest
docker manifest inspect nginx:latestCommand 190: Create multi-platform manifest
docker manifest create myapp:latest myapp:amd64 myapp:arm64Command 191: Pull image for specific platform
docker pull --platform linux/arm64 nginx:latestCommand 192: Inspect image config
docker image inspect --format='{{json .Config}}' <image> | jq25. Docker Daemon Management
Command 193: Check Docker daemon status
systemctl status dockerCommand 194: Restart Docker daemon
systemctl restart dockerCommand 195: Enable Docker on boot
systemctl enable dockerCommand 196: View Docker daemon config
cat /etc/docker/daemon.jsonCommand 197: Reload daemon configuration
systemctl daemon-reload && systemctl restart docker26. Latest Docker Docs Features To Learn Next
A headless scan of Docker’s current Get started, Guides, Manuals, and Reference sections shows that the platform story now goes beyond classic container commands. The biggest additions are AI workflow tooling, cloud-backed build acceleration, secure base images, and testing flows built around containers.
Newer Docker Surfaces Now Visible In The Docs
- AI workflows: Docker Model Runner , MCP Catalog and Toolkit , and the broader AI docs area surfaced from the Manuals navigation.
- Cloud-backed builds: Docker Build Cloud and Docker Offload are now first-class docs areas for remote build and run workflows.
- Secure foundations: Docker Hardened Images appears as a dedicated product track for minimal, security-focused base images.
- Testing workflows: Testcontainers and Testcontainers Cloud are now part of the main Docker docs information architecture.
Highest-Value Guides From The Current Docs
- Build and run agentic AI applications with Docker
- Building Compose projects with Bake
- Docker Build Cloud: Reclaim your time with fast, multi-architecture builds
- Securing your software supply chain with Docker Scout
- Generate Docker Compose Files with Claude Code and Docker MCP Toolkit
Practice Sequence For Modern Docker Learning
- Start with project bootstrapping and local feedback loops.
- Move into Compose watch and Bake for multi-service development.
- Add Scout, SBOM, and provenance for software supply chain visibility.
- Explore Build Cloud or Offload when local build time becomes the bottleneck.
- Add Testcontainers when you want repeatable integration tests with real dependencies.
docker init
docker compose up --watch
docker buildx bake --print
docker scout recommendations myimage:latest
docker debug myimage:latestWhat To Keep In Mind
docker buildx buildremains the foundation for modern Docker build workflows.- The newer docs are increasingly centered on complete developer loops: bootstrap, inner-loop iteration, remote build acceleration, supply-chain security, AI workflows, and test automation.
- If you already know classic
docker run,docker build, anddocker compose, the next learning jump is not more container flags. It is learning how these newer Docker products fit together.
Common Flags & Options
Run flags:
-d- Detached mode (background)-it- Interactive with TTY-p- Publish port-v- Volume mount-e- Environment variable--name- Container name--rm- Remove after exit--network- Connect to network--restart- Restart policy--memory- Memory limit--cpus- CPU limit
Output formats:
-q- Quiet mode (IDs only)-a- All (includes stopped)-f- Filter output--format- Format output using template--no-trunc- Don’t truncate output
Common options:
-f- Force operation-t- Tag for image--rm- Remove intermediate containers--build-arg- Build-time variables--no-cache- Don’t use cache when building
Quick Reference
Container Operations
docker run [OPTIONS] IMAGE # Create and start container
docker start <container> # Start stopped container
docker stop <container> # Stop running container
docker restart <container> # Restart container
docker rm <container> # Remove container
docker ps # List running containers
docker ps -a # List all containers
docker logs <container> # View container logs
docker exec -it <container> /bin/bash # Get shell in containerImage Operations
docker images # List images
docker pull <image> # Pull image from registry
docker build -t <name:tag> . # Build image from Dockerfile
docker push <image> # Push image to registry
docker rmi <image> # Remove image
docker tag <source> <target> # Tag an imageVolume Operations
docker volume ls # List volumes
docker volume create <volume> # Create volume
docker volume rm <volume> # Remove volume
docker volume inspect <volume> # Inspect volumeNetwork Operations
docker network ls # List networks
docker network create <network> # Create network
docker network rm <network> # Remove network
docker network connect <net> <cont> # Connect container to networkDocker Compose Operations
docker compose up # Start services
docker compose up -d # Start in detached mode
docker compose down # Stop and remove services
docker compose ps # List services
docker compose logs # View service logs
docker compose exec <service> <cmd> # Execute command in serviceCleanup Operations
docker system prune # Remove unused data
docker container prune # Remove stopped containers
docker image prune # Remove unused images
docker volume prune # Remove unused volumes
docker network prune # Remove unused networksPractice Tips
- Start with basic run commands to understand container lifecycle
- Practice building images from Dockerfiles in this directory
- Use
docker inspectto understand container and image details - Always name your containers for easier management
- Use
docker composefor multi-container applications - Clean up regularly with prune commands to save disk space
- Use
.dockerignoreto exclude files from build context - Tag images properly with version numbers for better tracking
- Mount volumes for persistent data and development
- Check logs frequently when debugging container issues
Useful One-Liners
Stop and remove all containers
docker stop $(docker ps -q) && docker rm $(docker ps -a -q)Remove all unused resources
docker system prune -a --volumes -fGet shell in running container
docker exec -it $(docker ps -q -l) /bin/bashRemove dangling images
docker rmi $(docker images -f "dangling=true" -q)View logs from all containers
docker ps -q | xargs -L 1 docker logsShow container IP addresses
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)Monitor real-time container stats
docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"Popular Service Port Numbers (Essential for Docker)
Web Servers & Proxies
- HTTP: 80 # nginx, apache, caddy
- HTTPS: 443 # nginx, apache, caddy (TLS/SSL)
- HTTP Alt: 8080 # Alternative HTTP, Tomcat
- HTTP Alt 2: 8000 # Alternative HTTP, development servers
- HTTP Alt 3: 3000 # Node.js default, React dev server
- HTTP Alt 4: 4200 # Angular CLI dev server
- HTTP Alt 5: 5000 # Flask default
- HTTP Alt 6: 8888 # Alternative HTTP, Jupyter
- Nginx: 80, 443
- Apache: 80, 443
- Tomcat: 8080 # Also 8443 for HTTPS
- Jetty: 8080
- HAProxy: 80, 443, 8404 (stats)
- Traefik: 80, 443, 8080 (dashboard)
- Caddy: 80, 443, 2019 (admin API)
- IIS: 80, 443Databases (Relational)
- PostgreSQL: 5432
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=secret postgres:15
- MySQL: 3306
docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret mysql:8
- MariaDB: 3306
docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret mariadb:10
- MS SQL Server: 1433
docker run -d -p 1433:1433 -e ACCEPT_EULA=Y -e SA_PASSWORD=SecureP@ss mcr.microsoft.com/mssql/server
- Oracle: 1521
- IBM DB2: 50000
- CockroachDB: 26257 (SQL), 8080 (Admin UI)Databases (NoSQL)
- MongoDB: 27017 (default), 27018, 27019
docker run -d -p 27017:27017 mongo:6
- Redis: 6379
docker run -d -p 6379:6379 redis:7
- Cassandra: 7000 (internode), 9042 (CQL), 7199 (JMX)
docker run -d -p 9042:9042 cassandra:4
- Elasticsearch: 9200 (HTTP), 9300 (Transport)
docker run -d -p 9200:9200 -p 9300:9300 elasticsearch:8.8.0
- Couchbase: 8091-8096, 11210
- CouchDB: 5984
docker run -d -p 5984:5984 couchdb:3
- Neo4j: 7474 (HTTP), 7687 (Bolt)
docker run -d -p 7474:7474 -p 7687:7687 neo4j:5
- InfluxDB: 8086
docker run -d -p 8086:8086 influxdb:2.7
- TimescaleDB: 5432 (PostgreSQL compatible)
- ArangoDB: 8529
- DynamoDB Local: 8000
docker run -d -p 8000:8000 amazon/dynamodb-localMessage Queues & Event Streaming
- RabbitMQ: 5672 (AMQP), 15672 (Management UI)
docker run -d -p 5672:5672 -p 15672:15672 rabbitmq:3-management
- Apache Kafka: 9092 (broker), 9093 (SSL)
# Zookeeper: 2181, 2888, 3888
- Apache ActiveMQ: 61616 (OpenWire), 8161 (Web Console)
- NATS: 4222 (client), 8222 (HTTP monitoring)
- Apache Pulsar: 6650 (binary), 8080 (HTTP)
- ZeroMQ: 5555, 5556 (configurable)
- AWS SQS (Local): 9324
- Celery: 5672 (RabbitMQ backend)
- Redis Queue: 6379 (via Redis)Cache Systems
- Redis: 6379
- Memcached: 11211
docker run -d -p 11211:11211 memcached:1.6
- Varnish: 80, 6081 (default), 6082 (admin)
- Hazelcast: 5701-5703Search Engines
- Elasticsearch: 9200 (HTTP), 9300 (Transport)
- Solr: 8983
docker run -d -p 8983:8983 solr:9
- Meilisearch: 7700
- Algolia: 443 (cloud-based)
- Typesense: 8108Monitoring & Observability
- Prometheus: 9090
docker run -d -p 9090:9090 prom/prometheus
- Grafana: 3000
docker run -d -p 3000:3000 grafana/grafana
- Jaeger: 16686 (UI), 14268 (collector), 6831 (agent)
- Zipkin: 9411
- New Relic: 443 (cloud)
- Datadog Agent: 8125 (DogStatsD), 8126 (APM)
- Kibana: 5601
docker run -d -p 5601:5601 kibana:8.8.0
- Splunk: 8000 (Web), 8089 (Management), 9997 (Forwarder)
- Nagios: 80
- Zabbix: 10051 (server), 10050 (agent)
- Netdata: 19999
- InfluxDB: 8086
- Telegraf: 8125, 8092, 8094Container Orchestration & Management
- Kubernetes API: 6443
- Kubelet: 10250
- Kube Proxy: 10256
- etcd: 2379 (client), 2380 (peer)
- Docker Engine: 2375 (HTTP), 2376 (HTTPS)
- Docker Registry: 5000
docker run -d -p 5000:5000 registry:2
- Portainer: 9000 (HTTP), 8000 (tunnel)
docker run -d -p 9000:9000 -p 8000:8000 portainer/portainer-ce
- Rancher: 80, 443
- Nomad: 4646 (HTTP), 4647, 4648
- Consul: 8500 (HTTP), 8600 (DNS)CI/CD & DevOps Tools
- Jenkins: 8080 (Web), 50000 (Agent)
docker run -d -p 8080:8080 -p 50000:50000 jenkins/jenkins:lts
- GitLab: 80, 443, 22 (SSH)
- GitHub Actions: N/A (cloud-based)
- CircleCI: N/A (cloud-based)
- TeamCity: 8111
- Bamboo: 8085
- Travis CI: N/A (cloud-based)
- ArgoCD: 8080, 8083
- Drone: 80
- Concourse: 8080
- Spinnaker: 9000 (Deck), 8084 (Gate)
- Harbor: 80, 443Development Tools
- Jupyter: 8888
docker run -d -p 8888:8888 jupyter/scipy-notebook
- VS Code Server: 8080
- JupyterLab: 8888
- RStudio: 8787
- Apache Airflow: 8080
- Superset: 8088
- MLflow: 5000
- Kubeflow: 8080
- Keycloak: 8080
docker run -d -p 8080:8080 quay.io/keycloak/keycloakAPI Gateways & Service Mesh
- Kong: 8000 (proxy), 8001 (admin), 8443 (SSL), 8444 (admin SSL)
- Tyk: 8080
- Ambassador: 8080, 8443
- Istio: 15010-15014, 15017, 15020
- Linkerd: 4191, 4143
- Envoy: 10000 (admin), 9901 (stats)
- NGINX Plus: 80, 443, 8080 (API)
- Apigee: 9001File Storage & Object Storage
- MinIO: 9000 (API), 9001 (Console)
docker run -d -p 9000:9000 -p 9001:9001 minio/minio server /data --console-address ":9001"
- SeaweedFS: 9333 (master), 8080 (volume)
- Nextcloud: 80, 443
docker run -d -p 8080:80 nextcloud
- ownCloud: 80
- Samba: 445, 139
- NFS: 2049
- FTP: 21 (control), 20 (data)
- SFTP: 22Authentication & Security
- Keycloak: 8080, 8443
- OAuth2 Proxy: 4180
- Vault: 8200
docker run -d -p 8200:8200 vault:1.13
- Auth0: 443 (cloud)
- Okta: 443 (cloud)
- LDAP: 389 (plain), 636 (SSL)
- Active Directory: 389, 636, 88 (Kerberos)
- OpenLDAP: 389, 636Email Servers
- SMTP: 25 (plain), 587 (TLS), 465 (SSL)
- IMAP: 143 (plain), 993 (SSL)
- POP3: 110 (plain), 995 (SSL)
- Postfix: 25
- Dovecot: 143, 993, 110, 995
- MailHog: 1025 (SMTP), 8025 (UI)
docker run -d -p 1025:1025 -p 8025:8025 mailhog/mailhog
- Mailcatcher: 1025 (SMTP), 1080 (Web)Application Servers
- Node.js: 3000 (typical)
- Express.js: 3000 (typical)
- Ruby on Rails: 3000 (default)
- Django: 8000 (default)
- Flask: 5000 (default)
- FastAPI: 8000 (typical)
- Spring Boot: 8080 (default)
- ASP.NET: 5000 (HTTP), 5001 (HTTPS)
- Laravel: 8000 (php artisan serve)
- Phoenix (Elixir): 4000 (default)
- Go (net/http): 8080 (typical)Content Management Systems
- WordPress: 80
docker run -d -p 8080:80 wordpress
- Drupal: 80
- Joomla: 80
- Ghost: 2368
docker run -d -p 2368:2368 ghost
- Strapi: 1337
- Contentful: 443 (cloud)Analytics & Business Intelligence
- Metabase: 3000
docker run -d -p 3000:3000 metabase/metabase
- Redash: 5000
- Tableau: 80, 8000
- Apache Superset: 8088
- Matomo: 80
- Plausible: 8000Game Servers
- Minecraft: 25565
docker run -d -p 25565:25565 itzg/minecraft-server
- Counter-Strike: 27015
- TeamSpeak: 9987 (voice), 10011 (ServerQuery), 30033 (File Transfer)
- Mumble: 64738
- Discord Bot: N/A (uses Discord API)Testing & Mock Servers
- Selenium Hub: 4444
docker run -d -p 4444:4444 selenium/hub
- Selenium Node: 5555
- WireMock: 8080
- MockServer: 1080
- JSON Server: 3000
- Mockoon: 3000VPN & Network Tools
- OpenVPN: 1194
- WireGuard: 51820
- IPsec: 500, 4500
- PPTP: 1723
- SSH: 22
docker run -d -p 2222:22 linuxserver/openssh-server
- Telnet: 23
- FTP: 21
- SFTP: 22Common Docker Compose Port Mappings
version: '3.8'
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
postgres:
image: postgres:15
ports:
- "5432:5432"
redis:
image: redis:7
ports:
- "6379:6379"
mongodb:
image: mongo:6
ports:
- "27017:27017"
rabbitmq:
image: rabbitmq:3-management
ports:
- "5672:5672" # AMQP
- "15672:15672" # Management UI
elasticsearch:
image: elasticsearch:8.8.0
ports:
- "9200:9200"
- "9300:9300"
kibana:
image: kibana:8.8.0
ports:
- "5601:5601"
prometheus:
image: prom/prometheus
ports:
- "9090:9090"
grafana:
image: grafana/grafana
ports:
- "3000:3000"
jenkins:
image: jenkins/jenkins:lts
ports:
- "8080:8080"
- "50000:50000"
gitlab:
image: gitlab/gitlab-ce
ports:
- "80:80"
- "443:443"
- "22:22"
portainer:
image: portainer/portainer-ce
ports:
- "9000:9000"
- "8000:8000"
minio:
image: minio/minio
ports:
- "9000:9000"
- "9001:9001"
vault:
image: vault:1.13
ports:
- "8200:8200"
keycloak:
image: quay.io/keycloak/keycloak
ports:
- "8080:8080"
mailhog:
image: mailhog/mailhog
ports:
- "1025:1025" # SMTP
- "8025:8025" # Web UIPort Conflict Resolution Tips
# Check if port is in use
lsof -i :8080
netstat -an | grep 8080
ss -tulpn | grep 8080
# Map to different host port to avoid conflicts
docker run -d -p 8081:8080 myapp # Instead of 8080:8080
# Use docker inspect to check port mappings
docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}}{{$p}} -> {{(index $conf 0).HostPort}} {{end}}' <container>
# Find which container is using a port
docker ps --format '{{.Names}}\t{{.Ports}}' | grep 8080Interview Tips for Port Mapping
-
Standard vs Custom Ports
- Standard: Use well-known ports in containers (80, 3306, etc.)
- Host mapping: Map to different ports on host to avoid conflicts
docker run -d -p 8080:80 nginx # nginx uses 80 inside, 8080 on host -
Security Consideration
- Bind to localhost only for dev:
-p 127.0.0.1:5432:5432 - Expose to all interfaces:
-p 5432:5432or-p 0.0.0.0:5432:5432
# Only accessible from localhost (secure) docker run -d -p 127.0.0.1:5432:5432 postgres # Accessible from any interface (less secure) docker run -d -p 5432:5432 postgres - Bind to localhost only for dev:
-
Multiple Port Mappings
docker run -d \ -p 80:80 \ -p 443:443 \ -p 8080:8080 \ nginx -
Dynamic Port Assignment
# Let Docker assign random host port docker run -d -p 5432 postgres # Check assigned port docker port <container> 5432 -
UDP vs TCP
# TCP (default) docker run -d -p 53:53 bind9 # UDP explicitly docker run -d -p 53:53/udp bind9 # Both TCP and UDP docker run -d -p 53:53/tcp -p 53:53/udp bind9
Common Dockerfile Instructions
FROM ubuntu:22.04 # Base image
WORKDIR /app # Set working directory
COPY . . # Copy files to container
RUN apt-get update && apt-get install # Run commands
ENV NODE_ENV=production # Set environment variables
EXPOSE 8080 # Document port
CMD ["node", "app.js"] # Default command
ENTRYPOINT ["python"] # Fixed command prefix
USER appuser # Set user
VOLUME ["/data"] # Create mount point
LABEL version="1.0" # Add metadata
ARG VERSION=latest # Build argument
HEALTHCHECK CMD curl -f http://localhost/ # Health checkDocker Compose File Example
version: '3.8'
services:
web:
build: .
ports:
- "8080:80"
volumes:
- ./app:/app
environment:
- NODE_ENV=production
depends_on:
- db
restart: always
db:
image: postgres:14
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=secret
volumes:
db-data:
networks:
default:
driver: bridgeInterview Q&A Scenarios
Scenario 1: Container keeps restarting
# Check logs
docker logs --tail 100 <container>
# Check exit code
docker inspect --format='{{.State.ExitCode}}' <container>
# Check resource limits
docker stats <container>
# Try running without restart policy
docker run --rm -it <image> /bin/bashScenario 2: Image size is too large
# Check layer sizes
docker history <image> --no-trunc
# Use multi-stage builds
# Use alpine base images
# Use .dockerignore file
# Remove unnecessary files in same RUN layerScenario 3: Container cannot connect to network
# Check container network
docker inspect --format='{{json .NetworkSettings.Networks}}' <container>
# Test DNS resolution
docker exec <container> nslookup google.com
# Check if port is exposed
docker port <container>
# Inspect network
docker network inspect <network>Scenario 4: Out of disk space
# Check disk usage
docker system df
# Remove unused resources
docker system prune -a --volumes
# Check for large log files
find /var/lib/docker/containers -name "*-json.log" -exec ls -lh {} \;Scenario 5: Build failing due to cache
# Build without cache
docker build --no-cache -t myapp:latest .
# Clear build cache
docker builder prune -a
# Use specific cache from registry
docker build --cache-from myapp:latest -t myapp:latest .Docker Best Practices
Dockerfile Best Practices
-
Use specific base image tags - Not
latestFROM node:18.17-alpine # Good FROM node # Bad -
Use multi-stage builds - Reduce final image size
FROM node:18 AS builder RUN npm ci FROM node:18-alpine COPY --from=builder /app . -
Order layers by change frequency - Leverage cache
FROM node:18 WORKDIR /app COPY package*.json ./ # Changes less RUN npm ci COPY . . # Changes more -
Combine RUN commands - Reduce layers
RUN apt-get update && \ apt-get install -y curl && \ rm -rf /var/lib/apt/lists/* # Clean in same layer -
Use .dockerignore - Exclude unnecessary files
node_modules .git *.md .env -
Run as non-root user - Security
RUN adduser -D appuser USER appuser -
Use COPY instead of ADD - Unless you need tar extraction
COPY app.js /app/ # Preferred ADD archive.tar /app/ # Only when needed -
Pin versions - Reproducible builds
RUN apt-get install -y python3=3.9.2-1
Security Best Practices
- Never store secrets in images
- Scan images regularly -
docker scout cves - Use official base images
- Keep images updated - Patch vulnerabilities
- Limit container capabilities -
--cap-drop - Use read-only filesystem when possible
- Run as non-root user
- Set resource limits - Prevent DoS
- Use secrets management - Docker secrets or vault
- Enable Content Trust -
DOCKER_CONTENT_TRUST=1
Operations Best Practices
- Name your containers - Easy identification
- Use health checks - Auto recovery
- Set restart policies - High availability
- Use labels - Better organization
- Configure logging - Troubleshooting
- Monitor resource usage -
docker stats - Regular cleanup -
docker system prune - Use volumes for data - Persistence
- Use networks - Container isolation
- Document with labels - Metadata
Docker Buildx Best Practices (Modern Builds)
-
Use buildx for all new projects - Superior to legacy docker build
docker buildx build --platform linux/amd64,linux/arm64 --push -t myapp:latest . -
Always specify platforms explicitly - Don’t rely on defaults
# Good - explicit platforms docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest . # Bad - platform may vary based on host docker buildx build -t myapp:latest . -
Use registry cache for CI/CD - Faster builds
docker buildx build \ --cache-from type=registry,ref=myregistry.com/myapp:cache \ --cache-to type=registry,ref=myregistry.com/myapp:cache,mode=max \ -t myapp:latest --push . -
Use GitHub Actions cache for GH workflows
docker buildx build \ --cache-from type=gha \ --cache-to type=gha,mode=max \ -t myapp:latest . -
Leverage buildx bake for monorepos - Build multiple images
docker buildx bake -f docker-bake.hcl --push -
Use secrets for sensitive data - Never hardcode
docker buildx build --secret id=token,env=GITHUB_TOKEN -t myapp:latest . -
Enable SBOM and provenance in production - Security and compliance
docker buildx build --sbom=true --provenance=true -t myapp:latest --push . -
Create dedicated builder instances - Isolate build environments
docker buildx create --name prod-builder --driver docker-container --use -
Use mode=max for cache - Cache all layers
--cache-to type=registry,mode=max # Cache all layers --cache-to type=registry,mode=min # Cache only final layers (default) -
Clean up build cache regularly - Prevent disk bloat
docker buildx prune --filter until=72h # Remove cache older than 3 days
Buildx Common Use Cases
Use Case 1: Multi-Architecture Container Registry
# Setup builder
docker buildx create --name multiarch --use
# Build and push for multiple platforms
docker buildx build \
--platform linux/amd64,linux/arm64,linux/arm/v7 \
-t myregistry.com/myapp:latest \
--push .Use Case 2: Fast CI/CD with Registry Cache
# In CI/CD pipeline
docker buildx build \
--cache-from type=registry,ref=myregistry.com/myapp:buildcache \
--cache-to type=registry,ref=myregistry.com/myapp:buildcache,mode=max \
-t myregistry.com/myapp:${CI_COMMIT_SHA} \
--push .Use Case 3: Local Development with Load
# Build for local architecture and load into Docker
docker buildx build \
--platform linux/amd64 \
-t myapp:dev \
--load .Use Case 4: Export Build Artifacts
# Export built files without creating image
docker buildx build \
--target artifacts \
--output type=local,dest=./dist \
.Use Case 5: Monorepo with Bake
# docker-bake.json
{
"group": {
"default": {
"targets": ["frontend", "backend", "api"]
}
},
"target": {
"frontend": {
"context": "./frontend",
"tags": ["myapp/frontend:latest"],
"platforms": ["linux/amd64", "linux/arm64"]
},
"backend": {
"context": "./backend",
"tags": ["myapp/backend:latest"],
"platforms": ["linux/amd64", "linux/arm64"]
},
"api": {
"context": "./api",
"tags": ["myapp/api:latest"],
"platforms": ["linux/amd64", "linux/arm64"]
}
}
}# Build all services
docker buildx bake --pushCMD vs ENTRYPOINT - Interview Favorite!
CMD - Default command (can be overridden)
FROM ubuntu
CMD ["echo", "Hello World"]docker run myimage # Prints: Hello World
docker run myimage echo "Bye" # Prints: Bye (CMD overridden)ENTRYPOINT - Fixed command (arguments appended)
FROM ubuntu
ENTRYPOINT ["echo"]docker run myimage "Hello" # Prints: Hello
docker run myimage "Bye" # Prints: ByeCombining ENTRYPOINT + CMD (Best Practice)
FROM ubuntu
ENTRYPOINT ["python"]
CMD ["app.py"]docker run myimage # Runs: python app.py
docker run myimage test.py # Runs: python test.pyOverride ENTRYPOINT at runtime
docker run --entrypoint /bin/bash myimageCommon Pitfalls & Solutions
Pitfall 1: Using :latest tag
Problem: Unpredictable builds, version conflicts
Solution: Always use specific version tags
FROM node:18.17-alpine # Good
FROM node:latest # BadPitfall 2: Running as root
Problem: Security vulnerability
Solution: Create and use non-root user
RUN adduser -D appuser
USER appuserPitfall 3: Large image sizes
Problem: Slow deployments, wasted space
Solution: Use multi-stage builds, alpine images, .dockerignore
Pitfall 4: Not cleaning up in same layer
Problem: Large image size
Solution: Clean up in same RUN command
# Bad
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# Good
RUN apt-get update && \
apt-get install -y curl && \
rm -rf /var/lib/apt/lists/*Pitfall 5: Forgetting .dockerignore
Problem: Large build context, slow builds
Solution: Always create .dockerignore file
Pitfall 6: No health checks
Problem: Container appears running but app is down
Solution: Add HEALTHCHECK
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost/ || exit 1Pitfall 7: Hardcoding configuration
Problem: Not portable across environments
Solution: Use environment variables
ENV DB_HOST=localhost
ENV DB_PORT=5432Pitfall 8: No resource limits
Problem: One container can starve others
Solution: Set memory and CPU limits
docker run -d --memory="512m" --cpus="1" myappKey Differences (Interview Questions)
Container vs Image
- Image: Read-only template with app and dependencies
- Container: Running instance of an image
COPY vs ADD
- COPY: Simple file copy (preferred)
- ADD: Extra features (tar extraction, URL support)
CMD vs ENTRYPOINT
- CMD: Default command, easily overridden
- ENTRYPOINT: Main executable, arguments appended
RUN vs CMD vs ENTRYPOINT
- RUN: Executes during build (creates layer)
- CMD: Runs when container starts (default arguments)
- ENTRYPOINT: Runs when container starts (main command)
ARG vs ENV
- ARG: Build-time variable only
- ENV: Runtime variable (persists in image)
docker compose up vs docker compose start
- up: Create and start containers
- start: Start existing stopped containers
docker stop vs docker kill
- stop: Sends SIGTERM, then SIGKILL (graceful)
- kill: Sends SIGKILL immediately (force)
Bind mount vs Volume
- Bind mount: Specific host path
- Volume: Managed by Docker (preferred)
docker build vs docker buildx build
- docker build: Legacy builder, single platform, basic caching
- docker buildx build: Modern builder (BuildKit), multi-platform, advanced cache, secrets, SBOM, provenance
| Feature | docker build | docker buildx build |
|---|---|---|
| Multi-platform | ❌ No | ✅ Yes |
| Registry cache | Limited | ✅ Full support |
| Secrets | ❌ No | ✅ Yes |
| SSH forwarding | ❌ No | ✅ Yes |
| SBOM/Provenance | ❌ No | ✅ Yes |
| Multiple outputs | ❌ No | ✅ Yes (OCI, tar, local) |
| Bake (multi-target) | ❌ No | ✅ Yes |
| Remote builders | ❌ No | ✅ Yes |
| Performance | Slower | ✅ Faster (parallel) |
Migration Example:
# Old way
docker build -t myapp:latest .
docker push myapp:latest
# New way (buildx)
docker buildx build \
--platform linux/amd64,linux/arm64 \
--cache-to type=registry,mode=max \
-t myregistry.com/myapp:latest \
--push .Quick Command Combinations
Build, tag, and push in one go
docker build -t myregistry.com/myapp:1.0 . && \
docker push myregistry.com/myapp:1.0Remove all stopped containers and dangling images
docker container prune -f && docker image prune -fComplete cleanup (nuclear option)
docker stop $(docker ps -q) 2>/dev/null; \
docker system prune -a --volumes -fRun temporary testing container
docker run --rm -it -v $(pwd):/app -w /app node:18 /bin/bashDebug networking issues
docker run --rm --network container:<container_name> nicolaka/netshootCheck all container resource usage
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"Find which container is using most memory
docker stats --no-stream --format "table {{.Name}}\t{{.MemUsage}}" | sort -k 2 -h.dockerignore Example
# Dependencies
node_modules
vendor
# Build outputs
dist
build
target
# Logs
*.log
logs/
# Version control
.git
.gitignore
# Environment files
.env
.env.local
*.env
# IDE
.vscode
.idea
*.swp
# Testing
coverage
.pytest_cache
# Documentation
README.md
docs/
# CI/CD
.github
.gitlab-ci.yml
Jenkinsfile
# OS files
.DS_Store
Thumbs.dbProduction-Ready Dockerfile Example
# Multi-stage build for Node.js app
FROM node:18-alpine AS builder
# Install build dependencies
RUN apk add --no-cache python3 make g++
WORKDIR /app
# Copy dependency files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production && \
npm cache clean --force
# Copy application code
COPY . .
# Build application
RUN npm run build
# Production stage
FROM node:18-alpine AS production
# Add non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
WORKDIR /app
# Copy dependencies from builder
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/package.json ./
# Switch to non-root user
USER nodejs
# Expose port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
CMD node healthcheck.js
# Set environment
ENV NODE_ENV=production
# Start application
CMD ["node", "dist/server.js"]Practice Directory: ./docker/
Related Files: Dockerfile, docker-compose.yaml, requirements.txt
Interview Topics Covered:
✅ 200+ Docker commands across 25 categories
✅ Latest Docker Buildx features (multi-platform, cache backends, SBOM, provenance)
✅ Multi-stage builds & BuildKit advanced features
✅ Buildx builder management & imagetools
✅ Registry/GitHub Actions/S3/Local cache strategies
✅ Secrets & SSH forwarding in builds
✅ Buildx bake for monorepo/multi-service builds
✅ Security best practices & vulnerability scanning
✅ Troubleshooting & debugging techniques
✅ Performance tuning & resource management
✅ Docker Swarm orchestration basics
✅ Common interview Q&A scenarios
✅ Best practices & anti-patterns
✅ CMD vs ENTRYPOINT explained
✅ docker build vs docker buildx comparison
✅ Production-ready Dockerfile examples
✅ Real-world problem solving scenarios
Latest Buildx Features (2024-2026):
- Multi-platform builds (ARM64, AMD64, ARM/v7, etc.)
- Advanced cache backends (registry, GHA, S3, local)
- SBOM & provenance attestations for supply chain security
- Buildx bake for complex multi-service builds
- Secrets & SSH agent forwarding
- Multiple output formats (OCI, Docker, local, tar)
- Remote builders (Kubernetes, cloud)
- Imagetools for manifest management