Docker

Docker CLI — Global Parameters

Parameter Name Description
Global CLI Flags
docker Docker CLI The main Docker CLI command. All other Docker commands are subcommands of this executable. Docker acts as a facade for managing Docker Engine via the REST API. Main categories: container, image, network, volume, compose, swarm, system. To view all available subcommands, use docker --help. Execution priority: global flags → subcommand → subcommand arguments. Example: docker ps — list containers, docker image ls — list images, docker volume create mydata — create volume
docker --config <path> Docker config directory Specifies an alternative path to the Docker CLI config directory. Default is ~/.docker. Contains: config.json (registry credentials), contexts/ (saved contexts), tls/ (TLS certificates). Useful for isolating configurations of different environments (dev/staging/prod). When specifying your own config, CLI does not load the main config.json. Example: docker --config ~/.docker-dev ps — uses configuration from the dev profile. To create a new config: mkdir ~/.docker-staging && docker --config ~/.docker-staging login. Allows storing separate credentials for each environment
docker -c <context>, docker --context <context> Docker context Uses the specified Docker context to execute the command. A context is a template that stores information about the Docker daemon (endpoint, TLS settings, authorization). Allows switching between different environments without modifying environment variables. List contexts: docker context ls. Manage: docker context create, docker context use. Built-in contexts: default (local daemon), desktop-linux (Docker Desktop). Example: docker --context prod ps — shows containers on the production server. Best practice: docker context create staging --docker host=ssh://staging@example.com — creates a context for the staging server
docker -D, docker --debug Debug mode Enables CLI debug mode, which outputs detailed debug information: HTTP requests to Docker API, headers, response bodies, timings. Useful when troubleshooting connection issues, API errors, TLS problems. Debug output is directed to stderr, allowing redirect to a file. Docker Engine log level can also be raised via /etc/docker/daemon.json with "log-level": "debug". Example: docker -D build . 2> debug.log — save debug output to a file. To activate permanently, set DOCKER_DEBUG=1 in environment variables. Note: may expose sensitive data (tokens, passwords) in output
docker -H <host>, docker --host <host> Docker daemon host Connect to a remote Docker daemon instead of the local default (unix:///var/run/docker.sock). Supported protocols: SSH (ssh://user@host), TCP (tcp://host:port), Unix socket (unix:///path/to/socket), TLS-secured TCP (tls://host:port). TLS is required for secure connection. Example: docker -H tcp://10.0.0.5:2376 ps — connect to remote daemon. With SSH: docker -H ssh://user@192.168.1.10 ps (uses SSH tunnel). Warning: unencrypted TCP (port 2375) is insecure — all data is transmitted in plaintext
docker -l <level>, docker --log-level <level> Log level Sets Docker CLI log level. Available values (in increasing severity): debug (debug), info (information, default), warn (warnings), error (errors), fatal (critical errors, exits). Affects only CLI messages — does not change Docker Engine log level. Useful for filtering noise when used in CI/CD scripts. Example: docker --log-level warn ps — shows only warnings and errors. Values can also be set via DOCKER_LOGLEVEL=debug variable
TLS Parameters
docker --tls TLS connection Enables TLS encryption for connecting to the Docker daemon. Uses certificates from $DOCKER_CERT_PATH or $DOCKER_CONFIG/tls/. Required for secure remote connection. Without --tlsverify, server authentication is not performed (vulnerable to MITM attacks). Example: docker --tls --host tcp://10.0.0.5:2376 ps — connects with encryption. To generate certificates, use docker-machine or swarm ca. Docker Desktop has TLS enabled by default
docker --tlsverify TLS verify Enables TLS with mandatory server certificate verification (mutual TLS). Verifies server authenticity via CA certificate, protecting against spoof attacks. Requires ca.pem in $DOCKER_CERT_PATH. Without this flag, vulnerable to MITM (Man-in-the-Middle). Example: docker --tlsverify --tlscacert /path/to/ca.pem --host tcp://prod-server:2376 ps. For two-way authentication, add --tlscert and --tlskey. In production, always use with --tlsverify
docker --tlscacert <path> TLS CA certificate Path to the CA (Certificate Authority) certificate file (ca.pem). Used to verify Docker daemon authenticity. The certificate must be signed by a trusted certification authority. Usually generated along with client certificates. Example: docker --tlsverify --tlscacert /etc/docker/ca.pem --tlscert /etc/docker/cert.pem --tlskey /etc/docker/key.pem -H tcp://10.0.0.5:2376 ps. If this flag is absent, Docker looks for ca.pem in $DOCKER_CERT_PATH or ~/.docker/tls/. For Docker Hub, certificates are loaded automatically
docker --tlscert <path> TLS certificate Path to the client TLS certificate (cert.pem). Used for two-way authentication (mutual TLS) — the daemon verifies client authenticity. Combined with --tlskey to form an SSL certificate. Example: docker --tlscert /etc/docker/cert.pem --tlskey /etc/docker/key.pem -H tls://prod:2376 ps. The certificate must be signed by the same CA as the daemon. To generate: openssl req -newkey rsa:4096 -nodes -sha256 -keyout client.key -out client.csr, then sign via CA
docker --tlskey <path> TLS private key Path to the client TLS private key (key.pem). Must correspond to the client certificate from --tlscert. Store the key in a secure location with 600 permissions. Example: docker --tlscert /etc/docker/cert.pem --tlskey /etc/docker/key.pem --tlsverify --tlscacert /etc/docker/ca.pem -H tls://10.0.0.5:2376 ps. If the key is compromised, immediately regenerate all certificates. Docker Desktop manages keys automatically

Docker Core Commands

Command Name Description
docker version Docker version Shows Docker CLI and Engine versions. Outputs information about Client and Server parts: version, API version, Go version, Git commit, build date, client/server status. Useful for diagnosing version incompatibilities. Example: docker version — shows full information. --format flag for formatting: docker version --format '{{.Client.Version}}'. If daemon is not running, shows only Client information and a connection error
docker info Docker system info Shows Docker daemon system information: container count, image count, swarm status, default drivers (storage, network, logging). Useful for checking configuration and resources. Example: docker info — full information. Key sections: Server Version, Storage Driver, Security Options, Total Memory, NRPE. --format key to extract specific fields: docker info --format '{{.ServerVersion}}'. Alternative: docker system info — also works
docker help Docker help Outputs Docker CLI help with a list of all available commands and options. Without arguments, shows general help. With argument — help for a specific command. Example: docker help run — help for docker run, docker --help — general help. Alternative: docker run --help. Also works: docker help container ls. In interactive mode, suggests command autocomplete (zsh/bash). Also available: docker MANIFEST to view official documentation
docker login Registry login Authorization to Docker registry. Saves credentials to ~/.docker/config.json for subsequent pull/push operations. Example: docker login — login to Docker Hub, docker login registry.example.com -u myuser -p mypass — login to private registry. Flags: --username, --password (or input via stdin for security), --help. For CI automation: echo "$PASSWORD" | docker login -u "$USER" --password-stdin. Output does not contain passwords
docker logout Registry logout Logout from registry, removes saved credentials from config.json. Useful when changing accounts or cleaning sensitive data. Example: docker logout — logout from Docker Hub, docker logout registry.example.com — logout from specific registry. After logout, all operations with that registry require re-authentication. Does not remove TLS certificates or contexts
docker search Search images Search images in Docker Hub. Supports filtering by name, author, rating. Example: docker search nginx — search nginx, docker search --filter "stars=100" nginx — only images with 100+ stars. Flags: --filter (stars, is-automated, is-official), --format (table/raw/go-template), --limit (max results), --no-trunc. For programmatic processing: docker search --format '{{.Name}}:{{.Tag}}'. Can also search in private registry via API
docker inspect Inspect objects Get low-level JSON information about a container, image, network, volume, or other Docker object. Returns full configuration and status. Example: docker inspect mycontainer — full information, docker inspect --format '{{.NetworkSettings.IPAddress}}' mycontainer — only IP address. Object types: container, image, network, volume, service, node. -f flag for Go templates, --type for filtering by object type. Useful for automation scripts and troubleshooting
docker events Docker events stream Docker daemon events stream in real-time. Includes events for container creation/removal, status changes, network, volume. Example: docker events — events stream, docker events --filter 'type=container' --filter 'event=start' — only container starts. Flags: --filter (multiplex), --since (date/time), --until, --format. Useful for monitoring, automation, logging. For filtering in scripts: docker events --filter 'image=nginx' | grep start
docker system Docker system management Docker system management: cleanup, disk space monitoring, information. Subcommands: df (analog of df -h), prune (cleanup unused objects), info (system information). Example: docker system df — disk usage, docker system prune -a — remove all unused objects. For cleaning: docker system prune --volumes (including volumes). Useful for freeing disk space and keeping the system clean
docker context Docker contexts Manage contexts for switching between different Docker daemons. Subcommands: create (create), inspect (view), rm (remove), use (activate), update (update). Example: docker context create prod --docker host=tcp://10.0.0.5:2376. Default contexts: default (local Docker), desktop-linux (Docker Desktop). Contexts stored in ~/.docker/contexts/. Useful for working with multiple environments
docker init Initialize project Interactive generation of starter Docker files for a project: Dockerfile, docker-compose.yml, .dockerignore. Automatically detects project type (Node.js, Python, Go, Java, etc.) and creates optimized files. Example: docker init — in current directory, docker init --mode complete — without questions. Creates: Dockerfile (with multi-stage build), docker-compose.yml (with services), .dockerignore, .env. Can also specify image: docker init --image nginx. Documentation: docker init docs
docker debug Container debugging Debug shell for container/image. Launches an interactive debugging session of the container with access to the filesystem and tools. Example: docker debug mycontainer — container debugging, docker debug ubuntu — image debugging. Launches nerdctl — alternative client with advanced capabilities. Includes access to strace, ltrace, gdb for deep diagnostics. Useful for exploring image and container contents
docker buildx Buildx builder Extended BuildKit builder with multi-arch build support, cache management, and CI integration. This is the modern way to build Docker images. Example: docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest . — multi-arch build. Subcommands: build (build), ls (list), create (create builder), inspect, rm, use, prune. BuildKit provides layer caching, secret variables, SSH-forwarding, cache export. Documentation: BuildKit docs
docker builder Build management Manage builder instances. Allows creating, configuring, and removing BuildKit builder instances for different tasks. Example: docker builder ls — list builders, docker builder create mybuilder --driver docker-container. Subcommands: ls, create, inspect, rm, prune, use, update. Useful for isolating build processes, managing resources, and optimizing build pipeline. Alternative: docker buildx

Docker Container Commands

Command Name Description
docker container ls List containers List of running containers. Analog of docker ps. Flags: -a (all containers), -n (last N), --filter (by status, name, network, etc.), --format (output format). Example: docker container ls — only running, docker container ls -a — all, docker container ls --filter "status=running" — only running. Output: CONTAINER ID, IMAGE, COMMAND, CREATED, STATUS, PORTS, NAMES. Useful for monitoring current containers and troubleshooting
docker container ls -a List all containers List of all containers including stopped and created ones. Shows full status: Created, Running, Paused, Exited, Dead. Useful for cleaning unused containers or finding deleted ones. Example: docker container ls -a --filter "status=exited" — only stopped. --size flag shows container data file sizes. Can be combined with docker rm for cleanup: docker container ls -a --filter "status=exited" -q | xargs docker rm
docker container run Run container Create and start a container. Creates a new instance from an image with the specified configuration. Example: docker container run --name web -p 8080:80 -d nginx. Main flags: -d (detach), -it (interactive TTY), --name, -p (ports), -v (volumes), -e (env), --network, --restart, --memory, --cpus. Flag order matters: global → run-specific → image → command. If image not found locally, automatically performs docker pull. For background execution use -d, for interactive access -it
docker container create Create container Create a container without starting it. Useful for configuring settings before starting, testing images, creating scripts. Example: docker container create --name mycontainer -v /data:/data nginx. Container can be started later: docker container start mycontainer. Returns container ID. Can inspect config: docker container inspect mycontainer. Useful in CI/CD for creating base images with configured volumes and networks
docker container start Start container Start a previously created or stopped container. Example: docker container start mycontainer — normal start, docker container start -a mycontainer — with output attached, docker container start -i mycontainer — interactive start. --attach flag attaches stdout/stderr, --interactive — stdin. Can start multiple containers: docker container start c1 c2 c3. For automatic start on system boot, use --restart when creating the container
docker container stop Stop container Stop container by sending SIGTERM signal. Container gets time for graceful shutdown (default 10 seconds, then SIGKILL). Example: docker container stop mycontainer, docker container stop -t 30 mycontainer — 30 seconds for shutdown. --time flag sets timeout. Can stop multiple: docker container stop $(docker container ls -q). After stop the container remains — use docker rm to remove. In production, always use stop instead of kill
docker container restart Restart container Restart a container: stop + start. Useful for applying configuration changes without removing the container. Example: docker container restart mycontainer, docker container restart -t 30 mycontainer. --time flag sets timeout for graceful shutdown. Can restart multiple: docker container restart $(docker container ls -q --filter "name=web"). When used with --restart=always or --restart=unless-stopped, the container automatically restarts on failures
docker container rm Remove container Remove a container. Container must be stopped (or use -f). Example: docker container rm mycontainer, docker container rm -f mycontainer — force removal. Flags: -f (force), -v (remove volumes), --link (remove link). Can remove multiple: docker container rm c1 c2 c3. To clean all stopped containers: docker container prune. Warning: deletion is irreversible — all data outside volumes will be lost
docker container exec Execute command Execute a command inside a running container. Useful for debugging, launching additional processes, running scripts. Example: docker container exec -it mycontainer bash — interactive session, docker container exec mycontainer ls -la /app — execute command. Flags: -i (stdin), -t (TTY), -u (user), --env, --workdir. For background processes without -it: docker container exec mycontainer touch /tmp/file.txt. Can execute any command installed in the image
docker container logs Container logs View container logs. Outputs container stdout/stderr. Example: docker container logs mycontainer — recent logs, docker container logs -f mycontainer — follow mode (tail -f), docker container logs --tail 100 mycontainer — last 100 lines. Flags: -f (follow), --tail (number of lines), --since (time), --timestamps (timestamps). To view logs with error: docker container logs mycontainer 2>&1 | grep -i error. For containers with --restart=always, logs are stored in /var/lib/docker/containers/
docker container top Running processes List of container processes. Analog of ps aux inside the container. Example: docker container top mycontainer. Output: PID, PPID, USER, CMD. Useful for monitoring container resources and detecting unusual processes. Flags depend on OS: Unix — -l (packages), Windows — -l (libraries). Alternative for detailed info: docker container stats mycontainer or docker exec mycontainer ps aux
docker container stats Resource usage Monitor CPU/RAM usage of containers in real-time. Example: docker container stats — all containers, docker container stats mycontainer — one container, docker container stats --no-stream — one-time output. Shows: CONTAINER, CPU %, MEM USAGE/LIMIT, NET I/O, BLOCK I/O, PIDs. For monitoring in script: docker container stats --no-stream --format "{{.Name}}: {{.CPUPerc}}". Shows network and block I/O. Useful for identifying bottlenecks and optimizing resources
docker container cp Copy files Copy files between host and container. Example: docker container cp mycontainer:/app/config.yml ./config.yml — from container, docker container cp ./file.txt mycontainer:/tmp/ — into container. Flags: -a (archive mode), -L (follow symlinks). When copying a directory: docker container cp ./dir mycontainer:/tmp/. To create archive inside: docker container cp mycontainer:/app .. Works with stopped containers. To copy files from image (before creating container), use docker create + docker cp + docker rm
docker container rename Rename container Rename a container. Useful for changing the name without recreating the container. Example: docker container rename old_name new_name. Container retains all configuration, IP address (in network), volumes. Cannot rename to an existing name. Works with both running and stopped containers. Alternative in docker-compose: name or container_name in yaml. Does not affect container hostname (set via --hostname)
docker container pause Pause container Pause a container using cgroups freezer. All container processes are paused at their current state. Example: docker container pause mycontainer. Useful for creating consistent snapshots, temporary pause without data loss. To resume: docker container unpause mycontainer. Cannot execute commands in a paused container (exec does not work). Data in filesystem and memory is saved at the moment of pause. Alternative: kill -STOP inside container
docker container unpause Unpause container Resume a paused container. All processes continue execution from the pause point. Example: docker container unpause mycontainer. Container resumes using resources as if it was never paused. Exact pause time = resume time (no execution loss). Can only resume previously paused containers
docker container kill Kill container Forcefully terminate a container. Sends SIGKILL signal (default) to container processes. Example: docker container kill mycontainer, docker container kill -s SIGINT mycontainer — send SIGINT. --signal flag allows selecting a signal: SIGINT, SIGTERM, SIGKILL, etc. Unlike stop — no graceful shutdown, container terminates instantly. Use only when stop did not help. May result in data loss or filesystem corruption
docker container wait Wait container Wait for container to exit. Blocks execution until container exits and returns the exit code. Example: docker container wait mycontainer — waits and returns exit code. Can wait for multiple: docker container wait c1 c2 c3. Useful in scripts for synchronization: docker run --rm myimage & CID=$!; docker wait $CID; echo "Exit: $?". Used in Docker Compose for depends_on logic. Container can be running or created
docker container prune Remove stopped containers Remove all stopped containers. Safe — removes only containers with Exited or Dead status. Example: docker container prune — with confirmation, docker container prune -f — without confirmation. --filter flag for filtering: docker container prune --filter "until=24h" — remove containers stopped 24h ago. Does not remove containers with attached volumes (by default). Alternative: docker rm $(docker ps -aq --filter "status=exited"). Recommended for regular cleanup

docker run — Main Parameters

Parameter Name Description
-d, --detach Detached mode Run container in the background (detached). Returns container ID to stdout immediately after start. Container continues working after closing the terminal. Example: docker run -d --name web nginx. Without -d, container runs in foreground and blocks the terminal. To manage detached container: docker logs -f for logs, docker attach to connect. Does not work with --rm in some Docker versions. For monitoring: docker stats
-it Interactive terminal Interactive TTY mode. Combination of -i (interactive — opens stdin) + -t (tty — allocates pseudo-terminal). Allows interacting with the container as with a regular shell. Example: docker run -it ubuntu bash — interactive bash inside container, docker run -it alpine — sh without argument. To disable log output without -d: -i. To connect to running container: docker exec -it mycontainer bash. Without -t, there will be no color output and terminal work
--name <name> Container name Named container instead of random ID. Name is used for references in Docker Compose and network, for convenient management. Example: docker run --name my-web -d nginx, docker stop my-web. Name must be unique — cannot create a container with an existing name. To check: docker ps --filter "name=my-web". Can be changed: docker rename. In docker-compose, name is determined by service automatically. Names cannot contain / and must start with a letter or symbol
-p <host-ip:host-port:container-port>, --publish <host-ip:host-port:container-port> Port mapping Forward ports from host to container. Allows making a service inside the container accessible from outside. Example: -p 8080:80 — access to container port 80 via host port 8080, -p 127.0.0.1:8080:80 — local access only. Syntax: [-p ip:hostPort:containerPort | hostPort:containerPort]. Supported protocols: -p 8080:80/tcp, -p 53:53/udp. Multiple ports: -p 8080:80 -p 8443:443. Issues: port may be in use (netstat -tulpn), permissions (<1024)
-P Publish all ports Auto-publish all EXPOSE ports from Dockerfile on random host ports. Useful for testing and temporary access. Example: docker run -P myapp, then check: docker port mycontainer. Each port is assigned a random high port. If Dockerfile has EXPOSE 80 443, both will be mapped. To check: docker inspect --format '{{range $p, $_ in .Config.ExposedPorts}}{{$p}} {{end}}' container. Port may conflict — if in use, another is assigned
-v <source>:<destination>[:ro], --volume <source>:<destination>[:ro] Mount volume Mount host path/volume into container. Data persists after container removal. Types: named volume, bind mount, tmpfs. Examples: -v data:/var/lib/data (named volume — auto-created), -v ~/.ssh:/root/.ssh:ro (bind mount with read-only), -v /host/path:/container/path (bind mount). Flags: :ro (read-only), :Z (SELinux), :z (SELinux shared). Bind mount is OS-dependent, named volume is portable. Bind mount data may require correct permissions (UID/GID)
--mount type=<bind|volume|tmpfs>,src=<name>,dst=<path> Advanced mount Modern mount syntax. More readable and reliable than -v. Types: bind (host path), volume (named volume), tmpfs. Examples: --mount type=volume,src=data,dst=/var/lib/data — named volume, --mount type=bind,src=/etc/ssl,dst=/etc/ssl,readonly — bind mount, --mount type=tmpfs,dst=/tmp,tmp-size=50M — tmpfs. Flags: readonly, volumeopt=key=value for volume options. Separates source and destination — allows creating volume without host path. Harder to read with many mounts
-e <KEY>=<VALUE>, --env <KEY>=<VALUE> Environment variable Pass env variables into the container. Overrides ENV from Dockerfile. Example: -e DB_HOST=postgres -e DB_PORT=5432. Can pass variables from host: -e $(printenv | grep DB_). --env-file flag loads from file. Important for application configuration without rebuilding the image. Variables are available inside as regular environment variables. Do not use for passwords in the command (visible in ps) — use --env-file or secrets. Supports typing via int/float conversion in the application
--env-file <path> Environment file Load env variables from a file. Each line of the file: KEY=VALUE or KEY (taken from host). Convenient for storing sensitive data and large configurations. Example: --env-file .env, --env-file config/database.env. File format: DB_HOST=postgres, DB_PORT=5432, # comment. .env files are usually included in .dockerignore. Priority: -e > --env-file > Dockerfile ENV. Variables from file override system environment variables
--restart <policy> Restart policy Container restart policy after stopping. Values: no (never, default), on-failure[:max-retries] (on error), always (always), unless-stopped (always except manual stop). Example: --restart unless-stopped — automatically restarts except manual stop. --restart on-failure:5 — maximum 5 attempts. Important for production — ensures fault tolerance. Works on host reboot. Does not work with --rm. Check: docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' container. In docker-compose: restart: always
--network <network> Network selection Connect to Docker network. Types: bridge (default), host (shared with host), none (no network), name of custom network. Example: --network my-net, --network host (no port needed), --network none (isolated). For container communication, use custom networks — DNS name = service name. Containers on default bridge cannot resolve each other's names. For multi-host: --network=overlay in swarm. Alternative: --network-alias for additional names
--ip <IP> Static IP Static IP address for container. Works only with custom bridge network (not default bridge). Example: --ip 172.20.0.100 --network my-net. IP must belong to the network subnet. If IP is in use — error. Useful for applications requiring a fixed IP (licensing, firewalls). Check: docker inspect --format '{{.NetworkSettings.Networks.my-net.IPAddress}}' container. By default, Docker assigns a random IP from the pool
--hostname <name> Hostname Container hostname. Sets the hostname inside the container. Affects hostname command and /etc/hostname. Example: --hostname myserver. By default, uses container ID (first 12 characters). Useful for applications that use hostname for identification. Changes only the internal hostname — not DNS in the network. In docker-compose: determined by hostname. To change in running container: docker exec hostname newname
--dns <IP> DNS server DNS server inside the container. Overrides DNS from Docker daemon config. Example: --dns 8.8.8.8 --dns 8.8.4.4 — Google DNS, --dns 1.1.1.1 — Cloudflare DNS. Can specify up to 3 DNS servers. Useful for internal DNS (CoreDNS, BIND). Check: docker exec container cat /etc/resolv.conf. For Docker network search: --dns-search example.com. If DNS is not configured, uses host DNS (/etc/resolv.conf). Works only when creating the container
--memory <size> Memory limit RAM limit for the container. Supported suffixes: b, k, m, g. Example: --memory 512m, --memory 2g, --memory 1024k. Without limit — full access to host RAM. If exceeded, container may be killed by OOM killer. For swap: --memory-swap (must be ≥ --memory). For compatibility: --oom-kill-disable (not recommended). Check: docker stats. For production: always set --memory for stability. In swarm: deploy.resources.reservations.memory
--cpus <count> CPU limit CPU resource limit for the container. Example: --cpus 1.5 — 1.5 cores, --cpus 4 — 4 cores. By default, container uses all available CPU. Value can be fractional for fine-tuning. For limiting specific cores: --cpuset-cpus "0,1". Check: docker stats, docker top. In docker-compose: cpus: 1.5. Works with cgroups v1/v2. Alternative: --cpu-shares (relative weight)
--privileged Privileged mode Elevated privileges: container gets access to all host devices, disables security restrictions (AppArmor, seccomp, capabilities). Use only for special cases (Docker-in-Docker, debugging). Example: docker run --privileged myimage. Security: container can become root on the host. For limited privileges: --cap-add instead. In swarm: privileged: true in service config. Always evaluate risks of use
--user <UID>[:<GID>] User inside container Run as a specific UID/GID instead of UID 0 (root by default). Example: --user 1000:1000, --user nobody. Useful for security and accessing mounted volumes with correct permissions. If not specified — uses image (Dockerfile USER). Check: docker exec id. In docker-compose: user: "1000:1000". For images without USER directive — default is root
--workdir <path> Working directory Working directory inside the container. Overrides WORKDIR from Dockerfile. Example: --workdir /app. Analog of cd at container start. All relative paths in the command will be from workdir. Useful for organizing file structure. In docker-compose: workdir: /app. Cannot be used in ENTRYPOINT — used when running the command. Checks directory existence
--rm Auto remove Automatically remove container after stopping. Convenient for one-time tasks. Example: docker run --rm myimage command. Does not work with -d and -it together — container will be removed immediately. Useful in CI/CD and scripts: docker run --rm postgres:15 psql -h db -c "SELECT 1". Container does not appear in docker ps -a. To save results, use volumes. After --rm, container can be inspected only during execution
--platform <os/arch[/variant]> Target platform Multi-arch platform for building/running on a specific architecture. Example: --platform linux/amd64, --platform linux/arm64. Useful for cross-platform development and emulation. When pull/build determines image architecture. For list of available: docker buildx ls --drivers. Error on incompatibility: No matching manifest. In CI: --platform to check on different architectures. Also: DOCKER_DEFAULT_PLATFORM environment variable
--health-cmd <command> Healthcheck command Command for checking container health. Returns 0 = healthy, 1 = unhealthy. Example: --health-cmd "curl -f http://localhost/ || exit 1", --health-cmd "pg_isready". Checks start after --health-interval. Status can be checked: docker inspect --format '{{.State.Health.Status}}' container. By default disabled. For Dockerfile: HEALTHCHECK CMD curl -f http://localhost/ || exit 1. Useful in swarm and docker-compose for automatic restart
--health-interval <duration> Healthcheck interval Healthcheck interval. Example: --health-interval 30s, --health-interval 5m. Also: --health-timeout (timeout for each check), --health-retries (retries for unhealthy). By default 0s (disabled). Full example: --health-cmd "curl -f http://localhost/" --health-interval 30s --health-timeout 10s --health-retries 3. In docker-compose: healthcheck: { test, interval, timeout, retries }
--entrypoint <command> Override entrypoint Replace ENTRYPOINT from Dockerfile. Useful for running the container with a different primary command. Example: --entrypoint bash to run in bash instead of image command, --entrypoint "" — clear entrypoint. In docker-compose: entrypoint: /bin/bash. Entry point + CMD = full startup command. Override only entry point, CMD from image is preserved. To clear CMD: --entrypoint "" --command "new command". Entry point runs as PID 1

Docker Image Commands

Command Name Description
docker image ls List images List of all local images. Flags: -a (all layers, including intermediate), --filter (by label, digest, creator), --format (table/raw/go-template), --no-trunc. Example: docker image ls — main images, docker image ls -a — all, docker image ls --filter "dangling=true" — dangling images. Output: REPOSITORY, TAG, IMAGE ID, CREATED, SIZE. To search for specific: docker image ls --format '{{.Repository}}:{{.Tag}}' | grep nginx. Useful for audit and disk space cleanup
docker image pull Pull image Download image from registry (Docker Hub, private registry). Example: docker image pull nginx — latest tag, docker image pull nginx:1.25 — specific version, docker image pull registry.example.com/myapp:v1. Supports digest: docker image pull nginx@sha256:... for exact version. Flags: --platform (architecture), --all-tags (all tags). On pull, layers are downloaded in parallel. To speed up: configure mirror in /etc/docker/daemon.json. If image already exists — digest is checked, not downloaded again
docker image push Push image Push image to registry. Requires authorization (docker login). Example: docker image push myapp:v1, docker image push registry.example.com/myapp:latest. First create a tag: docker image tag myapp:v1 registry.example.com/myapp:v1. Push uploads layers incrementally — unchanged layers are not re-uploaded. For multi-arch: docker buildx build --push --platform .... Docker Hub rate limiting: 100 pull/6h (anonymous), 200 (authenticated). Private registry requires HTTPS or --insecure-registry
docker image build Build image Build image from Dockerfile. Analog of docker build. Example: docker image build -t myapp:v1 .. Flags: -t (tag), -f (Dockerfile path), --build-arg, --network, --cache-from. By default, looks for Dockerfile in current directory. Result — local image with specified tag. For multi-stage build: --target production. Build cache speeds up repeated builds. For cleanup after: docker image prune. Alternative: docker buildx build for advanced capabilities
docker image rm Remove image Remove image from local system. Example: docker image rm myapp:v1, docker image rm nginx alpine myapp — multiple. Flags: -f (force), --no-prune. Cannot remove image used by running container (use -f). For dangling images: docker image rm $(docker image ls -q --filter "dangling=true"). If image has tagged parents — only tag is removed. For cleanup: docker image prune -a. Removing large images frees significant space
docker image prune Remove unused images Cleanup dangling images (without tags). Without flags, removes only dangling. Example: docker image prune — dangling, docker image prune -a — all unused, docker image prune --all. --filter flag for conditions: docker image prune --filter "until=24h". -f flag without confirmation. Removes images not used by any container. Includes intermediate layers. Use with caution — may be needed for rebuild. Alternative: docker system prune — full cleanup
docker image inspect Inspect image JSON information about image. Shows full configuration: architecture, CMD, Env, Volumes, Created time, etc. Example: docker image inspect nginx — array, docker image inspect --format '{{.Config.Cmd}}' nginx. Useful fields: .Architecture, .Config.ExposedPorts, .ContainerConfig, .RootFS.Layers. For getting ID: docker image inspect --format '{{.Id}}' nginx. For layers: docker image inspect --format '{{.RootFS.Layers}}' nginx. Can be used in scripts for automation
docker image history Image history Layer history of the image. Shows Dockerfile commands that created each layer. Example: docker image history nginx, docker image history --no-trunc nginx. Output: IMAGE, CREATED, CREATED BY, SIZE. Useful for analyzing image size and understanding its build. LARGE layers are visible in SIZE column. For specific layer: docker image history --format '{{.ID}}: {{.CreatedBy}}' nginx. If Dockerfile is not saved — can be recovered from history. Alternative: docker buildx debug for interactive exploration
docker image tag Tag image Create a tag for image. Does not create a copy — only a reference. Example: docker image tag myapp:v1 myapp:latest, docker image tag myapp:v1 registry.example.com/myapp:v1. Syntax: docker image tag SOURCE[:TAG] TARGET[:TAG]. Useful for versioning, moving to registry. Tag can be changed: docker image tag again. To remove: docker image rm target:tag. Tag does not affect image size — this is a lightweight reference
docker image save Save image Export image to tar archive. Useful for transferring between machines without registry. Example: docker image save -o myimage.tar myapp:v1, docker image save myapp:v1 nginx:alpine | gzip > images.tar.gz — multiple images. Flags: -o (output), --output. The resulting tar can be copied and loaded on another machine. Contains all layers, metadata, history. Size = sum of all layers. For compression, use gzip or docker save | gzip. Does not save volumes
docker image load Load image Import image from tar archive. Analog of docker load. Example: docker image load -i myimage.tar, docker image load < myimage.tar. Loads all images from archive. After load, can check: docker image ls. For compressed archive: gzip -d < myimage.tar.gz | docker load. Tags are preserved from archive. Images without tags appear as . Does not replace registry — for CI/CD use registry

Docker Build Commands

Parameter Name Description
docker buildx build BuildKit build Modern BuildKit build with advanced capabilities. Supports multi-arch, cache export, secrets, SSH forwarding. Example: docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest --push .. This is the recommended way to build Docker. Features: parallel layer build, progressive output, GitHub Actions integration. To activate: export DOCKER_BUILDKIT=1. Alternative: docker build (legacy builder). BuildKit uses docker-buildkit daemon for isolation
--platform <os/arch[/variant]> [, <os/arch[/variant]>...] Multi-platform build Build multi-arch images. Example: --platform linux/amd64,linux/arm64. Result — manifest list (multi-arch image). Useful for supporting different architectures in one image. On push, creates a manifest with multiple architectures. Pull without --platform will select host architecture. For configuration: docker buildx create --use builder with support for multiple platforms. Error on incompatible layers. In GitHub Actions: --platform linux/amd64,linux/arm64
--push Push after build Push image to registry immediately after build. Analog of docker buildx build --push. Example: docker buildx build --platform linux/amd64 -t myapp:latest --push .. Useful in CI/CD — one command for build + push. Requires docker login. Without --push, image remains local. For multiple tags: -t v1.0 -t latest --push. Push goes layer by layer — unchanged layers are not re-uploaded. For debug: remove --push and check locally
--load Load into local daemon Load image locally after build. For buildx, loads only the current platform (unlike --push with multi-arch). Example: docker buildx build --load -t myapp:latest .. Useful when need image locally without separate docker image save/load. Loads into standard Docker daemon. Faster than --push + pull. For multi-arch + local: use --load with one platform
--cache-from type=<inline|registry|local>,ref=<ref> Build cache source Use build cache from another image. Speeds up build by reusing previous layers. Example: --cache-from type=registry,ref=myapp:cache, --cache-from type=inline. Types: inline (in image manifest), registry (remote image), local (local directory). Useful in CI for caching between runs. Works with --cache-to for full cycle. Cache can be viewed: docker buildx du. Without cache — full rebuild
--cache-to type=<inline|registry>,dest=<dest> Export build cache Export build cache for reuse. Example: --cache-to type=inline,dest=myapp:cache, --cache-to type=registry,dest=registry.example.com/myapp:cache. Writes cache to image manifest or registry. Works with --cache-from for full cycle. Useful for optimizing CI/CD. After export, cache is included in next build. Size depends on Dockerfile. Without --cache-to, cache is lost after build
--target <stage-name> Multi-stage target Build specific stage in multi-stage Dockerfile. Allows building only the needed part. Example: --target production — builds only final stage, --target dev — development stage. In Dockerfile: FROM base AS builder, FROM production. Useful for reducing final image (build in one stage, copy to another). Without --target, last stage is built. In CI: --target production for optimization
--build-arg <KEY>=<VALUE> Build arguments ARG variables for Dockerfile. Overrides ARG from Dockerfile during build. Example: --build-arg NODE_ENV=production --build-arg API_URL=https://api.com. In Dockerfile: ARG NODE_ENV, ENV NODE_ENV=$NODE_ENV. Can specify multiple: --build-arg KEY1=val1 --build-arg KEY2=val2. Variables are not saved in image (unlike ENV). To check: docker image inspect --format '{{.ContainerConfig.Environment}}'. Empty ARG: --build-arg KEY=
--secret id=<id>,src=<file> Build secrets Secret BuildKit variables for secure transfer of sensitive data. Does not end up in image layers. Example: --secret id=npmrc,src=.npmrc. In Dockerfile: RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret. Secret file is not visible in docker image history. Supports: id (identifier), src (file), env (variable). In CI: docker buildx build --secret id=token,env=TOKEN .. Alternative: Docker Configs in swarm
--ssh [<default>|<name>=<socket>] SSH forwarding SSH forwarding during build for accessing private repositories. Example: --ssh default uses host SSH-agent, --ssh mykey=/path/to/key. In Dockerfile: RUN --mount=type=ssh git clone git@github.com:user/repo.git. Useful for cloning private repos without tokens in image. Works with DOCKER_BUILDKIT=1. For GitHub: ssh-add before build. Without --ssh, Git over SSH does not work
-f <path>, --file <path> Dockerfile path Path to Dockerfile. Allows using non-standard names or locations. Example: -f Dockerfile.prod, -f ./dev/Dockerfile, -f /absolute/path/Dockerfile. By default, looks for Dockerfile in context root. Supports stdin: cat Dockerfile | docker build -f - .. In docker-compose: dockerfile: Dockerfile.prod. Can use for different environments: Dockerfile.dev, Dockerfile.test. When specifying a directory, looks for Dockerfile inside
-t <name>, --tag <name> Image tag Tag generated image. Can specify multiple tags. Example: -t myapp:v1.0 -t myapp:latest. Format: [registry/]repository[:tag]. Examples: -t nginx:1.25, -t registry.example.com/myapp:v1. Tags can contain: letters, digits, ._, -. Without tag — latest by default. To remove: docker rmi tag. In CI: use semantic versioning -t 1.0.0 -t 1.0 -t 1 -t latest

Docker Volume Commands

Command Name Description
docker volume ls List volumes List of all volumes. Shows DRIVER (local, rancher, etc) and NAME. --filter driver=local flag for filtering, --format for formatting. Example: docker volume ls — all, docker volume ls --filter dangling=true — unused. Output: DRIVER, VOLUME NAME. For count: docker volume ls -q | wc -l. For search by name: docker volume ls -q | grep data. By default, all volumes use local driver. Custom drivers: docker volume create --driver local
docker volume create Create volume Create volume for persistent data storage. Example: docker volume create mydata, docker volume create --opt "label=extra" mydata. Flags: --driver (driver), --opt (options), --label. Volume is created in /var/lib/docker/volumes/. After creation: docker run -v mydata:/data myimage. For HTTPS/SSH drivers: --driver. Not auto-deleted — must be created manually. In docker-compose: volumes are created automatically
docker volume inspect Inspect volume Volume information: mountpoint, driver, options, labels. Example: docker volume inspect mydata — JSON. Useful fields: .Mountpoint (path on host), .Labels, .Options. For mountpoint: docker volume inspect --format '{{.Mountpoint}}' mydata. Useful for mounting on host or transferring data. Also: docker inspect --format '{{.Mounts[0].Destination}}' container for container. In production, use for managing storage
docker volume rm Remove volume Remove volume. Volume must not be used by containers. Example: docker volume rm mydata, docker volume rm v1 v2. Flags: -f (force). If volume is in use — error. For removing used: docker rm -v container + docker volume rm. Alternative: docker volume prune. Warning: deletion is irreversible — all data is lost. Use docker inspect for verification
docker volume prune Remove unused volumes Cleanup unused volumes (not used by any container). Example: docker volume prune — with confirmation, docker volume prune -f — without. --filter flag for conditions. Useful for freeing space. Removes only volumes with unused status. Does not remove volumes used by swarm services. To remove all: docker volume prune --all. Before removing, check: docker volume ls --filter dangling=true

Docker Network Commands

Command Name Description
docker network ls List networks List of all networks. Includes built-in (bridge, host, none) and custom. Flags: --filter (driver, scope), --format. Example: docker network ls — all, docker network ls --filter driver=bridge. Output: NETWORK ID, NAME, DRIVER, SCOPE (local/swarm). Built-in: bridge (default), host (shared namespace), none (no network). Custom: docker network create. Scope: local (single host), swarm (multi-host overlay)
docker network create Create network Create network for isolating and communicating containers. Example: docker network create --driver bridge my-net, docker network create --subnet=172.20.0.0/16 --ip-range=172.20.5.0/24 my-net. Drivers: bridge (default), overlay (swarm/multi-host), macvlan (MAC-based), host, none. Flags: --subnet, --gateway, --ip-range, --opt, --label. Containers in one network can resolve each other's names by service/container name. For swarm: --scope=swarm
docker network inspect Inspect network Network information: subnets, gateways, connected containers, drivers. Example: docker network inspect my-net — JSON. Useful fields: .IPAM.Config (subnets), .Containers (connected). For IP of specific container: docker network inspect --format '{{range $k, $v := .Containers}}{{if eq $v.Name "mycontainer"}}{{$v.IPv4Address}}{{end}}{{end}}' my-net. For debug: docker network inspect bridge — built-in network. In swarm: docker network inspect --format '{{.Scope}}' net
docker network connect Connect container Connect container to network. Example: docker network connect my-net mycontainer. Can specify IP: --ip 172.20.0.100, network alias: --alias web. Container can be connected to multiple networks. After connect, container gains access to other containers in the network by name. To check: docker network inspect my-net. For auto connect: --network when creating container. For swarm services: docker service network
docker network disconnect Disconnect container Disconnect container from network. Example: docker network disconnect my-net mycontainer. Container loses access to other containers in this network. For forced disconnect of running container: --force. Container can be disconnected from all networks except host (impossible). Container remains after disconnect. For auto disconnect: --network when recreating. Useful for isolation and security
docker network rm Remove network Remove network. Network must be empty (no connected containers). Example: docker network rm my-net, docker network rm n1 n2. Flags: -f (force). For removing with connected: docker network disconnect first. Built-in networks (bridge, host, none) cannot be removed. For cleanup: docker network prune. After removal, all network configurations are deleted. Use for cleanup
docker network prune Remove unused networks Cleanup unused networks (not used by any container). Example: docker network prune — with confirmation, docker network prune -f — without. Removes custom networks. Does not remove built-in (bridge, host, none). --filter flag for conditions. Useful for cleanup after docker-compose down. Alternative: docker-compose down --rmi all. Before removing: docker network ls --filter dangling=true

Docker Compose Commands

Command Name Description
docker compose up Start compose stack Start compose services from docker-compose.yml. Example: docker compose up — create + start, docker compose up -d — detached, docker compose up --build — rebuild. Creates containers, networks, volumes per configuration. By default uses docker-compose.yml. Flags: -d, --build, --scale, --no-deps, --force-recreate. On compose file change — auto-recreates. For creating resources: docker compose up --create-only. In CI/CD: docker compose up -d
docker compose down Stop compose stack Stop compose stack. Stops and removes containers, networks. Example: docker compose down, docker compose down -v — with volumes, docker compose down --rmi all — remove images. Flags: -v (volumes), --rmi (local images), --remove-orphans (orphan containers). By default, removes everything except volumes (if not specified). In production: docker compose down -v for full cleanup. To keep volumes: docker compose down without -v
docker compose ps Compose containers List of compose containers with status. Example: docker compose ps, docker compose ps -q — only IDs. Shows: NAME, COMMAND, STATUS, PORTS. Useful for monitoring services. Flags: -q (quiet), --services (list services), --all (all containers). For filtering: docker compose ps --filter "status=running". Analog of docker ps --filter "label=com.docker.compose.project=...". In CI: docker compose ps -q | xargs docker logs
docker compose logs Compose logs Logs of compose services. Example: docker compose logs — all, docker compose logs -f web — follow, docker compose logs --tail 100 db. Flags: -f (follow), --tail, --since, --timestamps, --no-color. For debug: docker compose logs --tail 1000 web | grep error. Logs of all services: docker compose logs | grep -i error. In CI: docker compose logs --tail 50 to save in artifacts. For disabling color: --no-color
docker compose exec Execute command Execute command inside running service container. Example: docker compose exec web bash, docker compose exec --user www-data web ls. Flags: -u (user), --workdir, --env. Unlike docker run --rm — container is preserved. Useful for debugging, launching maintenance. Analog: docker exec with container name. For service without running: docker compose run. Can execute: docker compose exec db psql -U postgres
docker compose build Build services Build compose services. Example: docker compose build — all, docker compose build web — service, docker compose build --no-cache. Flags: --no-cache, --parallel, --pull, --push. Builds images before up. For rebuild only changed: docker compose up --build. In CI: docker compose build --pull for fresh base images. For multi-arch: docker compose build --platform linux/amd64,linux/arm64. Alternative: docker compose up -d --build
docker compose pull Pull services Pull images for compose services. Example: docker compose pull — all, docker compose pull web. Flags: --ignore-buildable, --include-deps, --parallel. Useful in CI before up for fresh images. Analog: docker pull for each service. With --ignore-buildable — only external images. With --include-deps — pull dependencies. To check versions: docker compose pull --dry-run (if supported)
docker compose push Push services Push images for compose services. Example: docker compose push, docker compose push --ignore-buildable. Flags: --ignore-buildable, --include-deps. Push all images to registry. By default, push all. With --ignore-buildable — only images built by compose. In CI: docker compose push after docker compose build. Requires docker login. For multi-arch: use docker buildx
docker compose restart Restart services Restart compose services. Example: docker compose restart, docker compose restart web. Flags: -t (timeout), --no-deps. Restarts containers without changing config. Useful for applying changes. Analog: docker compose stop && docker compose start. For force: docker compose kill && docker compose start. In production: docker compose restart -t 30 for graceful
docker compose stop Stop services Stop compose services. Example: docker compose stop, docker compose stop web. Flags: -t (timeout). Stops containers but does not remove them. Containers remain — can start with docker compose start. Analog: docker compose up -d --no-recreate (stops but does not remove). For full removal: docker compose down. In CI: docker compose stop before docker compose down
docker compose start Start services Start compose services. Example: docker compose start, docker compose start web. Flags: --attach, --interactive. Starts previously stopped containers. Containers must be created (docker compose up or docker compose create). Analog: docker start $(docker compose ps -q). Useful for recovery after docker compose down with volumes preserved. Does not create new resources
docker compose rm Remove services Remove compose containers. Example: docker compose rm — with confirmation, docker compose rm -f — force. Flags: -f, -v (volumes), -s (stop). Removes containers but not volumes/images. Useful for cleanup. Analog: docker rm $(docker compose ps -q). To remove volumes: docker compose down -v. Does not remove networks. In CI: docker compose rm -f for cleanup
docker compose config Validate config Validate compose config for correctness. Outputs combined configuration. --verbose flag for detailed check. Example: docker compose config — validation + output YAML, docker compose config --quiet — only validation (exit 0 or 1). Useful in CI for checking configuration before deploy. Alternatives: docker-compose config (legacy), docker compose up --dry-run. Validation includes: syntax, types, references, resource limits. For JSON output: docker compose config --format json
docker compose images List images List of images used by compose. Example: docker compose images. Shows: IMAGE, ID, CREATED, SIZE. Useful for auditing used images. Flags: -q (quiet). In CI: docker compose images --format table for reports. Alternative: docker compose ps --format "{{.Image}}" for running. For all services: docker compose ps -a --format "{{.Image}}"
docker compose top Running processes Processes of compose services. Example: docker compose top, docker compose top web. Analog of docker top for each service. Shows PID, PPID, USER, CMD. Useful for monitoring and debugging. Flags: -l (Unix), -l (Windows). For all services: docker compose top | head -50. In CI: docker compose top --format json (if supported). Alternative: docker compose exec web ps aux
docker compose events Compose events Compose events stream. Example: docker compose events, docker compose events --filter "service=web". Analog of docker events for compose. Shows events: create, start, stop, die, pause, unpause. Useful for monitoring and automation. Flags: --filter, --since, --until. In CI: docker compose events | jq -r '.Status' | sort | uniq for analysis. For debug: docker compose events --format json

Docker System Commands

Command Name Description
docker system df Disk usage Disk usage by Docker: table with images, volumes, build cache, containers. Analog of df -h for Docker. Example: docker system df — table, docker system df -v — detailed. Output: TYPE, TOTAL, ACTIVE, SIZE, RECLAIMABLE. For cleanup: docker system prune. For specific types: docker system df --type image. Useful for monitoring disk space. In CI: docker system df --format table for reports. For analysis: docker system df -v | grep RECLAIMABLE
docker system prune Cleanup Docker Cleanup unused objects. Example: docker system prune — containers/networks/images, docker system prune -a — includes images, docker system prune --volumes — includes volumes. Flags: -a (all), --volumes, -f (without confirmation). Deletion: dangling images, stopped containers, unused networks, build cache. With -a — all images without containers. With --volumes — all unused volumes. Alternatives: docker container prune, docker image prune, docker volume prune. In CI: docker system prune -af --volumes after tests
docker system info System info Detailed information about Docker system: driver, storage, daemon config. Analog of docker info. Example: docker system info. Output: Server Version, Storage Driver, Security Options, Operating System, Architecture, CPU, Memory, Docker Root Dir. Useful for diagnosing configuration issues. For checking drivers: docker system info --format '{{.Driver}}'. In CI: docker system info for report. Alternative: docker info (also works)
docker system events Events stream Stream of Docker events. Example: docker system events, docker system events --filter 'type=container'. Analog of docker events. Shows events: container, image, network, volume, daemon. Flags: --filter, --since, --until. In CI: docker system events | jq -r '.Status' | sort | uniq for analysis. For monitoring: docker system events --format json. Alternative: docker events (also works)

Docker Swarm Commands

Command Name Description
docker swarm init Initialize swarm Create swarm cluster on the current node. Example: docker swarm init — auto-detect, docker swarm init --advertise-addr 10.0.0.5. First manager node. After init: docker swarm join-token manager/worker to add nodes. Manager nodes store cluster state. For production: 3 or 5 manager nodes for HA. After init: docker node ls — will show this node. Workers can be added: docker swarm join with token. Manager nodes store cluster state. For production: 3 or 5 manager nodes for HA. After init: docker node ls — will show this node. Worker nodes can be added: docker swarm join with token. Not initialized on Docker Desktop by default
docker swarm join Join swarm Connect node to swarm cluster. Example: docker swarm join --token manager-ip:2377. Token can be obtained: docker swarm join-token worker/manager. On manager node, will be added as worker. On worker node — as worker. Port 2377 (TCP) must be open. After join: docker node ls — check status. For manager join: docker swarm join --token . Node must have access to Docker API. Alternative: docker swarm join without token (if admin has configured auto-approve)
docker swarm leave Leave swarm Exit from swarm. Example: docker swarm leave — worker, docker swarm leave --force — manager. Manager node is removed from cluster. Worker node is disconnected. After leave, node becomes standalone. For forced leave (network issues): docker swarm leave --force. If this is the last manager — cluster is destroyed. Worker node can leave without force. For cleanup: docker swarm leave --force && docker system prune -a. After leave, all services on the node are stopped
docker service create Create service Create swarm service. Example: docker service create --name web --replicas 3 -p 8080:80 nginx. Creates distributed service with specified number of replicas. Flags: --name, --replicas, -p, --network, --mount, --env, --constraint, --update-parallelism. Service — abstraction over containers. Swarm automatically balances and scales. For rollback: docker service update --rollback. In production: always --replicas ≥ 2 for HA. Alternative: docker stack deploy with YAML
docker service ls List services List of all swarm services. --filter flag for filtering. Example: docker service ls — all, docker service ls --filter "name=web". Output: ID, NAME, MODE, REPLICAS, IMAGE, PORTS. Useful for monitoring services. For checking status: docker service ls --filter "replicas=1/3" (mismatched replicas). For JSON: docker service ls --format json. In CI: docker service ls | grep web | awk '{print $2}'. For inspect one: docker service inspect web
docker service scale Scale service Scale service. Example: docker service scale web=5 — 5 replicas, docker service scale web=2 db=3. Scale up/down in real-time. Swarm automatically adds/removes containers. For auto-scaling: use docker auto-scale or external tools. For rollback: docker service scale web=3. In production: scale depends on load. Monitoring: docker service ls. For horizontal scaling: --replicas N when creating. Alternative: docker service update --replicas N
docker service update Update service Rolling update service. Example: docker service update --image nginx:1.25 web, docker service update --replicas 5 web. Updates image, parameters, constraints. By default, rolling update with --update-parallelism 1 and --update-delay 30s. For rollback: docker service update --rollback web. Flags: --image, --replicas, --env, --constraint. For zero-downtime: --update-parallelism 1 --update-delay 10s --update-order stop-first. In CI/CD: docker service update --image newimage service
docker node ls List nodes List of all swarm nodes. --filter role=<manager|worker> flag for filtering. Example: docker node ls — all, docker node ls --filter role=manager. Output: ID, HOSTNAME, STATUS, AVAILABILITY, MANAGER STATUS, ENGINE VERSION. Useful for monitoring cluster. For checking status: docker node ls --filter "manager status=reachability=reachable". For drainage: docker node update --availability drain node-id. For promotion/demotion: docker node promote/demote node-id. In production: 3-5 manager for HA
docker stack deploy Deploy stack Deploy stack file (docker-compose.yml). Example: docker stack deploy -c docker-compose.yml myapp. Creates/updates all resources per configuration. Stack — group of related services. After deploy: docker stack ls, docker stack services myapp. Flags: -c (compose file), --resolve-image (always/changed/never). In CI/CD: docker stack deploy --prune -c docker-compose.yml myapp. For rollback: docker stack deploy with previous version. Alternative: docker service create manually
docker stack rm Remove stack Remove stack and all its resources. Example: docker stack rm myapp. Removes services, networks, volumes (if configured). After rm, stack does not appear in docker stack ls. For removing volumes: docker volume prune. For cleanup: docker stack rm myapp && docker system prune -a. In CI: docker stack rm myapp after tests. Alternative: docker stack deploy --prune for partial cleanup

Docker Environment Variables

Variable Name Description
DOCKER_HOST Docker daemon socket Docker daemon address. Default is unix:///var/run/docker.sock. For TCP: tcp://10.0.0.5:2376. Affects all Docker commands. For SSH: ssh://user@host. For TLS: tls://host:port. Set: export DOCKER_HOST=tcp://10.0.0.5:2376. Check: echo $DOCKER_HOST. Not recommended in CI — use contexts. For Docker Desktop: DOCKER_HOST=unix://$HOME/.docker/run/docker.sock (macOS). Alternative: docker --host flag
DOCKER_CONTEXT Docker context Active context. Switches between different daemons. Default value: default. Example: export DOCKER_CONTEXT=prod. Useful for switching environments without flag. Contexts stored in ~/.docker/contexts/. List: docker context ls. To create: docker context create prod --docker host=tcp://10.0.0.5:2376. Alternative: docker --context flag. In CI: DOCKER_CONTEXT for automation
DOCKER_CONFIG Config directory Path to config directory. Contains config.json, certificates, contexts. Default: ~/.docker. Example: export DOCKER_CONFIG=/opt/docker-config. Contents: config.json (auth), tls/ (certs), contexts/. For isolation: mkdir -p ~/.docker-dev && export DOCKER_CONFIG=~/.docker-dev. On config change: new commands use the new config. For backup: tar czf docker-config.tar.gz ~/.docker. Do not store sensitive data without encryption
DOCKER_TLS_VERIFY TLS verification TLS verification. Set to 1 to enable TLS. Empty value — disable. Example: export DOCKER_TLS_VERIFY=1. Affects DOCKER_HOST with TLS. For auto: docker-machine env (sets DOCKER_*) for Docker Machine. When working with Docker Desktop: TLS is enabled by default. For private registry: ensure ca.pem is available. Disabling TLS (DOCKER_TLS_VERIFY=) is not recommended in production
DOCKER_CERT_PATH TLS cert path Path to TLS certificates. Contains ca.pem, cert.pem, key.pem. Default: $DOCKER_CONFIG/tls. Example: export DOCKER_CERT_PATH=/etc/docker/tls. For Docker Machine: docker-machine env sets automatically. On TLS errors: check that all three files exist. For generation: docker-machine generate-certs (in newer versions). For production: use self-signed CA or Let's Encrypt. Files must have 600 permissions for keys
DOCKER_DEFAULT_PLATFORM Default platform Default platform for pull/build/run. Example: linux/amd64. Overrides auto-detection of architecture. Useful when host and target platforms differ. Example: export DOCKER_DEFAULT_PLATFORM=linux/arm64 — always pull arm64 on x86. Works with pull, build, run. To check: docker info --format '{{.Architecture}}'. In CI: DOCKER_DEFAULT_PLATFORM for cross-platform builds. Alternative: --platform flag. Error on platform incompatibility
DOCKER_API_VERSION API version Override API version of Docker Engine. Useful for compatibility with older CLI. Example: 1.41. Format: M.m (major.minor). Newer Docker requires API 1.41+. For older daemon: export DOCKER_API_VERSION=1.40. Check supported API: docker version --format '{{.Server.APIVersion}}'. Alternative: DOCKER_API_VERSION in daemon.json. In CI: DOCKER_API_VERSION for compatibility with old Docker versions. Too old version may not support new commands
BUILDKIT_PROGRESS BuildKit output BuildKit output format. Values: plain (detailed), tty (progress bar). For CI: plain. Example: export BUILDKIT_PROGRESS=plain. In terminal: tty shows progress bar. In CI/CD: plain for logging. Alternative: DOCKER_BUILDKIT=1 (enables BuildKit). With plain, see each build step. With tty — nice progress. For debug: export BUILDKIT_PROGRESS=plain. In GitHub Actions: automatically plain