# 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
```bash
docker version
```

**Command 2:** Display system-wide information
```bash
docker info
```

**Command 3:** Check Docker disk usage
```bash
docker system df
```

**Command 4:** Show detailed disk usage
```bash
docker system df -v
```

**Command 5:** Display real-time events from server
```bash
docker events
```

**Command 6:** Show running processes of container
```bash
docker top <container>
```

---

## 2. Container Lifecycle Commands

**Command 7:** Run a container
```bash
docker run nginx
```

**Command 8:** Run container in detached mode
```bash
docker run -d nginx
```

**Command 9:** Run container with name
```bash
docker run -d --name my-nginx nginx
```

**Command 10:** Run container with port mapping
```bash
docker run -d -p 8080:80 nginx
```

**Command 11:** Run container with environment variables
```bash
docker run -d -e ENV=production -e DB_HOST=localhost nginx
```

**Command 12:** Run container with volume mount
```bash
docker run -d --mount type=bind,src=/host/path,dst=/container/path nginx
```

**Command 13:** Run container with interactive terminal
```bash
docker run -it ubuntu /bin/bash
```

**Command 14:** Run container and remove after exit
```bash
docker run --rm -it ubuntu /bin/bash
```

**Command 15:** Start a stopped container
```bash
docker start <container>
```

**Command 16:** Stop a running container
```bash
docker stop <container>
```

**Command 17:** Restart a container
```bash
docker restart <container>
```

**Command 18:** Pause a container
```bash
docker pause <container>
```

**Command 19:** Unpause a container
```bash
docker unpause <container>
```

**Command 20:** Kill a container
```bash
docker kill <container>
```

**Command 21:** Remove a container
```bash
docker rm <container>
```

**Command 22:** Force remove a running container
```bash
docker rm -f <container>
```

---

## 3. Container Inspection Commands

**Command 23:** List running containers
```bash
docker ps
```

**Command 24:** List all containers (including stopped)
```bash
docker ps -a
```

**Command 25:** List containers with size
```bash
docker ps -s
```

**Command 26:** List only container IDs
```bash
docker ps -q
```

**Command 27:** Inspect container details
```bash
docker inspect <container>
```

**Command 28:** View container logs
```bash
docker logs <container>
```

**Command 29:** Follow container logs (stream)
```bash
docker logs -f <container>
```

**Command 30:** Show last N lines of logs
```bash
docker logs --tail 50 <container>
```

**Command 31:** Show logs with timestamps
```bash
docker logs -t <container>
```

**Command 32:** Show logs since specific time
```bash
docker logs --since 30m <container>
```

**Command 33:** View container resource usage stats
```bash
docker stats
```

**Command 34:** View stats for specific container
```bash
docker stats <container>
```

**Command 35:** View port mappings
```bash
docker port <container>
```

---

## 4. Container Execution Commands

**Command 36:** Execute command in running container
```bash
docker exec <container> ls -la
```

**Command 37:** Get interactive shell in container
```bash
docker exec -it <container> /bin/bash
```

**Command 38:** Execute command as specific user
```bash
docker exec -u root <container> whoami
```

**Command 39:** Attach to running container
```bash
docker attach <container>
```

---

## 5. Image Commands

**Command 40:** List images
```bash
docker images
```

**Command 41:** List all images (including intermediates)
```bash
docker images -a
```

**Command 42:** Pull image from registry
```bash
docker pull nginx:latest
```

**Command 43:** Pull specific tag
```bash
docker pull nginx:1.21
```

**Command 44:** Search for image on Docker Hub
```bash
docker search nginx
```

**Command 45:** Build image from Dockerfile
```bash
docker build -t myapp:1.0 .
```

**Command 46:** Build with no cache
```bash
docker build --no-cache -t myapp:1.0 .
```

**Command 47:** Build from specific Dockerfile
```bash
docker build -f Dockerfile.prod -t myapp:prod .
```

**Command 48:** Build with build arguments
```bash
docker build --build-arg VERSION=1.0 -t myapp:1.0 .
```

**Command 49:** Tag an image
```bash
docker tag myapp:1.0 myregistry.com/myapp:1.0
```

**Command 50:** Push image to registry
```bash
docker push myregistry.com/myapp:1.0
```

**Command 51:** Remove an image
```bash
docker rmi nginx:latest
```

**Command 52:** Force remove an image
```bash
docker rmi -f nginx:latest
```

**Command 53:** Remove all unused images
```bash
docker image prune
```

**Command 54:** Remove all images
```bash
docker rmi $(docker images -q)
```

**Command 55:** Inspect image details
```bash
docker inspect nginx:latest
```

**Command 56:** Show image history
```bash
docker history nginx:latest
```

**Command 57:** Save image to tar archive
```bash
docker save -o nginx.tar nginx:latest
```

**Command 58:** Load image from tar archive
```bash
docker load -i nginx.tar
```

