Docker & Compose Quick Reference

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

containers

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:alpine

Open interactive bash / sh shell inside container

containers

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/sh

Stream container logs with timestamp

containers

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)

containers

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

containers

Forcefully stops (SIGKILL) and deletes the container.

$docker rm -f <container_id_or_name>

Real-time CPU and Memory usage statistics

containers

Displays a snapshot of CPU %, memory usage, network I/O, and block I/O for all running containers.

$docker stats --no-stream

Copy files between host and container

containers

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

containers

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

compose

Scaffolds networks, volumes, and starts all containers defined in docker-compose.yml in detached mode.

$docker compose up -d

Rebuild images and start without cache

compose

Rebuilds local service Dockerfiles and recreates containers even if configuration has not changed.

$docker compose up -d --build --force-recreate

Stop all services and destroy volumes

compose

Shuts down services, removes default bridge networks, deletes defined volumes (-v), and cleans up unreferenced containers.

$docker compose down -v --remove-orphans

Stream live logs for specific service

compose

Streams recent stdout and stderr output exclusively from the 'api' service container.

$docker compose logs -f --tail 50 api

Execute one-off command in running compose service

compose

Executes database migration or diagnostic script inside the running 'api' service instance.

$docker compose exec api npm run db:migrate

Restart a single compose service

compose

Gracefully restarts only the 'redis' container without interrupting other linked services.

$docker compose restart redis

Validate and view rendered compose YAML

compose

Parses environment variables and validates docker-compose.yml syntax, printing the final resolved configuration.

Build Docker image with tag and build context

images

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

images

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)

images

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

images

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

images

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.gz

Load image from tarball archive

images

Restores an exported Docker image tarball into the local image cache.

$docker load -i my-app.tar.gz

Run container with persistent named volume

volumes

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-alpine

Mount host directory with read-only flag (:ro)

volumes

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:alpine

List all volumes and remove dangling storage

volumes

Lists all local Docker volumes and purges orphaned volumes not linked to any active container.

$docker volume ls && docker volume prune -f

Create isolated bridge network for inter-container DNS

network

Enables containers on this network to resolve each other by container name rather than IP address.

$docker network create --driver bridge backend-net

Connect running container to another network

network

Attaches a running container to an additional Docker network without requiring a restart.

$docker network connect backend-net redis-cache

Inspect network IP range and connected endpoints

network

Outputs JSON metadata showing gateway, subnet (e.g. 172.20.0.0/16), and attached container MAC/IP addresses.

$docker network inspect backend-net

Complete system cleanup (containers, images, build cache)

cleanup

The ultimate Docker cleanup: deletes all stopped containers, unused networks, unreferenced images, and volumes.

$docker system prune -a --volumes -f

Inspect Docker disk usage breakdown

cleanup

Displays disk space occupied by images, containers, local volumes, and BuildKit build cache with reclaimable percentages.

$docker system df -v

Clear BuildKit compilation cache

cleanup

Purges cached layer stages produced by 'docker buildx' to free up gigabytes of local storage.

$docker builder prune --all -f

Frequently 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.

Explore Other Developer Cheat Sheets