Docker comes with a multitude of commands that serve different purposes, building container images, pulling images from a registry, running containers in production environments, and integrating with orchestration tools like Docker Swarm. In this article, we will walk you through what Docker commands are, why they matter, and a cheat sheet list of essential Docker commands to help you in your DevOps journey or day-to-day container operations.
Table of Contents:
What Are Docker Commands?
Docker commands are individual instructions that are executed from the Docker Command Line Interface( CLI) for managing the complete life cycle of Docker containers and Docker components such as images, networks, and volumes in a Dockerized environment.
Why Docker Commands Matter for Developers
With Docker commands, developers can use containers effectively throughout the software development lifecycle, promoting consistency while scaling across environments. They simplify CI/CD pipelines, increase resource isolation, and provide the ability to version container images. Troubleshooting becomes quick and efficient with resources such as Docker logs and docker exec.
1. Docker Container Commands
The Docker management commands are general commands used to get system information or help from Docker CLI.
1.1 Starting and Managing Containers
1.1.1. docker installation- Install Docker on Linux:
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
1.1.2. docker help – To get help from Docker.
docker --help
You can also use –help on all subcommands.
1.1.3. docker -d – To start the Docker daemon.
docker -d
docker info
1.1.5. docker version – To display the current installed Docker version.
docker version
1.1.6. docker run – Create a Container
docker run [OPTIONS] <image_name>
Creates and starts a new container from the specified image.
docker run -d -p 8080:80 nginx
1.1.7. docker stop and docker start – Manage Container Lifecycle
docker stop <container_name_or_id>
docker start <container_name_or_id>
docker stop gracefully stops a running container.
docker start restarts a previously stopped container.
docker stop my_container
docker start my_container
1.2. Viewing and Removing Containers
Viewing and removing containers helps monitor active instances and clean up stopped ones to manage system resources efficiently.
1.2.1. docker ps – List Running Containers
docker ps
Displays a list of currently running containers along with their IDs, names, status, ports, and more.
1.2.2. docker rm – Remove Stopped Containers
docker rm <container_name_or_id>
Deletes one or more stopped containers from the system.
docker rm my_stopped_container
Remove all stopped containers:
docker container prune
2. Docker Images Commands
2.1 Building Docker Images
2.1.1. docker build Syntax and Example
docker build [OPTIONS] -t <image_name>:<tag> <path>
This command builds a Docker image from a Dockerfile located at the specified path and tags it with a name.
docker build -t myapp:1.0 .
(-t) specifies the image name and optional tag (myapp:1.0)
(.) refers to the current directory where the Dockerfile is located
This creates a reusable image that can be used to run containers.
2.2 Pulling and Pushing Docker Images
2.2.1. docker pull – Fetch from Docker Hub
docker pull <image_name>:<tag>
Downloads an image from a remote registry like Docker Hub to your local machine.
docker pull node:18-alpine
This pulls the lightweight Node.js 18 Alpine image.
2.2.2. docker push – Push to a Registry
docker push <image_name>:<tag>
Uploads a locally built image to a container registry (like Docker Hub or a private registry). You must be logged in and the image must be tagged appropriately.
docker tag myapp:1.0 username/myapp:1.0
docker push username/myapp:1.0
This shares your image with others or allows deployment from a registry.
2.3 Listing and Removing Docker Images
2.3.1. docker images – List Images
docker images
Displays a list of all locally available Docker images, showing repository names, tags, image IDs, and sizes.
Example output:
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 5ad3bd0e67a3 3 days ago 142MB
2.3.2. docker rmi – Remove Images
docker rmi <image_name_or_id>
Deletes one or more Docker images from your local system to free up space.
docker rmi myapp:1.0
To force removal even if the image is in use:
docker rmi -f <image_id>
3. Managing Docker Volumes
Managing Docker volumes enables persistent data storage and sharing between containers, essential for stateful applications.
3.1 Creating and Listing Volumes
3.1.1. docker volume create – Create a Volume
docker volume create <volume_name>
3.1.2. Creates a new Docker volume for persistent data storage.
docker volume ls
Lists all Docker volumes on the host system.
3.2 Inspecting and Pruning Volumes
3.2.1. docker volume inspect – Get Volume Details
docker volume inspect <volume_name>
Provides detailed information about a specific volume, such as its mount point, driver, and container associations.
docker volume inspect my_volume
3.2.2. docker volume prune – Remove Unused Volumes
docker volume prune
Removes all unused volumes that are not associated with any containers, helping free up disk space.
Note: This command will prompt for confirmation before removing volumes.
4. Docker Networking Commands
Docker networking commands help create, inspect, connect, and manage container networks to enable seamless communication and isolation.
4.1 Creating and Inspecting Networks
Creating and inspecting networks lets you set up and view detailed information about Docker networks for container communication and management.
4.1.1. docker network create – Create a Network
Create a network:
docker network create <network_name>
4.1.2. docker network inspect – View Network Details
The command for inspecting a Docker network and viewing its details is:
docker network inspect <network_name_or_id>
This command provides detailed information about the network, including the connected containers, network settings, and IP addresses.
4.1.3. docker network connect – Connect a container to a network:
docker network connect <network_name> <container_id>
4.2 Connecting and Disconnecting Containers
Connecting and disconnecting containers allows you to dynamically manage which Docker networks a container is attached to, enabling or isolating inter-container communication as needed.
4.2.1. docker network connect – Attach a Container
To attach a running container to an existing network:
docker network connect <network_name> <container_name_or_id>
4.2.2. docker network disconnect – Detach a Container
To detach a running container from a network:
docker network disconnect <network_name> <container_name_or_id>
5. Docker Compose Commands
Docker Compose commands simplify defining, running, and managing multi-container Docker applications with easy YAML configurations.
Here are the commands and explanations for Docker Compose service management:
5.1 Starting and Stopping Services
Starting and stopping services controls the lifecycle of multi-container applications defined in Docker Compose files.
5.1.1. docker-compose up – Start Services
docker-compose up
Starts and runs all the services defined in the docker-compose.yml file.
Use -d to run them in detached mode (in the background).
docker-compose up -d
5.1.2. docker-compose down – Stop and Remove Containers
docker-compose down
Stops and removes all the containers, networks, and default volumes created by docker-compose up
.
5.2 Running Commands Inside Compose Containers
Here’s a concise explanation with the command for running commands inside a running Compose service container:
5.2.1. docker-compose exec – Run Commands Inside a Service
docker-compose exec <service_name> <command>
This command lets you execute arbitrary commands inside a running container of a specific service defined in your docker-compose.yml
.
To open a bash shell inside a running web service container:
docker-compose exec web bash
6. Docker Swarm Commands
Docker Swarm commands manage clustering, orchestration, and scaling of containerized applications across multiple Docker hosts.
6.1 Initializing Docker Swarm
Initializing Docker Swarm sets up a Docker host as a manager node to create and manage a Swarm cluster.
6.1.1. docker swarm init – Start Swarm Mode
docker swarm init
Initializes the current Docker host as a Swarm manager, enabling it to orchestrate a cluster of nodes and deploy services.
Example Output:
You’ll receive a docker swarm join
token to add worker or manager nodes to the Swarm.
6.2 Managing Services and Stacks in Swarm
Managing services and stacks in Swarm enables deployment, scaling, and updating of multi-container applications across the cluster.
6.2.1. docker service create – Create a New Service
docker service create --name <service_name> <image>
Creates and starts a new service in Docker Swarm.
docker service create --name webserver -p 80:80 nginx
This deploys an Nginx service with port 80 exposed.
6.2.2. docker stack deploy – Deploy a Stack
docker stack deploy -c <compose_file> <stack_name>
Deploys a full application stack using a Docker Compose file in Swarm mode.
docker stack deploy -c docker-compose.yml mystack
This launches all services defined in docker-compose.yml
under the stack name mystack
.
7. Debugging and Monitoring with Docker Commands
Debugging and monitoring with Docker commands helps track container health, view logs, and analyze resource usage for troubleshooting.
7.1 Viewing Logs and Stats
Viewing logs and stats lets you monitor container output and performance metrics in real time for effective troubleshooting.
7.1.1. docker logs – Container Logs
docker logs <container_name_or_id>
Displays the log output (stdout and stderr) from a container, useful for debugging.
docker logs my_container
7.1.2. docker stats – Resource Usage Stats
docker stats
Shows real-time CPU, memory, and I/O usage for all running containers.
docker stats my_container
7.2 Executing Commands in Running Containers
Executing commands in running containers allows real-time interaction and debugging inside active Docker environments.
7.2.1. docker exec – Execute Inside a Container
docker exec -it <container_name_or_id> <command>
Runs a command inside a running container. The -it
flags allow interactive terminal access.
docker exec -it my_container bash
For Alpine-based containers (no bash):
docker exec -it my_container sh
8. Docker System Cleanup Commands
Docker system cleanup commands help free up disk space by removing unused containers, images, volumes, and networks.
8.1: Pruning Docker System Objects
Pruning Docker system objects removes all unused containers, images, volumes, and networks to reclaim disk space efficiently.
8.1.1. docker system prune – Clean Up Unused Resources
docker system prune
Removes all unused containers, networks, images (not tagged), and build cache to free up disk space.
docker system prune -f
The -f
flag skips confirmation prompts.
Note: This action is irreversible and can remove data you may still need.
8.2 Removing Unused Containers, Images, and Volumes
Removing unused containers, images, and volumes clears up storage by deleting resources no longer in use or associated with active containers.
8.2.1. docker container prune – Remove Stopped Containers
docker container prune
Deletes all stopped containers to free up system resources.
docker container prune -f
The -f
flag skips the confirmation prompt.
Note: Only containers not currently running will be removed.
8.2.2. docker image prune – Remove Unused Images
docker image prune
Removes dangling (unused and untagged) images from the system to reclaim disk space.
docker image prune -f
The -f
flag skips confirmation.
To remove all unused images (not just dangling ones):
docker image prune -a
Advanced Docker Commands
Advanced Docker commands enable fine-tuned container management, networking, security, and automation for complex workflows.
1. Copying Files Between Containers and Hosts
Copying files between containers and hosts allows seamless data transfer for configuration, backups, and debugging tasks.
1.1. docker cp – Copy Files
docker cp <container_name_or_id>:<source_path> <destination_path>
Copies files or directories from a container to the host or vice versa.
Example (copy from container to host):
docker cp my_container:/app/logs/output.txt ./output.txt
Example (copy from host to container):
docker cp ./input.txt my_container:/app/input.txt
2. Inspecting Containers and Images
Inspecting containers and images provides detailed metadata and configuration information for troubleshooting and management.
docker inspect <container_name_or_id>
Provides detailed JSON output about a container or image, including configuration, state, networking, and more.
docker inspect my_container
You can use --format
to filter specific information, like IP address:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' my_container
3. Committing Changes to Containers
Committing changes to containers creates a new image from a modified container’s current state for reuse or distribution.
3.1. docker commit – Create an Image from a Container
docker commit <container_name_or_id> <image_name>:<tag>
Creates a new Docker image from a container’s current state, preserving its changes.
docker commit my_container myapp:latest
This creates a new image myapp:latest
based on my_container
.
Security Commands in Docker
Security commands in Docker help manage access, secrets, and enforce container isolation to protect applications and data.
1. Managing Docker Secrets
Managing Docker secrets securely stores and controls sensitive data like passwords and API keys for containers.
1.2. docker secret – Create and Manage Secrets
docker secret <subcommand> <options>
Manages sensitive data such as passwords, certificates, and keys for use in Docker Swarm services.
Create a secret:
docker secret create <secret_name> <file_path>
Example:
docker secret create my_secret /path/to/secret.txt
List secrets:
docker secret ls
Remove a secret:
docker secret rm <secret_name>
2. Working with Docker Configurations
Working with Docker configurations simplifies managing application settings and environment variables for containerized services.
2.1. docker config – Create and Use Configs
docker config <subcommand> <options>
Manages non-sensitive configuration data (e.g., application settings) used by services in Docker Swarm.
Create a config:
docker config create <config_name> <file_path>
Example:
docker config create my_config /path/to/config.conf
List configs:
docker config ls
Remove a config:
docker config rm <config_name>
Conclusion
Docker commands help to complete common tasks such as creating, running, stopping, and removing containers and images, managing networks, managing volumes, inspecting logs, accessing container shells, etc. These are operations that developers and operators use to manage and automate container workflows.
Master Docker Commands for Faster Container Management- FAQs
1. How to give a command in Docker?
To run multiple commands inside a container using docker exec , you can use the -c flag followed by the commands you want to execute. The commands should be separated by semicolons. This command will execute command1, command2 , and command3 sequentially inside the container.
2. What is a Docker volume?
A Docker volume is a persistent storage mechanism for Docker containers, designed to store and share data independently of the container’s lifecycle. It allows data to be saved even when containers are stopped, removed, or updated, and can be shared between multiple containers. Volumes are managed by Docker and stored in a directory on the host machine, typically /var/lib/docker/volumes on Linux systems.