---

## 6. Volume Commands

**Command 59:** List volumes
```bash
docker volume ls
```

**Command 60:** Create a volume
```bash
docker volume create my-volume
```

**Command 61:** Inspect volume
```bash
docker volume inspect my-volume
```

**Command 62:** Remove a volume
```bash
docker volume rm my-volume
```

**Command 63:** Remove all unused volumes
```bash
docker volume prune
```

**Command 64:** Run container with named volume
```bash
docker run -d --mount type=volume,src=my-volume,dst=/data nginx
```

**Command 65:** Run container with bind mount
```bash
docker run -d --mount type=bind,src="$(pwd)",dst=/app nginx
```

**Command 66:** Run container with read-only volume
```bash
docker run -d --mount type=volume,src=my-volume,dst=/data,readonly nginx
```

---

## 7. Network Commands

**Command 67:** List networks
```bash
docker network ls
```

**Command 68:** Create a network
```bash
docker network create my-network
```

**Command 69:** Create bridge network
```bash
docker network create --driver bridge my-bridge
```

**Command 70:** Inspect network
```bash
docker network inspect my-network
```

**Command 71:** Connect container to network
```bash
docker network connect my-network <container>
```

**Command 72:** Disconnect container from network
```bash
docker network disconnect my-network <container>
```

**Command 73:** Remove a network
```bash
docker network rm my-network
```

**Command 74:** Remove all unused networks
```bash
docker network prune
```

**Command 75:** Run container on specific network
```bash
docker run -d --network my-network nginx
```

---

## 8. Docker Compose Commands

**Command 76:** Start services
```bash
docker compose up
```

**Command 77:** Start services in detached mode
```bash
docker compose up -d
```

**Command 78:** Build and start services
```bash
docker compose up --build
```

**Command 79:** Stop services
```bash
docker compose down
```

**Command 80:** Stop services and remove volumes
```bash
docker compose down -v
```

**Command 81:** List running services
```bash
docker compose ps
```

**Command 82:** View service logs
```bash
docker compose logs
```

**Command 83:** Follow service logs
```bash
docker compose logs -f
```

**Command 84:** View logs for specific service
```bash
docker compose logs <service>
```

**Command 85:** Execute command in service
```bash
docker compose exec <service> /bin/bash
```

**Command 86:** Scale a service
```bash
docker compose up -d --scale web=3
```

**Command 87:** Build or rebuild services
```bash
docker compose build
```

**Command 88:** Restart services
```bash
docker compose restart
```

**Command 89:** Watch files and rebuild or refresh on changes
```bash
docker compose watch
```

**Command 90:** Start services with watch enabled
```bash
docker compose up --watch
```

**Command 91:** Validate compose file
```bash
docker compose config
```

**Command 92:** Pull service images
```bash
docker compose pull
```

---

## 9. Registry & Repository Commands

**Command 93:** Login to Docker registry
```bash
docker login
```

**Command 94:** Login to specific registry
```bash
docker login myregistry.com
```

**Command 95:** Logout from registry
```bash
docker logout
```

**Command 96:** Tag image for registry
```bash
docker tag myapp:1.0 myregistry.com/myapp:1.0
```

**Command 97:** Push to registry
```bash
docker push myregistry.com/myapp:1.0
```

---

## 10. Container Copy Commands

**Command 98:** Copy file from container to host
```bash
docker cp <container>:/path/to/file /host/path
```

**Command 99:** Copy file from host to container
```bash
docker cp /host/path <container>:/path/to/file
```

**Command 100:** Copy directory from container
```bash
docker cp <container>:/path/to/directory /host/path
```

---

## 11. System Cleanup Commands

**Command 101:** Remove stopped containers
```bash
docker container prune
```

**Command 102:** Remove unused images
```bash
docker image prune
```

**Command 103:** Remove unused volumes
```bash
docker volume prune
```

**Command 104:** Remove unused networks
```bash
docker network prune
```

**Command 105:** Remove all unused objects
```bash
docker system prune
```

**Command 106:** Remove all unused objects including volumes
```bash
docker system prune -a --volumes
```

**Command 107:** Stop all running containers
```bash
docker stop $(docker ps -q)
```

**Command 108:** Remove all containers
```bash
docker rm $(docker ps -a -q)
```

**Command 109:** Remove all images
```bash
docker rmi $(docker images -q)
```

---

## 12. Docker Export/Import Commands

**Command 110:** Export container filesystem
```bash
docker export <container> -o container.tar
```

**Command 111:** Import container filesystem as image
```bash
docker import container.tar myimage:latest
```

**Command 112:** Create image from container
```bash
docker commit <container> myimage:latest
```

**Command 113:** Create image with commit message
```bash
docker commit -m "Added feature" <container> myimage:1.0
```

---

## 13. Advanced Run Options

