Docker: Production Commands
Forget manual configuration. Copy and paste commands to spin up containers, clean volumes and deploy in record time.
Sections9
ℹ️ Basic Information
8 snippetsUse this section to check the overall Docker status, installed versions, or get detailed information about the Docker system and resource usage.
Check Docker Version
Displays the Docker client version installed on your system, useful for checking compatibility and the environment.
docker --versionDetailed Docker System Information
Provides a detailed summary of Docker system information, including the number of containers (running, paused, stopped), images, volumes, networks, and daemon configurations.
docker infoDetailed System Information (Alternative)
Similar to `docker info`, this command can provide a more specific or formatted view of Docker system information, depending on the version and configuration.
docker system infoDocker Disk Space Usage
Shows Docker disk space usage, detailing consumption by images, containers, volumes, and build cache, helping to identify where space is being used.
docker system dfDocker Client and Server Version
Displays the versions of the Docker client (CLI) and server (daemon), allowing verification of communication and compatibility between them.
docker versionReal-time Docker System Events
Streams real-time events from the Docker daemon, such as container, image, and volume creation, start, stop, and destruction, useful for continuous monitoring.
docker system eventsSystem Events in the Last Hour
Displays Docker daemon events that occurred in the last hour, useful for reviewing recent system activities and debugging recently emerged issues.
docker system events --since 1hClean Unused Data Older Than 24h
Removes unused Docker data older than 24 hours, such as stopped containers, untagged images, and build cache, helping to free up space selectively.
docker system prune --filter until=24h📦 Containers
20 snippetsUse this section for managing the Docker container lifecycle, from execution and configuration to stopping, removal, and debugging. Essential for deploying and maintaining applications.
List Running Containers
Lists all Docker containers that are currently running, showing their IDs, names, images, commands, mapped ports, and status.
docker psList All Containers (Including Stopped)
Lists all Docker containers, including those that are stopped or have exited (`-a` for "all").
docker ps -aList Only Container IDs
Lists only the IDs of running Docker containers, useful for chaining commands or automated scripts.
docker ps -qList Containers with Custom Format
Lists running containers with a custom table format, displaying only names, status, and mapped ports, allowing for a cleaner and more focused view.
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"Run Container Mapping Port
Runs a new container from the `blueprint-backend` image and maps host port `3001` to container port `3001` (`-p` for "publish"), allowing external access to the service.
docker run -p 3001:3001 blueprint-backendRun Container in Background (Detached)
Runs a new container in `detached` mode (background, `-d`), assigns the name `backend` (`--name`), and maps host port `3001` to container port `3001`.
docker run -d --name backend -p 3001:3001 blueprint-backendRun Interactive Container and Remove on Exit
Runs an `alpine` image container in interactive mode (`-i`) with a pseudo-TTY (`-t`), executing the `sh` command. The container will be automatically removed (`--rm`) upon termination.
docker run -it --rm alpine shRun Container with Environment Variables
Runs an `app` image container and sets the `NODE_ENV` environment variable to `production` (`-e` for "env"), useful for configuring application behavior within the container.
docker run -e NODE_ENV=production appRun Container with Volume and Specific Command
Runs a `node` image container, mounting the host's current working directory (`$(pwd)`) as `/app` inside the container (`-v` for "volume") and setting `/app` as the working directory (`-w`). Then, executes `npm install`.
docker run -v $(pwd):/app -w /app node npm installRun Container with Automatic Restart Policy
Runs a container from the `app` image and configures an automatic restart policy (`--restart unless-stopped`), ensuring the container will restart automatically unless explicitly stopped.
docker run --restart unless-stopped appRun Container Limiting Memory
Runs a container from the `app` image and limits the amount of RAM it can use to 256 megabytes (`--memory`), useful for resource control.
docker run --memory="256m" appRun Container Limiting CPU
Runs a container from the `app` image and limits CPU usage to 0.5 (equivalent to 50% of one CPU core) (`--cpus`), useful for resource control.
docker run --cpus="0.5" appStop a Specific Container
Sends a SIGTERM signal to the specified container, requesting its graceful shutdown. After a timeout, if the container does not stop, a SIGKILL is sent.
docker stop container_nameStop All Running Containers
Stops all running Docker containers, using the output of `docker ps -q` (which lists only the IDs of running containers) as an argument for `docker stop`.
docker stop $(docker ps -q)Remove a Specific Container
Removes a specific Docker container. The container must be stopped before being removed, unless the `-f` (force) flag is used.
docker rm container_nameRemove All Containers (Running and Stopped)
Removes all Docker containers, both running and stopped, using the output of `docker ps -aq` (which lists all IDs) as an argument for `docker rm`.
docker rm $(docker ps -aq)Restart a Container
Restarts a running Docker container, stopping it and starting it again.
docker restart container_namePause a Container
Pauses all processes within a running container, temporarily suspending it without terminating it, freeing up CPU resources but retaining memory.
docker pause container_nameUnpause a Container
Unpauses a container that was previously paused, allowing its processes to resume execution.
docker unpause container_nameForce Stop a Container (Kill)
Forces the immediate stop of a Docker container by sending a SIGKILL signal, without waiting for it to shut down gracefully. Use with caution, as it may result in data loss.
docker kill container_name🖼️ Images
18 snippetsUse this section for creating, managing, listing, or cleaning Docker images. Essential for developing and distributing Dockerized applications.
List Local Docker Images
Lists all locally stored Docker images, showing their repositories, tags, IDs, and sizes.
docker imagesList All Images (Including Intermediate)
Lists all Docker images, including intermediate layers (`-a` for "all"), which are typically hidden and can consume space.
docker images -aList Images with Custom Format
Lists Docker images with a custom table format, displaying repository, tag, and size, for a more organized and focused view.
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"Basic Docker Image Build
Builds a Docker image from the `Dockerfile` located in the `./backend` directory and tags it with the name `blueprint-backend` (`-t` for "tag").
docker build -t blueprint-backend ./backendFrontend Image Build
Builds a Docker image from the `Dockerfile` located in the `./frontend` directory and tags it with the name `blueprint-frontend`.
docker build -t blueprint-frontend ./frontendBuild Image Without Cache
Builds a Docker image from the `Dockerfile` in the current directory, without using layer cache (`--no-cache`), ensuring all steps are executed from scratch, and tags it as `app:latest`.
docker build --no-cache -t app:latest .Multi-stage Image Build with Specific Target
Builds a Docker image from the `Dockerfile` in the current directory, using a specific build stage (`--target production`) defined in the multi-stage Dockerfile, and tags it as `app:prod`.
docker build --target production -t app:prod .Build Image with Build Arguments
Builds a Docker image from the `Dockerfile` in the current directory, passing a build argument (`--build-arg NODE_ENV=production`) that can be used within the Dockerfile during the build process, and tags it as `app`.
docker build --build-arg NODE_ENV=production -t app .Build Image with Detailed Progress
Builds a Docker image with detailed, plain progress output (`--progress=plain`), useful for debugging in CI/CD environments or when standard output is not a TTY.
docker build --progress=plain -t app .Image Build with Layer Squashing
Builds a Docker image and "squashes" the resulting layers into a single layer after the base image, reducing the number of layers and, potentially, the final image size (`--squash`).
docker build --squash -t app .Image Build with Labels (Metadata)
Builds a Docker image and adds a `version=1.0` label (`--label`) to the image, useful for metadata, organization, and filtering.
docker build --label version=1.0 -t app .Remove a Docker Image
Removes a specific Docker image from local storage. The image cannot be in use by any container to be removed.
docker rmi image_nameRemove All Local Images
Removes all unused Docker images, using the output of `docker images -q` (which lists only image IDs) as an argument for `docker rmi`.
docker rmi $(docker images -q)Remove Dangling Images
Removes Docker images that are not associated with any container and have no tags (dangling or orphaned images), freeing up disk space.
docker image pruneRemove All Unused Images (Including Intermediate Layers)
Removes all unused Docker images, including intermediate layers (`-a` for "all"), which are not referenced by any named image.
docker image prune -aRename/Tag an Image
Creates a new tag (`target:1.0`) for an existing image (`source:latest`), allowing the same image to be referenced with different names or specific versions.
docker tag source:latest target:1.0Push Image to Remote Registry
Pushes a Docker image to a remote registry (`registry.com/app:latest`), making it available to other users or systems.
docker push registry.com/app:latestPull Image from Remote Registry
Downloads a Docker image from a remote registry (`registry.com/app:latest`) to your system's local storage.
docker pull registry.com/app:latest📊 Logs and Monitoring
13 snippetsUse this section for debugging, monitoring performance, or analyzing issues in Docker containers through logs and real-time statistics.
View Container Logs
Displays the standard log output (stdout/stderr) of a specific Docker container, useful for debugging and monitoring.
docker logs container_nameFollow Container Logs
Displays container logs in real-time, following new entries (`-f` for "follow"), keeping the connection open and showing logs as they are generated.
docker logs -f container_nameView Last N Log Lines
Displays the last 50 log lines of a specific container (`--tail`), useful for a quick check of recent events without loading the entire history.
docker logs --tail 50 container_nameView Logs From a Period
Displays container logs generated in the last 2 hours (`--since`), allowing logs to be filtered by time period to focus on recent events.
docker logs --since="2h" container_nameView Logs with Timestamps
Displays container logs, adding a timestamp to each log line (`--timestamps`), which is useful for chronological analysis and event correlation.
docker logs --timestamps container_nameReal-time Resource Statistics
Displays a real-time stream of resource usage statistics (CPU, memory, network, disk I/O) for all running containers, useful for performance monitoring and bottleneck identification.
docker statsSpecific Container Resource Statistics
Displays real-time resource usage statistics for a specific Docker container, allowing focus on the performance of a single service.
docker stats container_nameRunning Processes in Container
Displays processes running inside a specific Docker container, similar to the Linux `top` command, useful for debugging and checking which processes are active.
docker top container_nameStatic Resource Statistics
Displays a static snapshot of resource usage statistics for running containers, without the continuous real-time stream (`--no-stream`), useful for point-in-time captures.
docker stats --no-streamFormatted Resource Statistics
Displays container resource usage statistics with a custom table format, showing the container name and CPU usage percentage, for a concise view.
docker stats --format "table {{.Container}}\t{{.CPUPerc}}"Real-time Docker Events
Streams real-time events from the Docker daemon, such as creation, start, stop, and destruction of containers, images, and volumes, useful for auditing and automation.
docker eventsInspect Container Details
Displays detailed low-level information about a specific Docker container in JSON format, including network configurations, volumes, status, metadata, and event history.
docker inspect container_nameInspect Image Details
Displays detailed low-level information about a specific Docker image in JSON format, including layers, metadata, port configurations, and environment variables.
docker inspect image_name⚡ Execution and Interaction
11 snippetsUse this section to interact directly with running containers, execute commands inside them, copy files between host and container, or manage port mappings and networks.
Access Interactive Shell in Container (Bash)
Executes the `bash` command inside a running Docker container, allocating a pseudo-TTY (`-t`) and keeping standard input open (`-i`) for interaction, allowing access to the container's shell.
docker exec -it container_name bashAccess Basic Shell in Container (Sh)
Executes the `sh` (basic shell) command inside a running Docker container in interactive mode with pseudo-TTY, useful when `bash` is not available in the container.
docker exec -it container_name shExecute Specific Command in Container
Executes a specific command (`ls -la /app`) inside a running Docker container, without needing shell interaction.
docker exec container_name ls -la /appCopy File from Host to Container
Copies the `file.txt` file from the host to the `/app/` directory inside the specified container (`container_name`).
docker cp file.txt container_name:/app/Copy File/Directory from Container to Host
Copies the `logs` directory from inside the specified container (`container_name:/app/logs`) to the local `./logs` directory on the host.
docker cp container_name:/app/logs ./logsView Mapped Ports of a Container
Displays port mappings for a specific Docker container, showing which host ports are connected to which container ports.
docker port container_nameMap Specific Port When Running Container
Runs a container from the `nginx` image and maps host port `8080` to container port `80` (`-p` for "publish"), allowing web server access.
docker run -p 8080:80 nginxAutomatically Map Ports When Running Container
Runs an `nginx` image container and automatically maps all ports exposed in the container's `Dockerfile` to random, unused ports on the host (`-P` for "publish all").
docker run -P nginxExecute Command as Root User in Container
Executes the `bash` command inside a running container as the `root` user (`-u`), useful for administrative tasks requiring elevated privileges.
docker exec -u root container bashExecute Command in Background in Container
Executes the `sleep 60` command inside a running container in `detached` mode (background, `-d`), without blocking the current terminal.
docker exec -d container sleep 60Execute Command with Environment Variables in Container
Executes a command (`cmd`) inside a running container, passing an environment variable (`--env VAR=value`) that will only be available for the execution of that command.
docker exec -it container --env VAR=value cmd🧹 Cleanup and Maintenance
12 snippetsUse this section to free disk space, remove unused Docker resources, or clean the Docker environment to maintain efficiency.
Remove Unused Docker Data
Removes all unused Docker data, including stopped containers, unused networks, and dangling images, but not volumes by default.
docker system pruneRemove ALL Unused Docker Data
Removes all unused Docker data, including stopped containers, unused networks, dangling images, and all untagged images (`-a` for "all").
docker system prune -aRemove Unused Data Including Volumes
Removes all unused Docker data, including volumes not referenced by any container (`--volumes`), as well as stopped containers, networks, and dangling images.
docker system prune --volumesRemove Stopped Containers
Removes all stopped Docker containers, freeing up resources and disk space.
docker container pruneRemove Orphan Images
Removes Docker images that are not associated with any container and have no tags ("dangling" or "orphan" images).
docker image pruneRemove Unused Volumes
Removes all Docker volumes not in use by any container, freeing up disk space. Use with caution to avoid data loss.
docker volume pruneRemove Unused Networks
Removes all Docker networks not in use by any container, freeing up network resources.
docker network pruneView Detailed Space Usage
Displays detailed Docker disk space usage (`-v` for "verbose"), showing more granular information about the consumption of each resource type.
docker system df -vFilter Docker System Events
Displays Docker daemon events, filtering only events related to containers (`--filter type=container`), useful for monitoring specific activities.
docker system events --filter type=containerClear Docker Build Cache
Clears the Docker build cache, removing unused intermediate layers, which can free up disk space and resolve build issues.
docker builder pruneView Disk Space Usage
Displays a summary of disk space usage by Docker, detailing consumption by images, containers, volumes, and build cache.
docker system dfView Formatted Image Sizes
Lists Docker images with a custom table format, displaying repository, tag, and size, for a quick analysis of space occupied by images.
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"🔧 Docker Compose
84 snippetsUse this section for multi-container applications or development environments using Docker Compose to orchestrate services. Covers basic commands to advanced configurations and CI/CD integration.
Check Docker Compose Version
Displays the installed Docker Compose version, useful for checking compatibility and available features.
docker-compose --versionBring Up Services (Foreground)
Builds, (re)creates, starts, and attaches to containers for all services defined in the `docker-compose.yml` file, running in the foreground and displaying logs.
docker-compose upBring Up Services (Background - Detached)
Builds, (re)creates, starts, and attaches to containers for all services defined in the `docker-compose.yml` file, running in `detached` (background) mode.
docker-compose up -dStart Specific Service
Starts only the `backend` service and its dependencies defined in the `docker-compose.yml` file.
docker-compose up backendStart Services Rebuilding Images
Builds service images before starting containers, ensuring that images are updated with the latest changes in the `Dockerfile`.
docker-compose up --buildStart Services Forcing Recreation
Recreates all containers, even if there are no changes in configuration or image, useful for troubleshooting or applying new configurations.
docker-compose up --force-recreateBring Up Services Removing Orphans
Removes service containers no longer defined in the `docker-compose.yml` file (orphans) upon startup, cleaning the environment.
docker-compose up --remove-orphansBring Up Service Without Dependencies
Starts a specific service without starting its dependencies, useful for testing a component in isolation.
docker-compose up --no-depsBring Up Services with Custom Timeout
Sets a 30-second timeout for graceful container shutdown when stopping or restarting services during `up`.
docker-compose up --timeout 30Stop and Remove Services and Networks
Stops and removes containers, networks, and default volumes created by `docker-compose up`.
docker-compose downStop and Remove Services, Networks, and Volumes
Stops and removes containers, networks, and also named volumes defined in the `docker-compose.yml` file (`-v` for "volumes").
docker-compose down -vStop Services Only
Stops the containers for services defined in `docker-compose.yml`, but does not remove them, allowing them to be restarted later with `docker-compose start`.
docker-compose stopStop Specific Service
Stops only the `backend` service container defined in `docker-compose.yml`.
docker-compose stop backendStop and Remove Services and Images
Stops and removes containers, networks, and also images created by the services (`--rmi all`), freeing up more disk space.
docker-compose down --rmi allStop Services with Custom Timeout
Sets a 10-second timeout for graceful container shutdown when stopping services with `down`.
docker-compose down --timeout 10Force Container Removal
Removes stopped containers without prompting for confirmation (`-f` for "force").
docker-compose rm -fStop and Remove Services and Orphans
Stops and removes containers, networks, and also any containers that are no longer referenced in the `docker-compose.yml` file.
docker-compose down --remove-orphansView Logs of All Services
Displays the consolidated log output of all services defined in `docker-compose.yml`.
docker-compose logsFollow Logs of All Services
Displays the log output of all services in real-time, following new entries (`-f` for "follow"), keeping the connection open.
docker-compose logs -fView Specific Service Logs
Displays the log output only for the `backend` service.
docker-compose logs backendAccess Shell in Service Container
Executes the `bash` command inside the `backend` service container, allowing interactive access to the container's shell.
docker-compose exec backend bashExecute Specific Command in Service Container
Executes a specific command (`cargo build`) inside the `backend` service container.
docker-compose exec backend cargo buildView Last N Lines of Service Log
Displays the last 50 lines of the `backend` service log.
docker-compose logs --tail 50 backendView Service Logs From a Period
Displays the logs of the `backend` service generated in the last hour.
docker-compose logs --since="1h" backendExecute Command Without TTY
Executes the `ls -la` command inside the `backend` service container without allocating a pseudo-TTY (`-T`), useful for automated scripts or when output does not require interactive formatting.
docker-compose exec -T backend ls -laExecute Command as Specific User
Executes the `bash` command inside the `backend` service container as the `root` user (`-u`), useful for administrative tasks requiring elevated privileges.
docker-compose exec -u root backend bashBuild Images for All Services
Builds images for all services that have a `build` defined in `docker-compose.yml`.
docker-compose buildBuild Specific Service Image
Builds the image only for the `backend` service.
docker-compose build backendBuild Images Without Cache
Builds service images without using layer cache, ensuring a clean and fresh build, useful for resolving cache issues.
docker-compose build --no-cacheScale Service to Multiple Instances
Starts services in `detached` mode and scales the `backend` service to 3 instances, useful for load balancing or performance testing.
docker-compose up -d --scale backend=3Update Service Images (Pull)
Pulls the latest images for all services defined in `docker-compose.yml` from their respective repositories.
docker-compose pullValidate Docker Compose Configuration
Validates and displays the effective configuration of `docker-compose.yml` (and override files), useful for debugging the configuration before starting services.
docker-compose configView Service Status
Lists all containers created by Docker Compose, showing their status, ports, and names, similar to `docker ps` but focused on Compose services.
docker-compose psParallel Image Build
Builds images for multiple services in parallel, speeding up the build process for projects with many services.
docker-compose build --parallelBuild Images with Detailed Progress
Builds images with detailed progress output and no special formatting, useful for CI/CD environments or logs.
docker-compose build --progress=plainScale Multiple Services
Starts services and scales multiple services simultaneously, for example, `web` to 2 instances and `db` to 1 instance, in a single operation.
docker-compose up --scale web=2 --scale db=1Execute Command with Inline Environment Variable
Executes a one-off command in a new `backend` service container, passing an environment variable `VAR` with the value `value` inline.
docker-compose run --env VAR=value backendExecute Command with .env File Variables
Executes a one-off command in a new `backend` service container, loading environment variables from a specific `.env` file.
docker-compose run --env-file .env backendView Configured Service Names
Displays only the names of services defined in the `docker-compose.yml` configuration, useful for scripts or automation.
docker-compose config --servicesBring Up Services with Specific .env File
Starts services using environment variables defined in a specific `prod.env` file, overriding or complementing those from the default `.env` file, for different environments.
docker-compose --env-file prod.env upView Environment Variables in New Container
Executes the `env` command inside a new `backend` service container and removes it (`--rm`) after execution, to list the environment variables available to the service.
docker-compose run --rm backend envView Environment Variables in Running Container
Executes the `printenv` command inside the *running* `backend` service container to list its environment variables.
docker-compose exec backend printenvStart Services with Custom Project Name
Starts services under a specific project name (`--project-name projeto`), which affects the names of created containers, networks, and volumes, useful for isolating environments.
docker-compose --project-name projeto upStart Services with Specific Volume Driver
Starts services in `detached` mode, specifying the `local` volume driver for volumes defined in the services. Generally, the driver is configured directly in `docker-compose.yml`.
docker-compose up -d --volume-driver localList Volume Content in Container
Executes the `ls /data` command inside the `backend` service container to list the content of a volume mounted at `/data`.
docker-compose exec backend ls /dataList Shared Volume Content in New Container
Executes the `ls /shared` command in a new `backend` service container (which is removed after execution) to list the content of a shared volume mounted at `/shared`.
docker-compose run --rm backend ls /sharedAdd Network Alias (YAML Configuration)
This command does not directly add a network alias via `up`. Network aliases for services are defined within the service's network configuration in the `docker-compose.yml` file to allow other services to find it by that name.
docker-compose up --network-alias webTestar Conectividade entre Serviços
Executa o comando `ping database` dentro do container do serviço `backend` para testar a conectividade de rede com o serviço `database`.
docker-compose exec backend ping databaseRemove Volumes When Stopping Services
Stops and removes containers, networks, and all named volumes defined in the `docker-compose.yml` file.
docker-compose down --volumesList Docker Compose Project Volumes
Lists all Docker volumes and filters those containing the project name (`projeto`), useful for identifying volumes created by Docker Compose.
docker volume ls | grep projetoList Docker Compose Project Networks
Lists all Docker networks and filters those containing the project name (`projeto`), useful for identifying networks created by Docker Compose.
docker network ls | grep projetoStart Service Without Its Dependencies
Starts the `backend` service without starting its dependencies, useful for isolating and testing a single service.
docker-compose up --no-deps backendRecreate Service Without Dependencies
Recreates the containers of a specific service without starting its dependencies, useful for forcing a recreation without affecting other services.
docker-compose up --force-recreate --no-depsRestart Specific Service
Restarts the `backend` service container.
docker-compose restart backendRestart All Services
Restarts all service containers defined in `docker-compose.yml`.
docker-compose restartPause Specific Service
Pauses the `backend` service container, suspending its processes without terminating it.
docker-compose pause backendDespausar Serviço Específico
Despausa o container do serviço `backend` que foi previamente pausado.
docker-compose unpause backendKill Specific Service
Forces the immediate stop of the `backend` service container by sending a SIGKILL signal, without waiting for a graceful shutdown.
docker-compose kill backendScale Service to Zero Instances
Reduces the number of instances of the `backend` service to zero, effectively stopping and removing all containers associated with it.
docker-compose up --scale backend=0Start Services with Specific Compose File
Starts services using an alternative `docker-compose` file (`docker-compose.prod.yml`) instead of the default, useful for different environments (production, development).
docker-compose -f docker-compose.prod.yml upStart Services with Multiple Compose Files
Starts services by combining configurations from multiple `docker-compose` files, where the second file (`override.yml`) can overwrite or extend the first.
docker-compose -f docker-compose.yml -f docker-compose.override.yml upStart Services in Compatibility Mode
Activates compatibility mode, which attempts to convert Compose `deploy` options to Docker `run` options, useful for compatibility with Docker Swarm.
docker-compose --compatibility upStart Services with Detailed Output (Verbose)
Starts services and displays detailed output (`--verbose`) of what Docker Compose is doing, useful for debugging startup issues.
docker-compose --verbose upStart Services Without Colors (No ANSI)
Starts services, disabling ANSI (color) output in the terminal (`--no-ansi`), useful for logs in systems that do not interpret color codes or for logging to files.
docker-compose --no-ansi upStart Services with Specific Profile
Starts services belonging to the `dev` profile (`--profile`), allowing activation/deactivation of service groups based on environment or purpose.
docker-compose --profile dev upStart Services with Multiple Profiles
Starts services belonging to the `dev` AND `test` profiles, activating multiple service groups simultaneously.
docker-compose --profile dev --profile test upValidate Configuration by Resolving Environment Variables
Validates and displays the `docker-compose.yml` configuration, resolving and substituting all environment variables with their current values, useful for checking the final configuration.
docker-compose config --resolve-env-varsRun Automated Tests (CI/CD)
Starts the services defined in `docker-compose.test.yml` and stops all other containers if one exits (`--abort-on-container-exit`), ideal for automated testing environments where a test failure should stop everything.
docker-compose -f docker-compose.test.yml up --abort-on-container-exitCI/CD Environment with Build
Starts the services defined in `docker-compose.ci.yml`, rebuilding the images, for a Continuous Integration (CI) environment ensuring the environment is always up-to-date.
docker-compose -f docker-compose.ci.yml up --buildRun Unit Tests in Container
Executes the `npm test` command in a new `backend` service container and removes it (`--rm`) after execution, ideal for running unit or integration tests in isolation.
docker-compose run --rm backend npm testRun Code Lint in Container
Executes the `flake8` lint tool in a new `backend` service container and removes it (`--rm`) after execution, for static Python code analysis.
docker-compose run --rm backend flake8 .Run Database Migrations
Executes the `python manage.py migrate` command in a new `backend` service container and removes it (`--rm`) after execution, to apply database migrations in Django applications.
docker-compose run --rm backend python manage.py migrateCollect Static Files (Django)
Executes the `python manage.py collectstatic` command inside the running `backend` service container to collect static files in Django applications.
docker-compose exec backend python manage.py collectstaticRecycle Docker Compose Environment
First, stops and removes all services and their networks (`down`), then starts them again, rebuilding the images (`up --build`), useful for a complete development environment "reset".
docker-compose down && docker-compose up --buildCheck Docker Compose V2 Version
Displays the Docker Compose V2 version, which is integrated into the Docker client (the `compose` command is a `docker` subcommand).
docker compose versionBring Up Services (Docker Compose V2)
Starts the services defined in the `docker-compose.yml` file using the Docker Compose V2 syntax.
docker compose upWatch Mode (Docker Compose V2)
Monitors the file system and automatically restarts or rebuilds services when changes are detected, useful for local development with instant feedback.
docker compose watchConvert to Docker Compose V2 (Alpha)
Attempts to convert a `docker-compose.yml` file from V1 to V2 syntax, useful for migration. (Alpha command, subject to change).
docker compose alpha convertConfiguration in JSON (Docker Compose V2)
Validates and displays the effective `docker-compose.yml` configuration in JSON format, useful for programmatic processing or integration with other tools.
docker compose config --format jsonExecute Command (Docker Compose V2)
Executes the `bash` command in a new `backend` service container (V2) and removes it (`--rm`) after execution.
docker compose run --rm backend bashWait for Container Health (Docker Compose V2)
Starts the services and waits until all containers are healthy (healthcheck) before considering the command complete, useful in CI/CD scripts to ensure the application is ready.
docker compose up --waitAttach Dependency Logs (Docker Compose V2)
Starts the services and attaches to the logs of all services, including their dependencies, useful for observing the complete application startup and debugging inter-service initialization issues.
docker compose up --attach dependenciesCopy Files (Docker Compose V2)
Copies files or directories from inside the `backend` service container to a local directory on the host, using Docker Compose V2 syntax.
docker compose cp backend:/app ./localStop Services with Timeout (Docker Compose V2)
Stops and removes services with a 30-second timeout for graceful shutdown, using Docker Compose V2 syntax.
docker compose down --timeout 30🌐 Networks and Volumes
13 snippetsUse this section for configuring communication between containers, managing data persistence, or isolating network environments in Docker.
List Docker Networks
Lists all Docker networks on the system, showing their IDs, names, drivers, and scopes, useful for understanding network topology.
docker network lsInspect Docker Network
Displays detailed low-level information about the Docker `bridge` network in JSON format, including connected containers, IP configurations, and options.
docker network inspect bridgeCreate New Docker Network
Creates a new Docker network named `blueprint-net` using the `bridge` driver, allowing containers connected to it to communicate easily by name.
docker network create --driver bridge blueprint-netRemove Docker Network
Removes a specific Docker network. The network must be empty (no connected containers) to be removed.
docker network rm network_nameList Docker Volumes
Lists all locally stored Docker volumes, showing their names and drivers, useful for managing data persistence.
docker volume lsInspect Docker Volume
Displays detailed low-level information about a specific Docker volume in JSON format, including its driver, mount point, and options.
docker volume inspect volume_nameRemove Docker Volume
Removes a specific Docker volume. The volume cannot be in use by any container. Use with caution to avoid data loss.
docker volume rm volume_nameUse Named Volume in Container
Runs an `alpine` image container and mounts a named volume (`nome_volume`) to the `/data` directory inside the container, ensuring data persistence.
docker run -v nome_volume:/data alpineTest Connection Between Containers
Executes the `ping container2` command inside `container1` to test network connectivity between two containers on the same Docker network.
docker exec -it container1 ping container2Test API Connectivity Between Containers
Executes the `curl` command inside the `frontend` container to test the accessibility and health status of an API in the `backend` container on port `3001`.
docker exec frontend curl http://backend:3001/healthConnect Container to a Network
Connects an existing Docker container to a specific Docker network (in this case, the `bridge` network), allowing it to communicate with other containers on that network.
docker network connect bridge containerDisconnect Container from a Network
Disconnects a Docker container from a specific network (in this case, the `bridge` network), isolating it from that network.
docker network disconnect bridge containerCreate Named Volume
Creates a new Docker named volume `data`, which can be used to persist data between containers or between the host and containers, regardless of the container's lifecycle.
docker volume create --name data🔧 Troubleshooting
14 snippetsUse this section when encountering issues with containers, networks, Docker installation, or performance. Contains commands to check status, diagnose common problems, and access system logs.
Check Docker Installation
Checks the Docker client and server (daemon) versions, useful for confirming if Docker is installed and if the daemon is responding.
docker versionDocker Service Status (Linux)
Checks the status of the Docker service on Linux using `systemctl`, showing if the daemon is active, running, and any recent system log messages.
systemctl status dockerDocker Service Status (Windows)
Checks the status of the Docker service on Windows using `Get-Service` (PowerShell), showing if the service is running.
Get-Service dockerAdd User to Docker Group (Linux)
Adds the current user (`$USER`) to the `docker` group on Linux, granting permissions to run Docker commands without `sudo`. Requires logout/login or `newgrp docker` to apply.
sudo usermod -aG docker $USERApply Docker Group in Current Shell
Changes the primary group of the current shell to `docker`, applying group permissions without needing to log out and log in again. Useful after adding the user to the docker group.
newgrp dockerView Disk Space Usage
Displays a summary of Docker disk space usage, detailing consumption by images, containers, volumes, and build cache, useful for diagnosing space issues.
docker system dfClean ALL Unused Docker Data
Removes all unused Docker data, including stopped containers, unused networks, dangling images, and all untagged images (`-a` for "all"), freeing up maximum possible space.
docker system prune -aList Docker Networks
Lists all Docker networks on the system, showing their IDs, names, drivers, and scopes, useful for diagnosing connectivity issues between containers.
docker network lsInspect Docker Network
Displays detailed low-level information about the Docker `bridge` network in JSON format, including connected containers and IP configurations, crucial for network debugging.
docker network inspect bridgeDocker Daemon Logs (Linux)
Displays Docker service logs on Linux using `journalctl`, useful for debugging issues with the Docker daemon itself, such as startup failures or internal errors.
journalctl -u docker.serviceDocker Logs (Windows Event Log)
Displays Docker-related event logs on Windows using `Get-EventLog` (PowerShell), useful for debugging issues with the operating system or the Docker service.
Get-EventLog -LogName Application -Source DockerList Docker Contexts
Lists all available Docker contexts, which allow easily switching between different Docker hosts (local, remote, cloud), useful for checking which environment is targeted by commands.
docker context lsChange Active Docker Context
Changes the active Docker context to `my-context`, directing subsequent Docker commands to the host or environment defined in that context. Essential when working with multiple Docker environments.
docker context use my-contextVerify Image Trust Signature
Verifies the trust signature of a specific Docker image, ensuring that the image has not been tampered with and comes from a trusted source, important for security.
docker trust inspect image:tagRelated cheatsheets
Get-LocationPowerShell: Automate the Boring Stuff
GUIs are for amateurs. Master the One-Liners and Pipelines that manage 100 servers simultaneously. Stop clicking windows and start treating your infrastructure as code.
git status -sGit: The Emergency Kit
Messed up the code? Save this guide. Essential commands to undo mistakes, revert commits and save your job.
ping -c 4 google.comLinux Networking: The Hacker Guide
Feel like Mr. Robot. Network commands to discover IPs, open ports and diagnose connections like a CyberSec professional.