Docker Commands Cheat Sheet
Essential Docker CLI and Docker Compose commands with syntax explanations, port mapping flags, volume persistence recipes, and complete system cleanup.
Run detached container with port mapping
Starts an Nginx container in the background (-d), forwards host port 8080 to container port 80, and names the container 'my-web'.
docker run -d -p 8080:80 --name my-web nginx:alpineOpen interactive bash / sh shell inside container
Allocates a pseudo-TTY with stdin (-it) inside a running container. Use /bin/bash if installed, otherwise /bin/sh.
docker exec -it <container_id_or_name> /bin/shStream container logs with timestamp
Follows logs live (-f), displays ISO timestamps (-t), and starts from the last 100 lines.
docker logs -f -t --tail 100 <container_id_or_name>List active containers vs all (including stopped)
Lists all containers with formatted columns for ID, image tag, uptime status, and assigned name.
docker ps -a --format 'table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}'Stop and remove container in one command
Forcefully stops (SIGKILL) and deletes the container.
docker rm -f <container_id_or_name>Real-time CPU and Memory usage statistics
Displays a snapshot of CPU %, memory usage, network I/O, and block I/O for all running containers.
docker stats --no-streamCopy files between host and container
Copies a local file into a container directory, or extracts files out of a container to the host.
docker cp ./schema.sql <container_name>:/docker-entrypoint-initdb.d/Inspect container IP address & environment variables
Extracts specific JSON configuration fields from container metadata using Go templates.
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_id>Start all services in background
Scaffolds networks, volumes, and starts all containers defined in docker-compose.yml in detached mode.
docker compose up -dRebuild images and start without cache
Rebuilds local service Dockerfiles and recreates containers even if configuration has not changed.
docker compose up -d --build --force-recreateStop all services and destroy volumes
Shuts down services, removes default bridge networks, deletes defined volumes (-v), and cleans up unreferenced containers.
docker compose down -v --remove-orphansStream live logs for specific service
Streams recent stdout and stderr output exclusively from the 'api' service container.
docker compose logs -f --tail 50 apiExecute one-off command in running compose service
Executes database migration or diagnostic script inside the running 'api' service instance.
docker compose exec api npm run db:migrateRestart a single compose service
Gracefully restarts only the 'redis' container without interrupting other linked services.
docker compose restart redisValidate and view rendered compose YAML
Parses environment variables and validates docker-compose.yml syntax, printing the final resolved configuration.
docker compose configBuild Docker image with tag and build context
Builds a Docker image using the Dockerfile in the current directory (.) and tags it 'my-app:v1.0.0'.
docker build -t my-app:v1.0.0 -f Dockerfile .Build specific target stage in multi-stage Dockerfile
Halts build at the specified stage ('builder'), useful for extracting test artifacts without production minimization.
docker build --target builder -t my-app:dev .Pass build-time variables (ARG)
Supplies parameters defined with ARG in Dockerfile during image compilation.
docker build --build-arg NODE_ENV=production -t app:prod .View image layers and size breakdown
Inspects how each Dockerfile instruction contributes to the final image disk footprint.
docker history --human --format 'table {{.CreatedBy}}\t{{.Size}}' <image_tag>Export image to compressed tarball archive
Packages an image and its layer history into a portable gzip archive for air-gapped server deployments.
docker save my-app:latest | gzip > my-app.tar.gzLoad image from tarball archive
Restores an exported Docker image tarball into the local image cache.
docker load -i my-app.tar.gzRun container with persistent named volume
Mounts the managed volume 'pgdata' to store database state across container rebuilds.
docker run -d -v pgdata:/var/lib/postgresql/data -p 5432:5432 postgres:16-alpineMount host directory with read-only flag (:ro)
Mounts the local ./config directory into the container with read-only permissions to prevent accidental tampering.
docker run -d -v $(pwd)/config:/etc/nginx/conf.d:ro -p 80:80 nginx:alpineList all volumes and remove dangling storage
Lists all local Docker volumes and purges orphaned volumes not linked to any active container.
docker volume ls && docker volume prune -fCreate isolated bridge network for inter-container DNS
Enables containers on this network to resolve each other by container name rather than IP address.
docker network create --driver bridge backend-netConnect running container to another network
Attaches a running container to an additional Docker network without requiring a restart.
docker network connect backend-net redis-cacheInspect network IP range and connected endpoints
Outputs JSON metadata showing gateway, subnet (e.g. 172.20.0.0/16), and attached container MAC/IP addresses.
docker network inspect backend-netComplete system cleanup (containers, images, build cache)
The ultimate Docker cleanup: deletes all stopped containers, unused networks, unreferenced images, and volumes.
docker system prune -a --volumes -fInspect Docker disk usage breakdown
Displays disk space occupied by images, containers, local volumes, and BuildKit build cache with reclaimable percentages.
docker system df -vClear BuildKit compilation cache
Purges cached layer stages produced by 'docker buildx' to free up gigabytes of local storage.
docker builder prune --all -fFrequently Asked Questions
How do I run a Docker container in the background with port forwarding?
Use 'docker run -d -p 8080:80 --name my-container <image>'. The '-d' flag runs the container in detached mode, and '-p 8080:80' maps host port 8080 to internal container port 80.
How do I completely clean up unused Docker containers, images, and volumes?
Run 'docker system prune -a --volumes -f'. This removes all stopped containers, all networks not used by at least one container, all dangling and unused images, and all unused volumes to reclaim disk space.
How do I open an interactive terminal shell inside a running Docker container?
Execute 'docker exec -it <container_id_or_name> /bin/sh' or 'docker exec -it <container_id_or_name> /bin/bash'. The '-i' (interactive) and '-t' (pseudo-TTY) flags keep stdin open.
What is the difference between 'docker compose up' and 'docker compose up -d'?
'docker compose up' attaches to stdout/stderr of all containers in the current terminal session, meaning pressing Ctrl+C will send SIGTERM and stop all services. 'docker compose up -d' runs containers in the background, freeing your terminal.
How do I inspect real-time CPU and memory usage of Docker containers?
Run 'docker stats'. It outputs a dynamic live stream displaying CPU percentage, memory usage against container limits, network I/O, and block I/O per container.