bashadvanced193 snippets

Docker: Production Commands

Forget manual configuration. Copy and paste commands to spin up containers, clean volumes and deploy in record time.

Sections9
1

ℹ️ Basic Information

8 snippets

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

bash
docker --version

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

bash
docker info

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

bash
docker system info

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

bash
docker system df

Docker Client and Server Version

Displays the versions of the Docker client (CLI) and server (daemon), allowing verification of communication and compatibility between them.

bash
docker version

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

bash
docker system events

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

bash
docker system events --since 1h

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

bash
docker system prune --filter until=24h
2

📦 Containers

20 snippets

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

bash
docker ps

List All Containers (Including Stopped)

Lists all Docker containers, including those that are stopped or have exited (`-a` for "all").

bash
docker ps -a

List Only Container IDs

Lists only the IDs of running Docker containers, useful for chaining commands or automated scripts.

bash
docker ps -q

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

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

bash
docker run -p 3001:3001 blueprint-backend

Run 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`.

bash
docker run -d --name backend -p 3001:3001 blueprint-backend

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

bash
docker run -it --rm alpine sh

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

bash
docker run -e NODE_ENV=production app

Run 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`.

bash
docker run -v $(pwd):/app -w /app node npm install

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

bash
docker run --restart unless-stopped app

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

bash
docker run --memory="256m" app

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

bash
docker run --cpus="0.5" app

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

bash
docker stop container_name

Stop 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`.

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

bash
docker rm container_name

Remove 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`.

bash
docker rm $(docker ps -aq)

Restart a Container

Restarts a running Docker container, stopping it and starting it again.

bash
docker restart container_name

Pause a Container

Pauses all processes within a running container, temporarily suspending it without terminating it, freeing up CPU resources but retaining memory.

bash
docker pause container_name

Unpause a Container

Unpauses a container that was previously paused, allowing its processes to resume execution.

bash
docker unpause container_name

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

bash
docker kill container_name
3

🖼️ Images

18 snippets

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

bash
docker images

List All Images (Including Intermediate)

Lists all Docker images, including intermediate layers (`-a` for "all"), which are typically hidden and can consume space.

bash
docker images -a

List Images with Custom Format

Lists Docker images with a custom table format, displaying repository, tag, and size, for a more organized and focused view.

bash
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").

bash
docker build -t blueprint-backend ./backend

Frontend Image Build

Builds a Docker image from the `Dockerfile` located in the `./frontend` directory and tags it with the name `blueprint-frontend`.

bash
docker build -t blueprint-frontend ./frontend

Build 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`.

bash
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`.

bash
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`.

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

bash
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`).

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

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

bash
docker rmi image_name

