Common Docker Commands
Effectively managing containers is crucial for modern application deployment and infrastructure. This reference provides an in-depth overview of…
Effectively managing containers is crucial for modern application deployment and infrastructure. This reference provides an in-depth overview of fundamental Docker commands, focusing on practical usage patterns for network engineers, sysadmins, cloud consultants, and developers. We will cover container lifecycle management, image operations, volume handling, network inspection, and resource monitoring, complete with command syntax and real-world considerations.
Container Lifecycle Management
Understanding how to start, stop, pause, and remove containers is foundational.
docker run: Create and Start Containers
The docker run command creates a new container and executes a command within it. It's often the first command used to bring an application online.
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
-d,--detach: Run container in background (detached mode).-p: Publish a container's port(s) to the host. E.g.,: -p 8080:80.--name: Assign a specific name to the container for easier reference.-v: Bind mount a volume. E.g.,: -v /opt/appdata:/var/www/html.--restart: Restart policy (e.g.,always,on-failure,no).--env: Set environment variables inside the container.--network: Connect the container to a specific Docker network.
Example: Run an Nginx container, exposing port 8080 on the host, named my-web-server, and restarting always.
docker run -d -p 8080:80 --name my-web-server --restart always nginx:latest
docker ps: List Containers
This command lists running containers and their essential details.
docker ps [OPTIONS]
-a,--all: Show all containers (default shows only running).-s,--size: Display total file sizes.-f,--filter: Filter output based on conditions (e.g.,status=exited,name=my-app).--format: Pretty-print containers using Go template.
Example: List all containers, including exited ones, showing their size.
docker ps -a -s
docker stop, docker start, docker restart: Manage Container State
These commands allow graceful termination, initiation, and re-initiation of containers.
docker stop my-web-server # Sends SIGTERM, then SIGKILL after a timeout (default 10s)
docker start my-web-server # Starts an exited container
docker restart my-web-server # Stops and then starts a container
docker rm: Remove Containers
Use this to delete one or more containers. A container must be stopped before it can be removed unless -f is used.
docker rm [OPTIONS] CONTAINER [CONTAINER...]
-f,--force: Force removal of a running container (sends SIGKILL).-v,--volumes: Remove anonymous volumes associated with the container.
Example: Remove an exited container named my-old-app and its associated anonymous volumes.
docker rm -v my-old-app
Container Interaction and Inspection
Accessing container logs, executing commands, and inspecting configurations are vital for debugging and monitoring.
docker logs: View Container Logs
Retrieves logs from a container, useful for troubleshooting applications.
docker logs [OPTIONS] CONTAINER
-f,--follow: Follow log output in real-time.--tail: Output the specified number of lines from the end of the logs.--since: Show logs since a specific timestamp (e.g.,2023-01-01T00:00:00Zor10mfor 10 minutes ago).--timestamps: Show timestamps in the logs.
Example: Tail the logs of my-web-server, showing timestamps.
docker logs -f --timestamps my-web-server
docker exec: Execute Commands in a Running Container
This command allows you to run a command inside a running container, essential for debugging or administrative tasks.
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
-i,--interactive: Keep STDIN open even if not attached.-t,--tty: Allocate a pseudo-TTY. Often used with-ifor interactive shell sessions.-u,--user: Username or UID (and optionally groupname or GID) to use.
Example: Get an interactive bash shell in the my-web-server container.
docker exec -it my-web-server bash
If bash is not available, try sh: docker exec -it my-web-server sh.
docker inspect: Get Detailed Information
Provides a wealth of low-level information about Docker objects (containers, images, volumes, networks) in JSON format.
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
--format: Format the output using Go template. Useful for extracting specific fields.
Example: Inspect the IP address of my-web-server.
docker inspect -f '{{.NetworkSettings.IPAddress}}' my-web-server
Image Management
Images are the blueprints for containers. Efficiently managing them saves disk space and simplifies deployments.
docker pull: Download Images
Downloads an image or a repository from a registry (default is Docker Hub).
docker pull [OPTIONS] NAME[:TAG|@DIGEST]
Example: Pull the latest Ubuntu image.
docker pull ubuntu:latest
docker images: List Images
Lists local Docker images.
docker images [OPTIONS]
-a,--all: Show all images (default hides intermediate images).-q,--quiet: Only show numeric IDs.-f,--filter: Filter output (e.g.,dangling=true).
docker build: Build Images from Dockerfile
Constructs a new image using instructions from a Dockerfile.
docker build [OPTIONS] PATH | URL | -
-t,--tag: Name and optionally a tag in the 'name:tag' format.--no-cache: Do not use cache when building the image.--pull: Always attempt to pull a newer version of the base images.
Example: Build an image from the current directory, tagging it as my-custom-app:v1.0.
docker build -t my-custom-app:v1.0 .
docker rmi: Remove Images
Deletes one or more images from the local store. Images in use by containers cannot be removed.
docker rmi [OPTIONS] IMAGE [IMAGE...]
-f,--force: Force removal of the image.
Example: Remove the my-custom-app:v1.0 image.
docker rmi my-custom-app:v1.0
docker image prune: Clean Up Unused Images
Removes all dangling images (images that are not tagged and not referenced by any container).
docker image prune [OPTIONS]
-a,--all: Remove all unused images, not just dangling ones (will remove images that have no associated containers, even if they have tags).-f,--force: Do not prompt for confirmation.
Example: Remove all unused images without confirmation.
docker image prune -a -f
Volume Management
Volumes provide persistent storage for Docker containers, decoupling data from the container's lifecycle.
docker volume create: Create a Volume
docker volume create [OPTIONS] [VOLUME]
Example: Create a named volume for a database.
docker volume create db_data
docker volume ls: List Volumes
docker volume ls [OPTIONS]
docker volume inspect: Get Volume Details
docker volume inspect db_data
docker volume rm: Remove a Volume
Removes one or more volumes. A volume must not be in use by any container to be removed.
docker volume rm [OPTIONS] VOLUME [VOLUME...]
docker volume prune: Clean Up Unused Volumes
Removes all unused local volumes.
docker volume prune [OPTIONS]
Example: Remove all unused volumes interactively.
docker volume prune
Network Management
Docker's networking capabilities allow containers to communicate with each other and the outside world.
docker network create: Create a Custom Network
docker network create [OPTIONS] NETWORK
--driver: Specify network driver (default isbridge, others includeoverlayfor Swarm).--subnet,--gateway: Define IP addressing for the network.
Example: Create a bridge network named my-app-network.
docker network create my-app-network
docker network ls: List Networks
docker network ls
docker network inspect: Inspect Network Details
View detailed configuration for a Docker network, including connected containers.
docker network inspect my-app-network
docker network connect: Connect Container to Network
Connects an existing container to a custom network.
docker network connect my-app-network my-web-server
docker network disconnect: Disconnect Container from Network
docker network disconnect my-app-network my-web-server
Resource Monitoring and Utilities
Monitoring container resource usage is critical for performance tuning and troubleshooting.
docker stats: Display Live Resource Usage
Provides a live stream of resource usage statistics for running containers (CPU, memory, network I/O, disk I/O).
docker stats [OPTIONS] [CONTAINER...]
--no-stream: Do not stream stats and just get the current data.--format: Pretty-print stats using Go template.
Example: Monitor CPU and memory usage for all running containers.
docker stats
docker top: View Container Processes
Shows the running processes within a container.
docker top my-web-server
docker system prune: Clean Up All Unused Docker Data
This powerful command removes all stopped containers, all dangling images, all unused networks, and all unused build cache. Use with caution.
docker system prune [OPTIONS]
-a,--all: Remove all unused images, not just dangling ones.--volumes: Remove all unused volumes.-f,--force: Do not prompt for confirmation.
Example: Clean up everything, including volumes, without prompt.
docker system prune -a --volumes -f
Docker Compose
For multi-container applications, Docker Compose simplifies defining and running Docker applications using a YAML file.
docker compose up: Create and Start Services
Builds, (re)creates, starts, and attaches to containers for a service.
docker compose up [OPTIONS] [SERVICE...]
-d,--detach: Run containers in the background.--build: Rebuild images before starting containers.--force-recreate: Recreate containers even if their configuration hasn't changed.--remove-orphans: Remove containers for services not defined in the Compose file.
Example: Start services defined in docker-compose.yml in detached mode, rebuilding images if necessary.
docker compose up -d --build
Note: For Docker versions 1.27 and older, the command was often docker-compose up (with a hyphen).
docker compose down: Stop and Remove Services
Stops and removes containers, networks, and volumes created by up.
docker compose down [OPTIONS]
-v,--volumes: Remove named volumes declared in thevolumessection of the Compose file.--rmi: Remove images.allremoves all images;localremoves only images without a custom tag.
Example: Stop and remove all services and their associated volumes.
docker compose down -v
Common Pitfalls
- Forgetting
-dindocker run: Your container will run in the foreground, tying up your terminal. If you exit, the container might stop. - Port Conflicts: Trying to map a container port to an already used host port will result in an error like
Error starting userland proxy: listen tcp 0.0.0.0:8080: bind: address already in use. - Permissions Issues with Volumes: When bind-mounting host directories (
-v /host/path:/container/path), ensure the process inside the container has appropriate read/write permissions on the host path. The UID/GID inside the container might not match the host. - Dangling Images/Volumes: Over time, images without tags or volumes not associated with any container can consume significant disk space. Regularly use
docker image prune -aanddocker volume prune. - Misunderstanding
docker rm -fvs.docker stop:docker stopattempts a graceful shutdown (SIGTERM), whiledocker rm -fordocker killimmediately terminates (SIGKILL) a running container, potentially leading to data corruption. - Not using Custom Networks: Relying solely on the default
bridgenetwork can lead to hostname resolution issues and less organized communication for multi-container applications. Custom bridge networks provide better isolation and DNS resolution by service name.