Development Cheat Sheet
Docker Cheat Sheet
A practical reference for essential Docker commands, images, containers, Dockerfiles, volumes, networks, Compose workflows, debugging, and safe cleanup.
- Copy-ready commands
- Docker Compose workflows
- Cleanup guidance
- Practical troubleshooting
Find a command
Search the Docker Cheat Sheet
Search by command, task, resource type, workflow, or Docker concept.
Matching sections will remain visible while unrelated sections are hidden.
Essential commands
Docker Quick Reference
Use this command list for common image, container, volume, network, and Compose tasks. Replace placeholder values before running a command.
| Task | Command | What it does | Copy |
|---|---|---|---|
| System | docker version |
Shows Docker client and server version information. | |
| System | docker info |
Displays system-wide Docker configuration and status. | |
| Image | docker pull <image> |
Downloads an image from a registry. | |
| Image | docker image ls |
Lists images stored locally. | |
| Build | docker build -t <name> . |
Builds and tags an image from the current directory. | |
| Run | docker run -d --name <name> -p 8080:80 <image> |
Starts a named background container and publishes a port. | |
| Inspect | docker ps |
Lists currently running containers. | |
| Inspect | docker ps -a |
Lists running and stopped containers. | |
| Logs | docker logs -f <container> |
Streams logs from a container. | |
| Execute | docker exec -it <container> sh |
Opens an interactive shell in a running container. | |
| Manage | docker stop <container> |
Requests a graceful stop of a running container. | |
| Manage | docker start <container> |
Starts an existing stopped container. | |
| Remove | docker rm <container> |
Removes a stopped container. | |
| Remove | docker rmi <image> |
Removes a local image when it is no longer in use. | |
| Storage | docker volume ls |
Lists Docker-managed volumes. | |
| Network | docker network ls |
Lists Docker networks. | |
| Compose | docker compose up -d |
Creates and starts the Compose application in the background. | |
| Compose | docker compose down |
Stops and removes Compose containers and default networks. |
Core architecture
How Docker Works
Docker builds immutable images from instructions and starts containers as isolated processes based on those images. The Docker client sends commands to the Docker daemon, which manages the resources.
| Component | Purpose | Common interaction |
|---|---|---|
| Docker client | Accepts commands and communicates with the Docker daemon. | docker build, docker run |
| Docker daemon | Builds images and manages containers, networks, and volumes. | docker info |
| Image | Read-only packaged filesystem and metadata used to create containers. | docker image ls |
| Container | A runnable instance of an image with its own writable layer. | docker ps |
| Registry | Stores and distributes tagged container images. | docker pull, docker push |
| Volume | Stores persistent data independently of a container lifecycle. | docker volume ls |
| Network | Connects containers to each other and to external services. | docker network ls |
Basic image-to-container workflow
Build → run → inspect → stop
docker build -t example-app .
docker run -d --name example-container example-app
docker ps
docker stop example-container
Verify the environment
Setup and System Information
Verify the Docker client, daemon, Compose plugin, active context, and available system resources before building or running containers.
Verify Docker and Compose
Check client, server, and Compose versions
docker --version
docker version
docker compose version
docker info
System information commands
| Command | What it shows | Useful for |
|---|---|---|
docker --version |
The installed Docker CLI version. | Confirming that the client command is available. |
docker version |
Client and Docker Engine component versions. | Checking whether the client can reach the daemon. |
docker compose version |
The installed Docker Compose plugin version. | Confirming support for modern docker compose commands. |
docker info |
Containers, images, storage driver, runtimes, and system details. | Diagnosing installation and daemon configuration. |
docker context show |
The currently active Docker context. | Confirming which daemon receives commands. |
docker context ls |
Available contexts and their endpoints. | Working with local and remote Docker environments. |
docker context use <context> |
Switches the active Docker context. | Changing the target daemon for future commands. |
docker system df |
Disk usage by images, containers, volumes, and build cache. | Finding Docker resources consuming storage. |
docker help |
Top-level Docker CLI help. | Discovering command groups and available options. |
docker <command> --help |
Help for one command or command group. | Checking syntax supported by the installed version. |
Reusable container packages
Docker Images
Images are read-only packages containing an application filesystem, runtime configuration, and metadata. Containers are created from locally available or registry-hosted images.
Download and inspect an image
Pull a versioned image and inspect it
docker pull nginx:alpine
docker image ls nginx
docker image inspect nginx:alpine
docker image history nginx:alpine
Image commands
| Command | Purpose | Important detail |
|---|---|---|
docker image pull <image> |
Downloads an image from a registry. | If no tag is supplied, Docker uses latest. |
docker image ls |
Lists images stored locally. | Also available through the shorthand docker images. |
docker image ls <repository>:<tag> |
Lists images matching an exact repository and tag. | Useful when several versions are stored locally. |
docker image inspect <image> |
Displays detailed image metadata as JSON. | Includes configuration, architecture, layers, and creation data. |
docker image history <image> |
Shows the history and size of image layers. | Useful when investigating unexpectedly large images. |
docker image tag <source> <target> |
Creates another tag referring to an image. | Does not create a duplicate image layer set. |
docker image rm <image> |
Removes or untags a local image. | Does not remove the image from a registry. |
docker image prune |
Removes dangling images. | Docker asks for confirmation unless -f is used. |
docker image prune -a |
Removes images not associated with at least one container. | Review the affected images before confirming. |
Export and import an image archive
Save an image and load it on another Docker host
docker image save -o example-app.tar example-app:1.0
docker image load -i example-app.tar
Container lifecycle
Docker Containers
A container is a created, running, paused, or stopped instance of an image. Its configuration is established when the container is created and reused when that container is restarted.
Basic container lifecycle
Create, start, inspect, stop, and remove
docker create --name web-server nginx:alpine
docker start web-server
docker inspect web-server
docker stop web-server
docker rm web-server
Core container commands
| Command | Purpose | Important detail |
|---|---|---|
docker create <image> |
Creates a container without starting it. | The container enters the created state. |
docker run <image> |
Creates and starts a new container. | Pulls the image when required by the configured pull policy. |
docker start <container> |
Starts an existing stopped or created container. | Reuses its previous container configuration. |
docker stop <container> |
Requests a graceful stop. | The main process receives a termination signal before forced shutdown. |
docker restart <container> |
Stops and starts a container. | Useful after configuration used by the application changes. |
docker ps |
Lists running containers. | Use -a to include stopped containers. |
docker inspect <container> |
Displays detailed container configuration and state. | Returns low-level information as JSON. |
docker rename <old> <new> |
Renames an existing container. | The container ID remains unchanged. |
docker rm <container> |
Removes a stopped container. | The underlying image remains available. |
Common container states
| State | Meaning |
|---|---|
| created | The container exists but has never started. |
| running | The container’s main process is active. |
| paused | The container’s processes are temporarily suspended. |
| restarting | The container is restarting according to its restart policy. |
| exited | The main process finished or the container was stopped. |
| dead | The container could not be fully removed and cannot restart. |
Define reproducible images
Dockerfile Instructions
A Dockerfile contains ordered instructions for building an image. Arrange stable dependency steps before frequently changing application files to improve build-cache reuse.
Example application Dockerfile
Python application with a non-root runtime user
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd --create-home appuser
USER appuser
ENV PORT=8000
EXPOSE 8000
CMD ["python", "app.py"]
Common Dockerfile instructions
| Instruction | Purpose | Example |
|---|---|---|
FROM |
Defines the base image and starts a build stage. | FROM python:3.13-slim |
WORKDIR |
Sets the working directory for later instructions. | WORKDIR /app |
COPY |
Copies files or directories from the build context. | COPY . . |
ADD |
Adds files with extra features such as archive extraction. | ADD archive.tar.gz /app/ |
RUN |
Executes a build command and creates a new image layer. | RUN apt-get update |
ENV |
Sets an environment variable persisted in the image. | ENV PORT=8000 |
ARG |
Defines a variable available during the build. | ARG APP_VERSION=1.0 |
EXPOSE |
Documents the network port the application expects to use. | EXPOSE 8000 |
USER |
Sets the default user for later build steps and runtime. | USER appuser |
CMD |
Provides the default command or arguments at runtime. | CMD ["python", "app.py"] |
ENTRYPOINT |
Configures the container’s main executable. | ENTRYPOINT ["python"] |
HEALTHCHECK |
Defines how Docker tests container health. | HEALTHCHECK CMD curl -f http://localhost/ || exit 1 |
VOLUME |
Declares a mount point intended for externally managed data. | VOLUME ["/data"] |
LABEL |
Adds descriptive metadata to the image. | LABEL org.opencontainers.image.version="1.0" |
Create application images
Build Images
Docker sends a build context to the builder, processes the selected Dockerfile, reuses valid cached layers, and exports the resulting image or other requested output.
Build and verify a tagged image
Build from the current directory
docker build --pull -t example-app:1.0 .
docker image ls example-app
docker image inspect example-app:1.0
Build options
| Command or option | Purpose | Important detail |
|---|---|---|
docker build . |
Builds using the current directory as the build context. | Uses Dockerfile in the context root by default. |
-t <name>:<tag> |
Assigns a repository name and tag to the result. | Use explicit version tags for reproducible workflows. |
-f <path> |
Selects a Dockerfile at another path. | The final positional argument still defines the build context. |
--pull |
Attempts to pull a newer version of referenced base images. | Useful when rebuilding against updated base images. |
--no-cache |
Prevents reuse of cached build layers. | Does not by itself guarantee a newly pulled base image. |
--build-arg <key>=<value> |
Supplies a value for a Dockerfile ARG. |
Do not use build arguments for secrets. |
--target <stage> |
Builds to a named stage in a multi-stage Dockerfile. | Useful for development, testing, or debugging stages. |
--platform <platform> |
Sets the target platform for the build result. | Example: linux/amd64 or linux/arm64. |
--progress=plain |
Displays plain-text build progress. | Helpful when investigating failed build steps. |
--secret id=<id>,src=<file> |
Provides a secret to supported BuildKit mount instructions. | Avoids copying the secret into an image layer. |
Example .dockerignore file
Exclude unnecessary and sensitive files from the build context
.git
.gitignore
node_modules
.venv
__pycache__
.env
*.log
dist
build
Create and start containers
Run Containers
docker run creates a new container from an image and
starts its main process. Runtime flags define its name, ports,
environment, storage, network, resource limits, and lifecycle policy.
Run a background web container
Named container with port and restart policy
docker run -d \
--name web-server \
--restart unless-stopped \
-p 8080:80 \
nginx:alpine
Common docker run options
| Option | Purpose | Example |
|---|---|---|
--name |
Assigns a readable container name. | --name web-server |
-d |
Runs the container in detached mode. | docker run -d nginx |
-it |
Keeps input open and allocates a terminal. | docker run -it alpine sh |
--rm |
Automatically removes the container when it exits. | docker run --rm alpine echo hello |
-p |
Publishes a container port on the host. | -p 8080:80 |
-e |
Sets a container environment variable. | -e APP_ENV=production |
--env-file |
Loads environment variables from a file. | --env-file .env |
--mount |
Attaches a volume, bind mount, or temporary filesystem. | --mount source=data,target=/data |
--network |
Connects the container to a selected network. | --network app-network |
--restart |
Defines when Docker should restart the container. | --restart unless-stopped |
--memory |
Sets a container memory limit. | --memory 512m |
--cpus |
Limits available CPU resources. | --cpus 1.5 |
--user |
Runs the main process as a selected user or UID. | --user 1000:1000 |
--read-only |
Makes the container root filesystem read-only. | docker run --read-only <image> |
--pull |
Controls when Docker attempts to pull the image. | --pull always |
Control container state
Manage Containers
List, filter, start, stop, restart, pause, update, rename, and remove existing containers without rebuilding their underlying images.
Inspect and restart an existing container
Review state, restart, and follow logs
docker ps -a
docker restart <container>
docker logs -f --tail 100 <container>
Listing and filtering
| Command | Result |
|---|---|
docker ps |
Lists running containers. |
docker ps -a |
Lists running and stopped containers. |
docker ps -q |
Prints only running container IDs. |
docker ps --filter status=exited |
Lists containers whose main process has exited. |
docker ps --filter name=<text> |
Lists containers with names matching the supplied text. |
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" |
Displays selected fields in a custom table. |
Container-management commands
| Command | Purpose | Important detail |
|---|---|---|
docker start <container> |
Starts a stopped or created container. | Add -a to attach its output. |
docker stop <container> |
Requests a graceful stop. | Use -t to configure the timeout. |
docker restart <container> |
Stops and starts the selected container. | Preserves the container’s writable layer and configuration. |
docker pause <container> |
Suspends the container’s processes. | The container remains present and paused. |
docker unpause <container> |
Resumes a paused container. | Processes continue from their suspended state. |
docker kill <container> |
Sends a signal to the container’s main process. | The default signal immediately terminates the process. |
docker wait <container> |
Waits for a container to stop and prints its exit code. | Useful in scripts and automated workflows. |
docker rename <old> <new> |
Changes the container name. | The container ID remains unchanged. |
docker update --restart unless-stopped <container> |
Changes the restart policy of an existing container. | The new policy takes effect immediately. |
docker rm <container> |
Removes a stopped container. | Named volumes are not removed automatically. |
docker rm -f <container> |
Force-removes a running container. | The main process is forcibly terminated. |
docker container prune |
Removes all stopped containers after confirmation. | Review stopped containers before continuing. |
Access container services
Ports and Publishing
Publishing creates a forwarding rule from a host address and port to a port inside the container. Declaring or exposing a container port alone does not make it accessible from the host.
Publish a web service only on localhost
Host port 8080 → container port 80
docker run -d \
--name local-web \
-p 127.0.0.1:8080:80 \
nginx:alpine
docker port local-web
Port-publishing syntax
| Syntax | Result | Example |
|---|---|---|
-p HOST:CONTAINER |
Publishes a fixed host port to a container port. | -p 8080:80 |
-p IP:HOST:CONTAINER |
Binds the published port to a selected host address. | -p 127.0.0.1:8080:80 |
-p CONTAINER |
Lets Docker select an available host port. | -p 80 |
-p HOST:CONTAINER/udp |
Publishes a UDP port instead of the default TCP protocol. | -p 5353:53/udp |
-p HOST:CONTAINER/tcp |
Explicitly publishes a TCP port. | -p 8080:80/tcp |
-P |
Publishes all ports declared by the image to available host ports. | docker run -P <image> |
Port inspection commands
| Command | Purpose |
|---|---|
docker port <container> |
Lists every published port mapping for the container. |
docker port <container> 80/tcp |
Shows the host mapping for one container port and protocol. |
docker ps --format "table {{.Names}}\t{{.Ports}}" |
Displays container names and published ports in a compact table. |
docker inspect <container> |
Shows detailed network and port configuration as JSON. |
Persist and share data
Docker Volumes
Volumes store data outside a container’s writable layer, allowing that data to survive container removal and be reused by replacement containers.
Create and mount a named volume
Persistent data mounted at /data
docker volume create app-data
docker run -d \
--name data-container \
--mount type=volume,source=app-data,target=/data \
alpine sleep infinity
docker volume inspect app-data
Storage mount types
| Mount type | Managed by | Best for | Example |
|---|---|---|---|
| Named volume | Docker | Persistent application and database data. | source=app-data,target=/data |
| Anonymous volume | Docker | Temporary persistent data without a human-readable name. | target=/data |
| Bind mount | Host filesystem | Sharing source code or configuration with the host. | source=/host/path,target=/app |
| tmpfs mount | Host memory | Sensitive or temporary non-persistent runtime data. | type=tmpfs,target=/tmp |
Volume commands
| Command | Purpose | Important detail |
|---|---|---|
docker volume create <volume> |
Creates a named volume. | Docker can also create it automatically during container creation. |
docker volume ls |
Lists Docker-managed volumes. | Use filters to narrow long lists. |
docker volume inspect <volume> |
Shows driver, mount point, labels, and options. | Returns detailed information as JSON. |
--mount type=volume,source=<volume>,target=<path> |
Mounts a named volume into a container. | The explicit --mount syntax is generally preferred. |
-v <volume>:<path> |
Mounts a named volume using short syntax. | Example: -v app-data:/data. |
--mount type=volume,source=<volume>,target=<path>,readonly |
Mounts a volume as read-only. | The container can read but cannot modify mounted content. |
docker volume rm <volume> |
Removes an unused volume. | Docker refuses while the volume is in use. |
docker volume prune |
Removes unused local volumes after confirmation. | Review important data before continuing. |
Connect isolated services
Docker Networks
Docker networks connect containers to each other and to external services. Containers on a user-defined bridge network can normally communicate using container names through Docker’s embedded DNS.
Create a network and test container-name resolution
Connect two containers through a user-defined bridge
docker network create app-network
docker run -d \
--name database \
--network app-network \
redis:alpine
docker run --rm \
--network app-network \
alpine ping -c 3 database
Network drivers
| Driver | Purpose | Typical use |
|---|---|---|
bridge |
Connects containers on one Docker host. | Standard single-host applications and development. |
host |
Uses the host’s networking directly. | Special cases requiring reduced network isolation. |
none |
Creates only a loopback interface for the container. | Containers that require complete network isolation. |
overlay |
Connects services across multiple Docker daemons. | Docker Swarm and multi-host communication. |
macvlan |
Assigns container interfaces their own MAC addresses. | Integration with networks expecting physical-style devices. |
ipvlan |
Provides controlled Layer 2 or Layer 3 IP networking. | Advanced underlay-network integration. |
Network-management commands
| Command | Purpose | Important detail |
|---|---|---|
docker network ls |
Lists available Docker networks. | Includes built-in and user-defined networks. |
docker network create <network> |
Creates a user-defined bridge network. | Use --driver to select another driver. |
docker network inspect <network> |
Displays configuration and connected containers. | Useful for checking subnets and container addresses. |
docker network connect <network> <container> |
Connects an existing container to a network. | A container can connect to multiple networks. |
docker network disconnect <network> <container> |
Disconnects a container from a network. | Active connections using that network may fail. |
docker network rm <network> |
Removes an unused user-defined network. | Connected containers must be disconnected first. |
docker network prune |
Removes unused custom networks after confirmation. | Built-in networks are not removed. |
Configure container behavior
Environment Variables
Environment variables provide runtime configuration without rebuilding an image. They can come from Dockerfile defaults, command-line flags, environment files, or Compose configuration.
Run a container with an environment file
Example app.env file and runtime command
# app.env
APP_ENV=development
LOG_LEVEL=info
PORT=8000
# Run the container
docker run --rm \
--env-file app.env \
-e LOG_LEVEL=debug \
example-app:1.0
Environment-variable methods
| Method | Purpose | Example |
|---|---|---|
ENV in Dockerfile |
Defines a default persisted in the image configuration. | ENV APP_ENV=production |
-e KEY=value |
Sets or overrides one variable when creating the container. | -e APP_ENV=development |
-e KEY |
Passes a variable from the current host environment. | -e DEBUG |
--env-file <file> |
Loads multiple variables from a file. | --env-file app.env |
environment: in Compose |
Defines variables directly for a Compose service. | APP_ENV: production |
env_file: in Compose |
Loads service variables from one or more files. | env_file: app.env |
Inspect runtime variables
| Command | Result |
|---|---|
docker exec <container> env |
Prints the environment visible to a process in a running container. |
docker exec <container> printenv <key> |
Prints one selected variable when printenv is available. |
docker inspect <container> |
Includes configured environment values in container metadata. |
Observe running workloads
Logs, Stats, and Inspection
Combine logs, resource metrics, process listings, filesystem changes, and low-level metadata to understand container behavior without modifying the container.
Quick container diagnosis
Review state, logs, processes, and resource usage
docker inspect <container>
docker logs --tail 100 <container>
docker top <container>
docker stats --no-stream <container>
Log commands
| Command | Result |
|---|---|
docker logs <container> |
Displays logs captured for the container. |
docker logs -f <container> |
Follows new log output until interrupted. |
docker logs --tail 100 <container> |
Displays the latest 100 log lines. |
docker logs --since 30m <container> |
Shows logs produced during the latest 30 minutes. |
docker logs --timestamps <container> |
Adds timestamps to displayed log lines. |
docker logs -f --tail 50 <container> |
Shows recent lines and continues following new output. |
Inspection and monitoring commands
| Command | Purpose | Important detail |
|---|---|---|
docker inspect <container> |
Displays detailed configuration and state as JSON. | Includes mounts, networking, environment, and process state. |
docker inspect --format "{{.State.Status}}" <container> |
Extracts one selected field using a format template. | Useful in scripts and targeted diagnostics. |
docker stats |
Streams CPU, memory, network, and block-I/O metrics. | Press Ctrl+C to stop the stream. |
docker stats --no-stream <container> |
Prints one resource-usage snapshot. | Useful for reports and scripts. |
docker top <container> |
Displays processes running inside the container. | Does not require a shell inside the image. |
docker diff <container> |
Shows filesystem changes in the writable container layer. | Marks paths as added, changed, or deleted. |
docker events |
Streams real-time events from the Docker daemon. | Use filters to focus on selected resources or event types. |
docker port <container> |
Lists published container port mappings. | Useful when Docker selected an ephemeral host port. |
Work with container processes and files
Execute and Copy Files
Use docker exec to start an additional process in a
running container and docker cp to transfer files between
the local filesystem and a running or stopped container.
Open an interactive container shell
Use sh when a minimal image does not include bash
docker exec -it <container> sh
Execute-command options
| Command | Purpose | Important detail |
|---|---|---|
docker exec <container> <command> |
Runs a new command in a running container. | The command ends independently of the main container process. |
docker exec -it <container> sh |
Starts an interactive shell session. | Minimal images may provide sh but not bash. |
docker exec -d <container> <command> |
Runs an additional command in the background. | The process runs only while the container remains running. |
docker exec -u <user> <container> <command> |
Runs the command as a selected user or UID. | Avoid using root unless the task requires it. |
docker exec -w <path> <container> <command> |
Sets the working directory for the new process. | The path must exist inside the container. |
docker exec -e KEY=value <container> <command> |
Sets a variable for the executed process. | Does not change the original container environment. |
docker exec <container> sh -c "cmd1 && cmd2" |
Runs a chained shell expression. | The shell interprets operators such as &&. |
Copy files between host and container
Copy a file into a container and retrieve a log directory
docker cp ./config.json <container>:/app/config.json
docker cp <container>:/app/logs ./container-logs
| Command | Purpose |
|---|---|
docker cp <local-path> <container>:<path> |
Copies a local file or directory into a container. |
docker cp <container>:<path> <local-path> |
Copies a container file or directory to the local filesystem. |
docker attach <container> |
Attaches the terminal to the container’s main process streams. |
Manage multi-container applications
Docker Compose
Docker Compose defines services, networks, volumes, and runtime
configuration in a YAML file, then manages the application as one
project with docker compose.
Example compose.yml
Web service with a healthy PostgreSQL dependency
services:
web:
build: .
ports:
- "127.0.0.1:8080:8000"
environment:
APP_ENV: development
DATABASE_HOST: db
depends_on:
db:
condition: service_healthy
db:
image: postgres:17-alpine
environment:
POSTGRES_DB: app
POSTGRES_USER: app
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD}
volumes:
- db-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d app"]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
Common Compose commands
| Command | Purpose | Important detail |
|---|---|---|
docker compose config |
Parses and renders the resolved Compose configuration. | Use before starting the application to catch configuration errors. |
docker compose up |
Creates, starts, and attaches to service containers. | Stopping the foreground command stops the containers. |
docker compose up -d |
Starts the application in the background. | Use logs and ps to monitor it afterward. |
docker compose up -d --build |
Builds required images and starts the application. | Useful after changing source code or a Dockerfile. |
docker compose ps |
Lists project containers, status, and ports. | Add --all to include stopped services. |
docker compose logs -f |
Follows aggregated service logs. | Add a service name to limit the output. |
docker compose exec <service> <command> |
Runs a command in a running service container. | An interactive terminal is allocated by default. |
docker compose run --rm <service> <command> |
Runs a one-off command in a new service container. | The temporary container is removed after it exits. |
docker compose build |
Builds or rebuilds service images. | Does not start the service containers. |
docker compose pull |
Pulls service images from their registries. | Does not automatically start the application. |
docker compose stop |
Stops service containers without removing them. | They can be resumed with docker compose start. |
docker compose restart |
Restarts service containers. | Does not apply changes made to Compose configuration. |
docker compose down |
Stops and removes project containers and default networks. | Named volumes are retained by default. |
docker compose down -v |
Also removes declared named and attached anonymous volumes. | Persistent application data may be deleted. |
Typical Compose workflow
Validate, start, inspect, and stop
docker compose config
docker compose up -d --build
docker compose ps
docker compose logs -f
docker compose down
Distribute container images
Registries and Image Sharing
Tag, authenticate, push, and pull Docker images through Docker Hub or another container registry.
Image reference format
[HOST[:PORT]/]NAMESPACE/REPOSITORY[:TAG]
Registry commands
| Task | Command | What it does | Copy |
|---|---|---|---|
| Login |
docker login
|
Authenticates with Docker Hub using the default login flow. | |
| Login |
docker login registry.example.com
|
Authenticates with a specified private or self-hosted registry. | |
| Secure login |
printf '%s' "$REGISTRY_TOKEN" | docker login registry.example.com --username "$REGISTRY_USER" --password-stdin
|
Passes a token through standard input for non-interactive login. | |
| Tag |
docker tag example-app:1.0 username/example-app:1.0
|
Creates a registry-ready tag for an existing local image. | |
| Tag |
docker tag example-app:1.0 registry.example.com/team/example-app:1.0
|
Tags an image for a custom registry and namespace. | |
| Push |
docker push username/example-app:1.0
|
Uploads one tagged image to its configured registry. | |
| Push |
docker push --all-tags username/example-app
|
Pushes every local tag belonging to the repository. | |
| Pull |
docker pull username/example-app:1.0
|
Downloads the specified image and tag from its registry. | |
| Inspect |
docker image inspect username/example-app:1.0
|
Displays image metadata, configuration, and repository digests. | |
| Logout |
docker logout registry.example.com
|
Removes locally stored credentials for the specified registry. |
Build and publish an image
docker build -t example-app:1.0 .
docker login
docker tag example-app:1.0 username/example-app:1.0
docker push username/example-app:1.0
docker pull username/example-app:1.0
Reclaim disk space
Cleanup Commands
Inspect Docker disk usage and safely remove stopped containers, unused images, networks, volumes, and build cache.
Inspect disk usage
docker system df
docker system df -v
Cleanup command reference
| Resource | Command | What it removes | Copy |
|---|---|---|---|
| Containers |
docker container prune
|
Removes all stopped containers after confirmation. | |
| Images |
docker image prune
|
Removes dangling images that are not associated with a tag. | |
| Images |
docker image prune -a
|
Removes every image not referenced by a container. | |
| Networks |
docker network prune
|
Removes custom networks not used by any container. | |
| Volumes |
docker volume prune
|
Removes unused anonymous local volumes. | |
| Volumes |
docker volume prune -a
|
Removes unused anonymous and named local volumes. | |
| Build cache |
docker builder prune
|
Removes unused build cache after confirmation. | |
| System |
docker system prune
|
Removes stopped containers, unused networks, dangling images, and unused build cache. | |
| System |
docker system prune -a
|
Also removes unused images instead of limiting cleanup to dangling images. | |
| System |
docker system prune -a --volumes
|
Performs broad cleanup and also removes unused anonymous volumes. |
Remove older unused resources
docker container prune --filter "until=24h"
docker image prune -a --filter "until=24h"
docker network prune --filter "until=24h"
Diagnose common problems
Docker Troubleshooting
Follow a repeatable diagnostic process for failed containers, unavailable ports, unhealthy services, build errors, resource problems, and Docker daemon issues.
Start with these checks
docker ps -a
docker logs --tail 100 <container>
docker inspect <container>
docker stats --no-stream
docker system df
Diagnostic commands
| Check | Command | What to look for | Copy |
|---|---|---|---|
| Status |
docker ps -a
|
Exited, restarting, unhealthy, or unexpectedly stopped containers. | |
| Logs |
docker logs --tail 100 <container>
|
Startup errors, missing files, connection failures, and crashes. | |
| Live logs |
docker logs -f --since 10m <container>
|
New log messages generated while reproducing the problem. | |
| Inspect |
docker inspect <container>
|
Environment variables, mounts, networks, ports, state, and health. | |
| Exit code |
docker inspect --format='{{.State.ExitCode}}' <container>
|
The exit status returned by the container process. | |
| Health |
docker inspect --format='{{json .State.Health}}' <container>
|
Health-check status, recent results, output, and failures. | |
| Ports |
docker port <container>
|
Published container ports and their mapped host addresses. | |
| Resources |
docker stats --no-stream
|
High CPU, memory consumption, network traffic, or block I/O. | |
| Events |
docker events --since 10m
|
Recent container starts, stops, kills, restarts, and network events. | |
| Daemon |
docker info
|
Docker daemon availability, storage driver, runtime, and warnings. |
Common problems and fixes
| Symptom | Likely cause | Recommended check |
|---|---|---|
| Container exits immediately | The main process completed, crashed, or received invalid configuration. |
Run docker logs <container> and inspect the exit
code.
|
| Container keeps restarting | Application failure combined with an automatic restart policy. |
Inspect logs and check
.HostConfig.RestartPolicy.
|
| Application is unreachable | Missing port publishing, incorrect host port, or the application is listening only on localhost inside the container. |
Check docker port, the run command, and the
application bind address.
|
| Container cannot reach another container | The containers use different networks or an incorrect service name. | Inspect both containers and verify their Docker networks. |
| Permission denied on mounted files | Host permissions or container user IDs do not match. | Inspect the mount, container user, file owner, and permission bits. |
| Build uses outdated files | A cached build layer was reused. |
Review the build context and test with
docker build --no-cache ..
|
| No space left on device | Images, stopped containers, volumes, logs, or build cache use too much disk space. |
Run docker system df -v before carefully pruning
unused resources.
|
| Cannot connect to the Docker daemon | The daemon is stopped, unavailable, or the current user lacks permission to access it. |
Run docker info and check the Docker service and
socket permissions.
|
Recreate a Compose service
docker compose config
docker compose logs --tail 100
docker compose build --no-cache <service>
docker compose up -d --force-recreate <service>
docker compose ps
Reduce container risk
Docker Security and Best Practices
Build smaller images, run containers with minimal privileges, protect secrets, limit resources, and keep dependencies updated.
Security checklist
| Practice | Recommended action | Why it matters |
|---|---|---|
| Images | Use trusted base images and review their publisher, tags, and update history. | Reduces exposure to unknown or unmaintained image content. |
| Versions | Pin deliberate image versions or digests and update them through a controlled process. | Makes builds more predictable and prevents unexpected changes. |
| Image size | Use multi-stage builds and copy only the runtime artifacts into the final image. | Reduces unnecessary packages, tools, and attack surface. |
| User | Create a dedicated user and run the application as a non-root user. | Limits the impact of a compromised application process. |
| Privileges |
Avoid --privileged and grant only specifically
required capabilities or devices.
|
Prevents unnecessary access to the host and kernel features. |
| Filesystem | Use a read-only root filesystem when possible and provide writable temporary locations explicitly. | Makes persistent modification of the container more difficult. |
| Secrets | Use runtime secret management or BuildKit secret mounts instead of placing credentials in images. | Prevents secrets from remaining in image layers or metadata. |
| Resources | Set appropriate memory, CPU, process, and storage limits. | Reduces the risk of one container exhausting host resources. |
| Network | Publish only necessary ports and separate workloads with user-defined networks. | Limits unnecessary network exposure and service access. |
| Updates | Rebuild and redeploy images regularly with current operating system and application dependencies. | Ensures fixes are incorporated into immutable deployments. |
| Scanning | Scan images and review discovered vulnerabilities before deployment. | Identifies known risks in packages and dependencies. |
| Daemon | Restrict access to the Docker socket and remote daemon API. | Docker daemon access can provide extensive control over the host. |
Run a more restricted container
docker run -d \
--name example-app \
--user 10001:10001 \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
--cap-drop ALL \
--security-opt no-new-privileges=true \
--memory 512m \
--cpus 1.0 \
--pids-limit 100 \
-p 127.0.0.1:8080:8080 \
example-app:1.0
Safer multi-stage Dockerfile
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:24-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
Use BuildKit secrets
# Build command
docker build --secret id=npm_token,src=./npm-token.txt .
# Dockerfile instruction
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci
Security review commands
| Review | Command | Purpose | Copy |
|---|---|---|---|
| History |
docker image history --no-trunc example-app:1.0
|
Reviews image layers and the commands that created them. | |
| User |
docker inspect --format='{{.Config.User}}' example-app:1.0
|
Shows the default user configured for the image. | |
| Configuration |
docker inspect <container>
|
Reviews runtime privileges, mounts, ports, networks, and limits. | |
| Processes |
docker top <container>
|
Displays processes currently running inside the container. | |
| Changes |
docker diff <container>
|
Shows files added, changed, or deleted in the container layer. |
Common questions answered
Docker FAQ
Quick answers to common questions about images, containers, Dockerfiles, Compose, networking, persistent data, and production use.
Docker fundamentals
| Question | Answer |
|---|---|
| What is Docker? | Docker is a platform for building, distributing, and running applications in containers. Containers package an application with the files and dependencies it needs to run consistently. |
| What is the difference between an image and a container? | An image is an immutable package containing an application and its runtime files. A container is a running or stopped instance created from an image. |
| How is a container different from a virtual machine? | A virtual machine includes a complete guest operating system and kernel. Containers are isolated processes that normally share the host kernel, making them generally lighter and faster to start. |
| What is a Dockerfile? | A Dockerfile is a text file containing ordered instructions used to build a container image, including its base image, files, dependencies, configuration, and startup command. |
| What is Docker Compose? | Docker Compose uses a YAML file to define and run an application with one or more services, networks, volumes, configurations, and secrets. |
| What is the difference between a Dockerfile and a Compose file? | A Dockerfile defines how an image is built. A Compose file defines how containers and supporting resources are configured and run. |
Running containers
| Question | Answer |
|---|---|
| Why does my container stop immediately? |
A container normally stops when its main process exits. Check
docker ps -a, read
docker logs <container>, and inspect its exit
code to identify the cause.
|
| Does EXPOSE publish a port? |
No. EXPOSE documents the port an application expects
to use. Publish it at runtime with -p or define it
under ports in a Compose file.
|
| How do containers communicate with each other? | Containers connected to the same user-defined network can communicate using container or Compose service names. Internal container communication does not require publishing ports to the host. |
| Can several containers use the same image? | Yes. Multiple containers can be created from one image, each with its own configuration, writable container layer, network settings, and runtime state. |
| Do I need to rebuild an image after changing source code? | Rebuild when the source code is copied into the image. During development, a bind mount can make host files available inside a container without rebuilding after every edit. |
| What does the latest tag mean? |
latest is an ordinary mutable tag and does not
automatically mean newest, safest, or most stable. Use explicit
version tags or image digests when reproducibility matters.
|
Data, registries, and cleanup
| Question | Answer |
|---|---|
| What happens to data when a container is removed? | Data in the container writable layer is removed with the container. Data stored in a named volume or bind-mounted host directory remains outside the container lifecycle. |
| Should I use a volume or a bind mount? | Use a Docker-managed volume for persistent application data such as databases. Use a bind mount when the container must directly access a specific host file or directory. |
| What is a container registry? | A registry stores and distributes container images. Docker Hub is the default public registry, but private and self-hosted registries can also be used. |
| Does docker compose down delete database data? |
Normal docker compose down keeps named volumes.
Adding -v removes the project volumes and can delete
persistent database or application data.
|
| Is docker system prune safe? |
It removes unused Docker resources and should be reviewed before
use. Run docker system df -v first and be especially
careful with -a and --volumes.
|
| Can Docker be used in production? | Yes, but production use requires more than building an image. Apply security controls, health checks, logging, monitoring, backups, resource limits, controlled updates, and an appropriate deployment platform. |