Remove 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`.

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

bash
docker image prune

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

bash
docker image prune -a

Rename/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.

bash
docker tag source:latest target:1.0

Push Image to Remote Registry

Pushes a Docker image to a remote registry (`registry.com/app:latest`), making it available to other users or systems.

bash
docker push registry.com/app:latest

Pull Image from Remote Registry

Downloads a Docker image from a remote registry (`registry.com/app:latest`) to your system's local storage.

bash
docker pull registry.com/app:latest
4

📊 Logs and Monitoring

13 snippets

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

bash
docker logs container_name

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

bash
docker logs -f container_name

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

bash
docker logs --tail 50 container_name

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

bash
docker logs --since="2h" container_name

View Logs with Timestamps

Displays container logs, adding a timestamp to each log line (`--timestamps`), which is useful for chronological analysis and event correlation.

bash
docker logs --timestamps container_name

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

bash
docker stats

Specific Container Resource Statistics

Displays real-time resource usage statistics for a specific Docker container, allowing focus on the performance of a single service.

bash
docker stats container_name

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

bash
docker top container_name

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

bash
docker stats --no-stream

Formatted Resource Statistics

Displays container resource usage statistics with a custom table format, showing the container name and CPU usage percentage, for a concise view.

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

bash
docker events

Inspect Container Details

Displays detailed low-level information about a specific Docker container in JSON format, including network configurations, volumes, status, metadata, and event history.

bash
docker inspect container_name

Inspect Image Details

Displays detailed low-level information about a specific Docker image in JSON format, including layers, metadata, port configurations, and environment variables.

bash
docker inspect image_name
5

⚡ Execution and Interaction

11 snippets

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

bash
docker exec -it container_name bash

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

bash
docker exec -it container_name sh

Execute Specific Command in Container

Executes a specific command (`ls -la /app`) inside a running Docker container, without needing shell interaction.

bash
docker exec container_name ls -la /app

Copy File from Host to Container

Copies the `file.txt` file from the host to the `/app/` directory inside the specified container (`container_name`).

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

bash
docker cp container_name:/app/logs ./logs

View Mapped Ports of a Container

Displays port mappings for a specific Docker container, showing which host ports are connected to which container ports.

bash
docker port container_name

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

bash
docker run -p 8080:80 nginx

Automatically 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").

bash
docker run -P nginx

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

bash
docker exec -u root container bash

Execute Command in Background in Container

Executes the `sleep 60` command inside a running container in `detached` mode (background, `-d`), without blocking the current terminal.

bash
docker exec -d container sleep 60

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

bash
docker exec -it container --env VAR=value cmd
6

🧹 Cleanup and Maintenance

12 snippets

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

bash
docker system prune

Remove ALL Unused Docker Data

Removes all unused Docker data, including stopped containers, unused networks, dangling images, and all untagged images (`-a` for "all").

bash
docker system prune -a

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

bash
docker system prune --volumes

Remove Stopped Containers

Removes all stopped Docker containers, freeing up resources and disk space.

bash
docker container prune

Remove Orphan Images

Removes Docker images that are not associated with any container and have no tags ("dangling" or "orphan" images).

bash
docker image prune

Remove Unused Volumes

Removes all Docker volumes not in use by any container, freeing up disk space. Use with caution to avoid data loss.

bash
docker volume prune

Remove Unused Networks

Removes all Docker networks not in use by any container, freeing up network resources.

bash
docker network prune

View Detailed Space Usage

Displays detailed Docker disk space usage (`-v` for "verbose"), showing more granular information about the consumption of each resource type.

bash
docker system df -v

Filter Docker System Events

Displays Docker daemon events, filtering only events related to containers (`--filter type=container`), useful for monitoring specific activities.

bash
docker system events --filter type=container

Clear Docker Build Cache

Clears the Docker build cache, removing unused intermediate layers, which can free up disk space and resolve build issues.

bash
docker builder prune

View Disk Space Usage

Displays a summary of disk space usage by Docker, detailing consumption by images, containers, volumes, and build cache.

bash
docker system df

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

bash
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
7

🔧 Docker Compose

84 snippets

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

bash
docker-compose --version

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

bash
docker-compose up

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

bash
docker-compose up -d

Start Specific Service

Starts only the `backend` service and its dependencies defined in the `docker-compose.yml` file.

bash
docker-compose up backend

Start Services Rebuilding Images

Builds service images before starting containers, ensuring that images are updated with the latest changes in the `Dockerfile`.

bash
docker-compose up --build

Start Services Forcing Recreation

Recreates all containers, even if there are no changes in configuration or image, useful for troubleshooting or applying new configurations.

bash
docker-compose up --force-recreate

Bring Up Services Removing Orphans

Removes service containers no longer defined in the `docker-compose.yml` file (orphans) upon startup, cleaning the environment.

bash
docker-compose up --remove-orphans

Bring Up Service Without Dependencies

Starts a specific service without starting its dependencies, useful for testing a component in isolation.

bash
docker-compose up --no-deps

Bring Up Services with Custom Timeout

Sets a 30-second timeout for graceful container shutdown when stopping or restarting services during `up`.

bash
docker-compose up --timeout 30

Stop and Remove Services and Networks

Stops and removes containers, networks, and default volumes created by `docker-compose up`.

bash
docker-compose down

Stop 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").

bash
docker-compose down -v

Stop 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`.

bash
docker-compose stop

Stop Specific Service

Stops only the `backend` service container defined in `docker-compose.yml`.

bash
docker-compose stop backend

Stop and Remove Services and Images

Stops and removes containers, networks, and also images created by the services (`--rmi all`), freeing up more disk space.

bash
docker-compose down --rmi all

Stop Services with Custom Timeout

Sets a 10-second timeout for graceful container shutdown when stopping services with `down`.

bash
docker-compose down --timeout 10

Force Container Removal

Removes stopped containers without prompting for confirmation (`-f` for "force").

bash
docker-compose rm -f

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

bash
docker-compose down --remove-orphans

View Logs of All Services

Displays the consolidated log output of all services defined in `docker-compose.yml`.

bash
docker-compose logs

Follow Logs of All Services

Displays the log output of all services in real-time, following new entries (`-f` for "follow"), keeping the connection open.

bash
docker-compose logs -f

View Specific Service Logs

Displays the log output only for the `backend` service.

bash
docker-compose logs backend

Access Shell in Service Container

Executes the `bash` command inside the `backend` service container, allowing interactive access to the container's shell.

bash
docker-compose exec backend bash

Execute Specific Command in Service Container

Executes a specific command (`cargo build`) inside the `backend` service container.

bash
docker-compose exec backend cargo build