**Command 114:** Run with resource limits (memory)
```bash
docker run -d --memory="512m" nginx
```

**Command 115:** Run with CPU limits
```bash
docker run -d --cpus="1.5" nginx
```

**Command 116:** Run with restart policy
```bash
docker run -d --restart=always nginx
```

**Command 117:** Run with restart policy (on-failure)
```bash
docker run -d --restart=on-failure:3 nginx
```

**Command 118:** Run with hostname
```bash
docker run -d --hostname myhost nginx
```

**Command 119:** Run with DNS settings
```bash
docker run -d --dns 8.8.8.8 nginx
```

**Command 120:** Run with add host entry
```bash
docker run -d --add-host myhost:192.168.1.100 nginx
```

**Command 121:** Run with working directory
```bash
docker run -d -w /app nginx
```

**Command 122:** Run with user
```bash
docker run -d --user 1000:1000 nginx
```

**Command 123:** Run in privileged mode
```bash
docker run -d --privileged nginx
```

---

## 14. Docker Context Commands

**Command 124:** List contexts
```bash
docker context ls
```

**Command 125:** Create context
```bash
docker context create mycontext
```

**Command 126:** Use context
```bash
docker context use mycontext
```

**Command 127:** Inspect context
```bash
docker context inspect mycontext
```

**Command 128:** Remove context
```bash
docker context rm mycontext
```

---

## 15. Health Check Commands

**Command 129:** Run with health check
```bash
docker run -d --health-cmd="curl -f http://localhost/" --health-interval=30s nginx
```

**Command 130:** Check container health status
```bash
docker inspect --format='{{.State.Health.Status}}' <container>
```

---

## 16. Multi-Stage Build Commands

**Command 131:** Build with specific target stage
```bash
docker build --target=builder -t myapp:builder .
```

**Command 132:** Build final stage from multi-stage Dockerfile
```bash
docker build --target=production -t myapp:prod .
```

**Multi-stage Dockerfile Example:**
```dockerfile
# 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
```bash
docker scout cves nginx:latest
```

**Command 134:** Get image improvement recommendations with Docker Scout
```bash
docker scout recommendations nginx:latest
```

**Command 135:** Open a debug shell into a running container
```bash
docker debug <container>
```

**Command 136:** Debug an image directly, even if it has no shell
```bash
docker debug nginx:latest
```

**Command 137:** Bootstrap Docker files for an application
```bash
docker init
```

**Command 138:** Run containers as a non-root user with a read-only filesystem
```bash
docker run -d --user 1001:1001 --read-only nginx
```

**Command 139:** Add no-new-privileges for runtime hardening
```bash
docker run -d --security-opt=no-new-privileges nginx
```

**Command 140:** Drop all capabilities and add back only what you need
```bash
docker run -d --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx
```

---

## 18. 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
```bash
docker buildx build -t myapp:latest --load .
```

**Command 142:** Build with build cache from registry
```bash
docker buildx build --cache-from myregistry.com/myapp:latest -t myapp:latest --load .
```

**Command 143:** Build with inline cache
```bash
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
```bash
docker buildx create --name mybuilder --driver docker-container --use
```

**Command 145:** Create builder with specific configuration
```bash
docker buildx create --name mybuilder \
  --driver docker-container \
  --driver-opt network=host \
  --buildkitd-flags '--allow-insecure-entitlement security.insecure' \
  --use
```

**Command 146:** Create builder from config file
```bash
docker buildx create --name mybuilder --config buildkitd.toml
```

**Command 147:** Create builder with multiple nodes
```bash
docker buildx create --name mybuilder --node mybuilder-0 --driver docker-container
docker buildx create --name mybuilder --append --node mybuilder-1 --driver docker-container
```

**Command 148:** List buildx builders
```bash
docker buildx ls
```

**Command 149:** Inspect builder
```bash
docker buildx inspect mybuilder
```

**Command 150:** Bootstrap builder (start without building)
```bash
docker buildx inspect mybuilder --bootstrap
```

**Command 151:** Use specific builder
```bash
docker buildx use mybuilder
```

**Command 152:** Remove builder
```bash
docker buildx rm mybuilder
```

**Command 153:** Stop builder instance
```bash
docker buildx stop mybuilder
```

### Multi-Platform Builds

**Command 154:** Build for multiple platforms
```bash
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 \
  -t myregistry.com/myapp:latest --push .
```

**Command 155:** Build for specific platform only
```bash
docker buildx build --platform linux/arm64 -t myapp:arm64 --load .
```

**Command 156:** Build for all common platforms
```bash
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
```bash
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
```bash
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
```bash
docker buildx build \
  --cache-from type=gha \
  --cache-to type=gha,mode=max \
  -t myapp:latest .
```

**Command 160:** Use inline cache (embedded in image)
```bash
docker buildx build \
  --cache-to type=inline \
  -t myapp:latest --push .