View Last N Lines of Service Log

Displays the last 50 lines of the `backend` service log.

bash
docker-compose logs --tail 50 backend

View Service Logs From a Period

Displays the logs of the `backend` service generated in the last hour.

bash
docker-compose logs --since="1h" backend

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

bash
docker-compose exec -T backend ls -la

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

bash
docker-compose exec -u root backend bash

Build Images for All Services

Builds images for all services that have a `build` defined in `docker-compose.yml`.

bash
docker-compose build

Build Specific Service Image

Builds the image only for the `backend` service.

bash
docker-compose build backend

Build Images Without Cache

Builds service images without using layer cache, ensuring a clean and fresh build, useful for resolving cache issues.

bash
docker-compose build --no-cache

Scale Service to Multiple Instances

Starts services in `detached` mode and scales the `backend` service to 3 instances, useful for load balancing or performance testing.

bash
docker-compose up -d --scale backend=3

Update Service Images (Pull)

Pulls the latest images for all services defined in `docker-compose.yml` from their respective repositories.

bash
docker-compose pull

Validate Docker Compose Configuration

Validates and displays the effective configuration of `docker-compose.yml` (and override files), useful for debugging the configuration before starting services.

bash
docker-compose config

View Service Status

Lists all containers created by Docker Compose, showing their status, ports, and names, similar to `docker ps` but focused on Compose services.

bash
docker-compose ps

Parallel Image Build

Builds images for multiple services in parallel, speeding up the build process for projects with many services.

bash
docker-compose build --parallel

Build Images with Detailed Progress

Builds images with detailed progress output and no special formatting, useful for CI/CD environments or logs.

bash
docker-compose build --progress=plain

Scale Multiple Services

Starts services and scales multiple services simultaneously, for example, `web` to 2 instances and `db` to 1 instance, in a single operation.

bash
docker-compose up --scale web=2 --scale db=1

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

bash
docker-compose run --env VAR=value backend

Execute Command with .env File Variables

Executes a one-off command in a new `backend` service container, loading environment variables from a specific `.env` file.

bash
docker-compose run --env-file .env backend

View Configured Service Names

Displays only the names of services defined in the `docker-compose.yml` configuration, useful for scripts or automation.

bash
docker-compose config --services

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

bash
docker-compose --env-file prod.env up

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

bash
docker-compose run --rm backend env

View Environment Variables in Running Container

Executes the `printenv` command inside the *running* `backend` service container to list its environment variables.

bash
docker-compose exec backend printenv

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

bash
docker-compose --project-name projeto up

Start 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`.

bash
docker-compose up -d --volume-driver local

List Volume Content in Container

Executes the `ls /data` command inside the `backend` service container to list the content of a volume mounted at `/data`.

bash
docker-compose exec backend ls /data

List 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`.

bash
docker-compose run --rm backend ls /shared

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

bash
docker-compose up --network-alias web