```

**Command 161:** Use S3 cache backend
```bash
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
```bash
docker buildx build -t myregistry.com/myapp:latest --push .
```

**Command 163:** Load image to local Docker
```bash
docker buildx build -t myapp:latest --load .
```

**Command 164:** Export to OCI tar
```bash
docker buildx build -o type=oci,dest=image.tar .
```

**Command 165:** Export to Docker tar
```bash
docker buildx build -o type=docker,dest=image.tar .
```

**Command 166:** Export to local directory
```bash
docker buildx build -o type=local,dest=./output .
```

**Command 167:** Multiple outputs
```bash
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
```bash
docker buildx bake
```

**Command 169:** Build specific target from bake file
```bash
docker buildx bake frontend backend
```

**Command 170:** Bake with override
```bash
docker buildx bake --set "*.platform=linux/amd64,linux/arm64"
```

**Command 171:** Bake with file
```bash
docker buildx bake -f docker-bake.hcl
```

**Command 172:** Print bake plan without building
```bash
docker buildx bake --print
```

**Example docker-bake.hcl:**
```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
```bash
docker buildx build --secret id=mysecret,src=/path/to/secret -t myapp:latest .
```

**Command 174:** Build with secret from environment
```bash
docker buildx build --secret id=aws,env=AWS_SECRET_ACCESS_KEY -t myapp:latest .
```

**Command 175:** Build with SSH agent forwarding
```bash
docker buildx build --ssh default -t myapp:latest .
```

**Command 176:** Build with specific SSH key
```bash
docker buildx build --ssh default=/path/to/key -t myapp:latest .
```

**Using secrets in Dockerfile:**
```dockerfile
# syntax=docker/dockerfile:1
FROM alpine
RUN --mount=type=secret,id=mysecret \
    cat /run/secrets/mysecret > /app/config
```

### Attestations & SBOM (Software Bill of Materials)

**Command 177:** Build with SBOM attestation
```bash
docker buildx build --sbom=true -t myapp:latest --push .
```

**Command 178:** Build with provenance attestation
```bash
docker buildx build --provenance=true -t myapp:latest --push .
```

**Command 179:** Build with both SBOM and provenance
```bash
docker buildx build --sbom=true --provenance=true -t myapp:latest --push .
```

**Command 180:** Disable attestations
```bash
docker buildx build --provenance=false --sbom=false -t myapp:latest --push .
```

### Buildx ImageTools (Manifest Management)

**Command 181:** Inspect remote image
```bash
docker buildx imagetools inspect myregistry.com/myapp:latest
```

**Command 182:** Create multi-platform manifest
```bash
docker buildx imagetools create -t myapp:latest \
  myapp:amd64 \
  myapp:arm64
```

**Command 183:** Annotate manifest
```bash
docker buildx imagetools create -t myapp:latest \
  --annotation "index:org.opencontainers.image.description=My Application"
```

**Command 184:** Create manifest from different sources
```bash
docker buildx imagetools create -t myregistry.com/myapp:latest \
  myregistry.com/myapp:amd64 \
  otherregistry.com/myapp:arm64
```

### Build Cache Management

**Command 185:** Show disk usage by builder
```bash
docker buildx du
```

**Command 186:** Show verbose cache details
```bash
docker buildx du --verbose
```

**Command 187:** Prune build cache
```bash
docker buildx prune
```

**Command 188:** Prune all build cache
```bash
docker buildx prune -a
```

**Command 189:** Prune with filter
```bash
docker buildx prune --filter until=24h
```

**Command 190:** Force prune without confirmation
```bash
docker buildx prune -f
```

### Advanced Build Options

**Command 191:** Build with custom network mode
```bash
docker buildx build --network=host -t myapp:latest .
```

**Command 192:** Build with build arguments
```bash
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
```bash
docker buildx build --target production -t myapp:prod .
```

**Command 194:** Build with metadata output
```bash
docker buildx build \
  --metadata-file metadata.json \
  -t myapp:latest .
```

**Command 195:** Build with ulimits
```bash
docker buildx build --ulimit nofile=1024:1024 -t myapp:latest .
```

**Command 196:** Build with shm-size
```bash
docker buildx build --shm-size=2g -t myapp:latest .
```

**Command 197:** Build with progress output
```bash
docker buildx build --progress=plain -t myapp:latest .
```

**Command 198:** Build with no cache and pull latest base
```bash
docker buildx build --no-cache --pull -t myapp:latest .
```

### Remote Builders (Cloud/Kubernetes)

**Command 199:** Create Kubernetes builder
```bash
docker buildx create --name k8s-builder \
  --driver kubernetes \
  --driver-opt namespace=buildkit \
  --use
```

**Command 200:** Create remote builder
```bash
docker buildx create --name remote-builder \
  --driver remote \
  tcp://remote-host:1234
```

---

## 19. Troubleshooting & Debugging

**Command 149:** Inspect image layers and sizes
```bash
docker history <image>
```

**Command 150:** Show only layer sizes
```bash
docker history --no-trunc --format "{{.Size}}\t{{.CreatedBy}}" <image>
```

**Command 151:** Run container with all logs to stdout
```bash
docker run -d --log-driver json-file --log-opt max-size=10m nginx
```

**Command 152:** Check why container exited
```bash
docker inspect --format='{{.State.ExitCode}} {{.State.Error}}' <container>
```

**Command 153:** View container changes in filesystem
```bash
docker diff <container>
```

**Command 154:** Attach to container STDOUT/STDERR
```bash
docker attach --sig-proxy=false <container>
```

**Command 155:** Run with specific entrypoint override
```bash
docker run -it --entrypoint /bin/sh nginx
```

**Command 156:** Debug failed build by running intermediate image
```bash
docker run -it <intermediate_image_id> /bin/bash
```

**Command 157:** Check container resource limits
```bash
docker inspect --format='{{.HostConfig.Memory}} {{.HostConfig.CpuShares}}' <container>
```

**Command 158:** View detailed error logs
```bash
docker events --filter 'event=die' --filter 'event=oom'
```

**Command 159:** Test container networking
```bash
docker run --rm --network container:<container> nicolaka/netshoot
```

---

## 20. Logging & Monitoring

**Command 160:** Configure logging driver for container
```bash
docker run -d --log-driver=syslog nginx
```

**Command 161:** Set log rotation
```bash
docker run -d --log-opt max-size=10m --log-opt max-file=3 nginx
```

**Command 162:** View Docker daemon logs (systemd)
```bash
journalctl -u docker.service -f
```

**Command 163:** Enable debug mode for Docker daemon
```bash
dockerd --debug
```

**Command 164:** Get real-time events
```bash
docker events --since '1h' --filter 'type=container'
```

**Command 165:** Check container exit code
```bash
docker inspect --format='{{.State.ExitCode}}' <container>
```

---

## 21. Performance Tuning

**Command 166:** Limit container memory with swap
```bash
docker run -d --memory="512m" --memory-swap="1g" nginx
```

**Command 167:** Set CPU shares (relative weight)
```bash
docker run -d --cpu-shares=512 nginx
```

**Command 168:** Pin container to specific CPUs
```bash
docker run -d --cpuset-cpus="0,1" nginx
```

**Command 169:** Set I/O weight
```bash
docker run -d --blkio-weight=500 nginx
```

**Command 170:** Limit disk write rate
```bash
docker run -d --device-write-bps /dev/sda:1mb nginx
```

**Command 171:** Set PID limit
```bash
docker run -d --pids-limit=100 nginx
```

**Command 172:** Use tmpfs mount for performance
```bash
docker run -d --tmpfs /app/cache:rw,noexec,nosuid,size=100m nginx
```

---

## 22. Docker Swarm Basics

**Command 173:** Initialize Docker Swarm
```bash
docker swarm init
```

**Command 174:** Join swarm as worker
```bash
docker swarm join --token <token> <manager-ip>:2377
```

**Command 175:** List swarm nodes
```bash
docker node ls
```

**Command 176:** Deploy stack from compose file
```bash
docker stack deploy -c docker-compose.yml mystack
```

**Command 177:** List services in stack
```bash
docker stack services mystack
```

**Command 178:** Scale service
```bash
docker service scale mystack_web=5
```

**Command 179:** List service tasks
```bash
docker service ps mystack_web
```

**Command 180:** Remove stack
```bash
docker stack rm mystack
```

---

## 23. Container Signals & Lifecycle

**Command 181:** Send SIGTERM to container
```bash
docker kill --signal=SIGTERM <container>
```

**Command 182:** Send custom signal
```bash
docker kill --signal=SIGUSR1 <container>
```

**Command 183:** Stop with custom timeout
```bash
docker stop -t 30 <container>
```

**Command 184:** Graceful shutdown with timeout
```bash
docker stop --time=60 <container>
```

**Command 185:** Wait for container to stop
```bash
docker wait <container>
```

**Command 186:** Rename a container
```bash
docker rename old-name new-name
```

---

## 24. Advanced Image Operations

**Command 187:** Flatten image (export/import)
```bash
docker export <container> | docker import - myimage:flat
```

**Command 188:** Inspect specific layer
```bash
docker image inspect --format='{{json .RootFS.Layers}}' <image> | jq
```

**Command 189:** Show image manifest
```bash
docker manifest inspect nginx:latest
```

**Command 190:** Create multi-platform manifest
```bash
docker manifest create myapp:latest myapp:amd64 myapp:arm64
```

**Command 191:** Pull image for specific platform
```bash
docker pull --platform linux/arm64 nginx:latest
```

**Command 192:** Inspect image config
```bash
docker image inspect --format='{{json .Config}}' <image> | jq
```

---

## 25. Docker Daemon Management

**Command 193:** Check Docker daemon status
```bash
systemctl status docker
```

**Command 194:** Restart Docker daemon
```bash
systemctl restart docker
```

**Command 195:** Enable Docker on boot
```bash
systemctl enable docker
```

**Command 196:** View Docker daemon config
```bash
cat /etc/docker/daemon.json
```

**Command 197:** Reload daemon configuration
```bash
systemctl daemon-reload && systemctl restart docker
```

---

## 26. 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](https://docs.docker.com/ai/model-runner/), [MCP Catalog and Toolkit](https://docs.docker.com/ai/mcp-catalog-and-toolkit/), and the broader AI docs area surfaced from the Manuals navigation.
- **Cloud-backed builds:** [Docker Build Cloud](https://docs.docker.com/build-cloud/) and [Docker Offload](https://docs.docker.com/offload/) are now first-class docs areas for remote build and run workflows.
- **Secure foundations:** [Docker Hardened Images](https://docs.docker.com/dhi/) appears as a dedicated product track for minimal, security-focused base images.
- **Testing workflows:** [Testcontainers](https://docs.docker.com/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](https://docs.docker.com/guides/agentic-ai/)
- [Building Compose projects with Bake](https://docs.docker.com/guides/compose-bake/)
- [Docker Build Cloud: Reclaim your time with fast, multi-architecture builds](https://docs.docker.com/guides/docker-build-cloud/)
- [Securing your software supply chain with Docker Scout](https://docs.docker.com/guides/docker-scout/)
- [Generate Docker Compose Files with Claude Code and Docker MCP Toolkit](https://docs.docker.com/guides/genai-claude-code-mcp/claude-code-mcp-guide/)

### Practice Sequence For Modern Docker Learning

1. Start with project bootstrapping and local feedback loops.
2. Move into Compose watch and Bake for multi-service development.
3. Add Scout, SBOM, and provenance for software supply chain visibility.
4. Explore Build Cloud or Offload when local build time becomes the bottleneck.
5. Add Testcontainers when you want repeatable integration tests with real dependencies.

```bash
docker init
docker compose up --watch
docker buildx bake --print
docker scout recommendations myimage:latest
docker debug myimage:latest
```

### What To Keep In Mind

- `docker buildx build` remains 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`, and `docker 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
```bash
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 container
```

### Image Operations
```bash
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 image
```

### Volume Operations
```bash
docker volume ls                         # List volumes
docker volume create <volume>            # Create volume
docker volume rm <volume>                # Remove volume
docker volume inspect <volume>           # Inspect volume
```

### Network Operations
```bash
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 network
```

### Docker Compose Operations
```bash
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 service
```

### Cleanup Operations
```bash
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 networks
```

---

## Practice Tips

1. **Start with basic run commands** to understand container lifecycle
2. **Practice building images** from Dockerfiles in this directory
3. **Use `docker inspect`** to understand container and image details
4. **Always name your containers** for easier management
5. **Use `docker compose`** for multi-container applications
6. **Clean up regularly** with prune commands to save disk space
7. **Use `.dockerignore`** to exclude files from build context
8. **Tag images properly** with version numbers for better tracking
9. **Mount volumes** for persistent data and development
10. **Check logs frequently** when debugging container issues

---

## Useful One-Liners

### Stop and remove all containers
```bash
docker stop $(docker ps -q) && docker rm $(docker ps -a -q)
```

### Remove all unused resources
```bash
docker system prune -a --volumes -f
```

### Get shell in running container
```bash
docker exec -it $(docker ps -q -l) /bin/bash
```

### Remove dangling images
```bash
docker rmi $(docker images -f "dangling=true" -q)
```

### View logs from all containers
```bash
docker ps -q | xargs -L 1 docker logs
```

### Show container IP addresses
```bash
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)
```

### Monitor real-time container stats
```bash
docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"
```

---

## Popular Service Port Numbers (Essential for Docker)

### Web Servers & Proxies
```bash
- 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, 443
```

### Databases (Relational)
```bash
- 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)
```bash
- 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-local
```

### Message Queues & Event Streaming
```bash
- 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
```bash
- Redis:             6379
- Memcached:         11211
  docker run -d -p 11211:11211 memcached:1.6

- Varnish:           80, 6081 (default), 6082 (admin)
- Hazelcast:         5701-5703
```

### Search Engines
```bash
- Elasticsearch:     9200 (HTTP), 9300 (Transport)
- Solr:              8983
  docker run -d -p 8983:8983 solr:9

- Meilisearch:       7700
- Algolia:           443 (cloud-based)
- Typesense:         8108
```

### Monitoring & Observability
```bash
- 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, 8094
```

### Container Orchestration & Management
```bash
- 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
```bash
- 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, 443
```

### Development Tools
```bash
- 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/keycloak
```

### API Gateways & Service Mesh
```bash
- 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:            9001
```

### File Storage & Object Storage
```bash
- 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:              22
```

### Authentication & Security
```bash
- 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, 636
```

### Email Servers
```bash
- 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
```bash
- 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
```bash
- 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
```bash
- Metabase:          3000
  docker run -d -p 3000:3000 metabase/metabase

- Redash:            5000
- Tableau:           80, 8000
- Apache Superset:   8088
- Matomo:            80
- Plausible:         8000
```

### Game Servers
```bash
- 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
```bash
- Selenium Hub:      4444
  docker run -d -p 4444:4444 selenium/hub

- Selenium Node:     5555
- WireMock:          8080
- MockServer:        1080
- JSON Server:       3000
- Mockoon:           3000
```

### VPN & Network Tools
```bash
- 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:              22
```

### Common Docker Compose Port Mappings

```yaml
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 UI
```

### Port Conflict Resolution Tips

```bash
# 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 8080
```

### Interview Tips for Port Mapping

1. **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
   ```bash
   docker run -d -p 8080:80 nginx  # nginx uses 80 inside, 8080 on host
   ```

2. **Security Consideration**
   - Bind to localhost only for dev: `-p 127.0.0.1:5432:5432`
   - Expose to all interfaces: `-p 5432:5432` or `-p 0.0.0.0:5432:5432`
   ```bash
   # 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
   ```

3. **Multiple Port Mappings**
   ```bash
   docker run -d \
     -p 80:80 \
     -p 443:443 \
     -p 8080:8080 \
     nginx
   ```

4. **Dynamic Port Assignment**
   ```bash
   # Let Docker assign random host port
   docker run -d -p 5432 postgres
   
   # Check assigned port
   docker port <container> 5432
   ```

5. **UDP vs TCP**
   ```bash
   # 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

```dockerfile
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 check
```

---

## Docker Compose File Example

```yaml
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: bridge
```

---

## Interview Q&A Scenarios

### Scenario 1: Container keeps restarting
```bash
# 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/bash
```

### Scenario 2: Image size is too large
```bash
# 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 layer
```

### Scenario 3: Container cannot connect to network
```bash
# 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
```bash
# 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
```bash
# 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
1. **Use specific base image tags** - Not `latest`
   ```dockerfile
   FROM node:18.17-alpine  # Good
   FROM node              # Bad
   ```

2. **Use multi-stage builds** - Reduce final image size
   ```dockerfile
   FROM node:18 AS builder
   RUN npm ci
   
   FROM node:18-alpine
   COPY --from=builder /app .
   ```

3. **Order layers by change frequency** - Leverage cache
   ```dockerfile
   FROM node:18
   WORKDIR /app
   COPY package*.json ./    # Changes less
   RUN npm ci
   COPY . .                 # Changes more
   ```

4. **Combine RUN commands** - Reduce layers
   ```dockerfile
   RUN apt-get update && \
       apt-get install -y curl && \
       rm -rf /var/lib/apt/lists/*  # Clean in same layer
   ```

5. **Use .dockerignore** - Exclude unnecessary files
   ```
   node_modules
   .git
   *.md
   .env
   ```

6. **Run as non-root user** - Security
   ```dockerfile
   RUN adduser -D appuser
   USER appuser
   ```

7. **Use COPY instead of ADD** - Unless you need tar extraction
   ```dockerfile
   COPY app.js /app/     # Preferred
   ADD archive.tar /app/ # Only when needed
   ```

8. **Pin versions** - Reproducible builds
   ```dockerfile
   RUN apt-get install -y python3=3.9.2-1
   ```

### Security Best Practices
1. **Never store secrets in images**
2. **Scan images regularly** - `docker scout cves`
3. **Use official base images**
4. **Keep images updated** - Patch vulnerabilities
5. **Limit container capabilities** - `--cap-drop`
6. **Use read-only filesystem** when possible
7. **Run as non-root user**
8. **Set resource limits** - Prevent DoS
9. **Use secrets management** - Docker secrets or vault
10. **Enable Content Trust** - `DOCKER_CONTENT_TRUST=1`

### Operations Best Practices
1. **Name your containers** - Easy identification
2. **Use health checks** - Auto recovery
3. **Set restart policies** - High availability
4. **Use labels** - Better organization
5. **Configure logging** - Troubleshooting
6. **Monitor resource usage** - `docker stats`
7. **Regular cleanup** - `docker system prune`
8. **Use volumes for data** - Persistence
9. **Use networks** - Container isolation
10. **Document with labels** - Metadata

### Docker Buildx Best Practices (Modern Builds)

1. **Use buildx for all new projects** - Superior to legacy docker build
   ```bash
   docker buildx build --platform linux/amd64,linux/arm64 --push -t myapp:latest .
   ```

2. **Always specify platforms explicitly** - Don't rely on defaults
   ```bash
   # 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 .
   ```

3. **Use registry cache for CI/CD** - Faster builds
   ```bash
   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 .
   ```

4. **Use GitHub Actions cache for GH workflows**
   ```bash
   docker buildx build \
     --cache-from type=gha \
     --cache-to type=gha,mode=max \
     -t myapp:latest .
   ```

5. **Leverage buildx bake for monorepos** - Build multiple images
   ```bash
   docker buildx bake -f docker-bake.hcl --push
   ```

6. **Use secrets for sensitive data** - Never hardcode
   ```bash
   docker buildx build --secret id=token,env=GITHUB_TOKEN -t myapp:latest .
   ```

7. **Enable SBOM and provenance in production** - Security and compliance
   ```bash
   docker buildx build --sbom=true --provenance=true -t myapp:latest --push .
   ```

8. **Create dedicated builder instances** - Isolate build environments
   ```bash
   docker buildx create --name prod-builder --driver docker-container --use
   ```

9. **Use mode=max for cache** - Cache all layers
   ```bash
   --cache-to type=registry,mode=max  # Cache all layers
   --cache-to type=registry,mode=min  # Cache only final layers (default)
   ```

10. **Clean up build cache regularly** - Prevent disk bloat
    ```bash
    docker buildx prune --filter until=72h  # Remove cache older than 3 days
    ```

### Buildx Common Use Cases

**Use Case 1: Multi-Architecture Container Registry**
```bash
# 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**
```bash
# 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**
```bash
# Build for local architecture and load into Docker
docker buildx build \
  --platform linux/amd64 \
  -t myapp:dev \
  --load .
```

**Use Case 4: Export Build Artifacts**
```bash
# Export built files without creating image
docker buildx build \
  --target artifacts \
  --output type=local,dest=./dist \
  .
```

**Use Case 5: Monorepo with Bake**
```yaml
# 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"]
    }
  }
}
```
```bash
# Build all services
docker buildx bake --push
```

---

## CMD vs ENTRYPOINT - Interview Favorite!

### CMD - Default command (can be overridden)
```dockerfile
FROM ubuntu
CMD ["echo", "Hello World"]
```
```bash
docker run myimage              # Prints: Hello World
docker run myimage echo "Bye"   # Prints: Bye (CMD overridden)
```

### ENTRYPOINT - Fixed command (arguments appended)
```dockerfile
FROM ubuntu
ENTRYPOINT ["echo"]
```
```bash
docker run myimage "Hello"      # Prints: Hello
docker run myimage "Bye"        # Prints: Bye
```

### Combining ENTRYPOINT + CMD (Best Practice)
```dockerfile
FROM ubuntu
ENTRYPOINT ["python"]
CMD ["app.py"]
```
```bash
docker run myimage              # Runs: python app.py
docker run myimage test.py      # Runs: python test.py
```

### Override ENTRYPOINT at runtime
```bash
docker run --entrypoint /bin/bash myimage
```

---

## Common Pitfalls & Solutions

### Pitfall 1: Using `:latest` tag
**Problem:** Unpredictable builds, version conflicts  
**Solution:** Always use specific version tags
```dockerfile
FROM node:18.17-alpine  # Good
FROM node:latest        # Bad
```

### Pitfall 2: Running as root
**Problem:** Security vulnerability  
**Solution:** Create and use non-root user
```dockerfile
RUN adduser -D appuser
USER appuser
```

### Pitfall 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
```dockerfile
# 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
```dockerfile
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost/ || exit 1
```

### Pitfall 7: Hardcoding configuration
**Problem:** Not portable across environments  
**Solution:** Use environment variables
```dockerfile
ENV DB_HOST=localhost
ENV DB_PORT=5432
```

### Pitfall 8: No resource limits
**Problem:** One container can starve others  
**Solution:** Set memory and CPU limits
```bash
docker run -d --memory="512m" --cpus="1" myapp
```

---

## Key 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:**
```bash
# 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
```bash
docker build -t myregistry.com/myapp:1.0 . && \
docker push myregistry.com/myapp:1.0
```

### Remove all stopped containers and dangling images
```bash
docker container prune -f && docker image prune -f
```

### Complete cleanup (nuclear option)
```bash
docker stop $(docker ps -q) 2>/dev/null; \
docker system prune -a --volumes -f
```

### Run temporary testing container
```bash
docker run --rm -it -v $(pwd):/app -w /app node:18 /bin/bash
```

### Debug networking issues
```bash
docker run --rm --network container:<container_name> nicolaka/netshoot
```

### Check all container resource usage
```bash
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"
```

### Find which container is using most memory
```bash
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.db
```

---

## Production-Ready Dockerfile Example

```dockerfile
# 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