Testar 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`.

bash
docker-compose exec backend ping database

Remove Volumes When Stopping Services

Stops and removes containers, networks, and all named volumes defined in the `docker-compose.yml` file.

bash
docker-compose down --volumes

List Docker Compose Project Volumes

Lists all Docker volumes and filters those containing the project name (`projeto`), useful for identifying volumes created by Docker Compose.

bash
docker volume ls | grep projeto

List Docker Compose Project Networks

Lists all Docker networks and filters those containing the project name (`projeto`), useful for identifying networks created by Docker Compose.

bash
docker network ls | grep projeto

Start Service Without Its Dependencies

Starts the `backend` service without starting its dependencies, useful for isolating and testing a single service.

bash
docker-compose up --no-deps backend

Recreate Service Without Dependencies

Recreates the containers of a specific service without starting its dependencies, useful for forcing a recreation without affecting other services.

bash
docker-compose up --force-recreate --no-deps

Restart Specific Service

Restarts the `backend` service container.

bash
docker-compose restart backend

Restart All Services

Restarts all service containers defined in `docker-compose.yml`.

bash
docker-compose restart

Pause Specific Service

Pauses the `backend` service container, suspending its processes without terminating it.

bash
docker-compose pause backend

Despausar Serviço Específico

Despausa o container do serviço `backend` que foi previamente pausado.

bash
docker-compose unpause backend

Kill Specific Service

Forces the immediate stop of the `backend` service container by sending a SIGKILL signal, without waiting for a graceful shutdown.

bash
docker-compose kill backend

Scale Service to Zero Instances

Reduces the number of instances of the `backend` service to zero, effectively stopping and removing all containers associated with it.

bash
docker-compose up --scale backend=0

Start 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).

bash
docker-compose -f docker-compose.prod.yml up

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

bash
docker-compose -f docker-compose.yml -f docker-compose.override.yml up

Start Services in Compatibility Mode

Activates compatibility mode, which attempts to convert Compose `deploy` options to Docker `run` options, useful for compatibility with Docker Swarm.

bash
docker-compose --compatibility up

Start Services with Detailed Output (Verbose)

Starts services and displays detailed output (`--verbose`) of what Docker Compose is doing, useful for debugging startup issues.

bash
docker-compose --verbose up

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

bash
docker-compose --no-ansi up

Start Services with Specific Profile

Starts services belonging to the `dev` profile (`--profile`), allowing activation/deactivation of service groups based on environment or purpose.

bash
docker-compose --profile dev up

Start Services with Multiple Profiles

Starts services belonging to the `dev` AND `test` profiles, activating multiple service groups simultaneously.

bash
docker-compose --profile dev --profile test up

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

bash
docker-compose config --resolve-env-vars

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

bash
docker-compose -f docker-compose.test.yml up --abort-on-container-exit

CI/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.

bash
docker-compose -f docker-compose.ci.yml up --build

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

bash
docker-compose run --rm backend npm test

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

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

bash
docker-compose run --rm backend python manage.py migrate

Collect Static Files (Django)

Executes the `python manage.py collectstatic` command inside the running `backend` service container to collect static files in Django applications.

bash
docker-compose exec backend python manage.py collectstatic

Recycle 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".

bash
docker-compose down && docker-compose up --build

Check Docker Compose V2 Version

Displays the Docker Compose V2 version, which is integrated into the Docker client (the `compose` command is a `docker` subcommand).

bash
docker compose version

Bring Up Services (Docker Compose V2)

Starts the services defined in the `docker-compose.yml` file using the Docker Compose V2 syntax.

bash
docker compose up

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

bash
docker compose watch

Convert 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).

bash
docker compose alpha convert

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

bash
docker compose config --format json

Execute Command (Docker Compose V2)

Executes the `bash` command in a new `backend` service container (V2) and removes it (`--rm`) after execution.

bash
docker compose run --rm backend bash

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

bash
docker compose up --wait

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

bash
docker compose up --attach dependencies

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

bash
docker compose cp backend:/app ./local

Stop Services with Timeout (Docker Compose V2)

Stops and removes services with a 30-second timeout for graceful shutdown, using Docker Compose V2 syntax.

bash
docker compose down --timeout 30
8

🌐 Networks and Volumes

13 snippets

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

bash
docker network ls

Inspect Docker Network

Displays detailed low-level information about the Docker `bridge` network in JSON format, including connected containers, IP configurations, and options.

bash
docker network inspect bridge

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

bash
docker network create --driver bridge blueprint-net

Remove Docker Network

Removes a specific Docker network. The network must be empty (no connected containers) to be removed.

bash
docker network rm network_name

List Docker Volumes

Lists all locally stored Docker volumes, showing their names and drivers, useful for managing data persistence.

bash
docker volume ls

Inspect Docker Volume

Displays detailed low-level information about a specific Docker volume in JSON format, including its driver, mount point, and options.

bash
docker volume inspect volume_name

Remove Docker Volume

Removes a specific Docker volume. The volume cannot be in use by any container. Use with caution to avoid data loss.

bash
docker volume rm volume_name

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

bash
docker run -v nome_volume:/data alpine

Test Connection Between Containers

Executes the `ping container2` command inside `container1` to test network connectivity between two containers on the same Docker network.

bash
docker exec -it container1 ping container2

Test 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`.

bash
docker exec frontend curl http://backend:3001/health

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

bash
docker network connect bridge container

Disconnect Container from a Network

Disconnects a Docker container from a specific network (in this case, the `bridge` network), isolating it from that network.

bash
docker network disconnect bridge container

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

bash
docker volume create --name data
9

🔧 Troubleshooting

14 snippets

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

bash
docker version

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

bash
systemctl status docker

Docker Service Status (Windows)

Checks the status of the Docker service on Windows using `Get-Service` (PowerShell), showing if the service is running.

bash
Get-Service docker

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

bash
sudo usermod -aG docker $USER

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

bash
newgrp docker

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

bash
docker system df

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

bash
docker system prune -a

List Docker Networks

Lists all Docker networks on the system, showing their IDs, names, drivers, and scopes, useful for diagnosing connectivity issues between containers.

bash
docker network ls

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

bash
docker network inspect bridge

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

bash
journalctl -u docker.service

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

bash
Get-EventLog -LogName Application -Source Docker

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

bash
docker context ls

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

bash
docker context use my-context

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

bash
docker trust inspect image:tag

Get the latest articles delivered to your inbox.

Follow Us: