G: Are you diving deep into the world of containers, or perhaps looking to sharpen your Docker skills? The Docker Command Line Interface (CLI) is your primary tool for interacting with Docker. While docker
might seem simple at first glance, its commands come packed with a plethora of options that unlock powerful functionalities for managing images, containers, networks, and volumes.
This comprehensive guide will take you on an A-Z journey through the most essential Docker CLI commands, detailing their common options and providing practical examples to supercharge your container orchestration game! Get ready to become a Docker CLI master. πͺ
π Why Master the Docker CLI?
The Docker CLI is more than just a set of commands; it’s the gateway to efficient development, deployment, and management of containerized applications. Understanding its nuances allows you to:
- Debug Effectively: Quickly inspect container states, logs, and network configurations.
- Automate Workflows: Script complex operations for CI/CD pipelines.
- Optimize Resources: Prune unused resources and monitor system performance.
- Troubleshoot Issues: Pinpoint problems with network connectivity, volume mounts, or container execution.
Let’s embark on this detailed exploration! πΊοΈ
π Core Docker Concepts (Quick Recap)
Before we jump into the commands, a brief refresher on the core components you’ll be interacting with:
- Images: π¦ Read-only templates that contain an application and all its dependencies. Think of them as blueprints for containers.
- Containers: πββοΈ Runnable instances of an image. They are isolated environments where your applications run.
- Volumes: πΎ Persistent data storage for Docker containers, allowing data to outlive the container itself.
- Networks: π Enable communication between containers, or between containers and the host machine.
π The A-Z Journey Through Docker CLI Commands
We’ll cover the most frequently used and critical docker
commands. While not every single option can be listed, we’ll focus on the ones that bring the most value and flexibility.
1. docker build
ποΈ – Crafting Your Container Images
This command is your go-to for building Docker images from a Dockerfile
and a “context” (a set of files at a specified path or URL).
-
Syntax:
docker build [OPTIONS] PATH | URL | -
-
Key Options:
--tag
, `-t: `: π·οΈ Name and optionally tag the image. It’s good practice to tag your images. - `–build-arg
= `: π οΈ Set build-time variables. Useful for passing sensitive information or dynamic values during the build process without embedding them in the `Dockerfile`. --no-cache
: π’ Build the image without using cached layers. This forces a fresh build.--file
,-f <path/to/Dockerfile>
: π Specify an alternativeDockerfile
path. Default is./Dockerfile
.
-
Usage Examples:
# 1. Build an image from the current directory, tag it 'my-app:latest' docker build -t my-app:latest . # 2. Build and tag with a specific version docker build -t my-app:v1.0 . # 3. Build with a build argument (e.g., passing a version number) docker build --build-arg APP_VERSION=2.0 -t my-app:v2.0 . # 4. Build without using the cache (useful for troubleshooting or ensuring fresh dependencies) docker build --no-cache -t my-app:dev . # 5. Build using a Dockerfile located in a different directory docker build -f ./dockerfiles/production.Dockerfile -t my-app:prod .
-
Pro Tip: Always include a
.dockerignore
file! It prevents unnecessary files (likenode_modules
,.git
,venv/
) from being sent to the Docker daemon as part of the build context, speeding up your builds and keeping images lean.
2. docker cp
πβ‘οΈπ¦ / π¦β‘οΈπ – Copying Files In and Out
This command allows you to copy files/folders between a container’s filesystem and the host machine’s filesystem.
-
Syntax:
docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH
(Host to Container)docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
(Container to Host)
-
Key Options:
- No commonly used specific options, it mainly relies on source and destination paths.
-
Usage Examples:
# 1. Copy a file from your host to a running container's `/app` directory docker cp ./config.yaml my-web-app:/app/config.yaml # 2. Copy an entire directory from your host to a container docker cp ./data/ my-database:/var/lib/mysql/data/ # 3. Copy a file from a container to your host's current directory docker cp my-web-app:/var/log/nginx/access.log . # 4. Copy a directory from a container to your host docker cp my-database:/etc/mysql/conf.d ./my-mysql-conf/
-
Important: The container must be running for
docker cp
to work reliably.
3. docker exec
π― – Running Commands Inside a Container
docker exec
allows you to execute a command inside a running container. It’s incredibly useful for debugging, inspecting, or performing administrative tasks within a container without restarting it.
-
Syntax:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
-
Key Options:
--interactive
,-i
: π¬ Keep STDIN open even if not attached. Essential for interactive sessions.--tty
,-t
: π₯οΈ Allocate a pseudo-TTY. Often used with-i
to get a proper shell experience. (Thinkdocker exec -it
).--detach
,-d
: πββοΈ Run the command in detached mode (in the background).--user <user|uid>[:<group|gid>]
: π€ Specify the username or UID to run the command as.
-
Usage Examples:
# 1. Get an interactive shell (Bash) inside a running container docker exec -it my-web-app bash # 2. Run a command and exit (e.g., check a file's content) docker exec my-web-app cat /app/index.js # 3. Run a command in the background (detached mode) docker exec -d my-database service mysql restart # 4. Run a command as a specific user (e.g., 'www-data') docker exec -it --user www-data my-web-app ls -la /app
4. docker images
πΌοΈ – Listing Available Images
This command lists the images you have locally stored on your Docker host.
-
Syntax:
docker images [OPTIONS] [REPOSITORY]
-
Key Options:
--all
,-a
: π¦ Show all images, including intermediate images created during multi-stage builds.--quiet
,-q
: π€« Only show numeric IDs. Useful for scripting.--filter
,-f <"key=value">
: π Filter output based on conditions (e.g.,dangling=true
,label=my-label
).--format "{{.ID}}\t{{.Repository}}\t{{.Tag}}"
: π Pretty-print images using Go templates.
-
Usage Examples:
# 1. List all local images docker images # 2. List all images, including intermediate ones docker images -a # 3. List only the IDs of all images docker images -q # 4. Filter for dangling (untagged, unused) images docker images -f "dangling=true" # 5. Filter for images from a specific repository docker images my-app # 6. List images with custom format docker images --format "{{.ID}}\t{{.Repository}}\t{{.Tag}}\t{{.Size}}"
5. docker inspect
π – Deep Dive into Docker Objects
docker inspect
provides detailed low-level information about Docker objects (containers, images, volumes, networks). It outputs a JSON array, making it perfect for scripting and automated parsing.
-
Syntax:
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
-
Key Options:
--format "{{.HostConfig.PortBindings}}"
: π― Format the output using Go templates, allowing you to extract specific fields.
-
Usage Examples:
# 1. Get all details about a running container docker inspect my-web-app # 2. Get all details about a specific image docker inspect nginx:latest # 3. Extract the IP address of a container docker inspect -f '{{.NetworkSettings.IPAddress}}' my-web-app # 4. Extract port bindings for a container docker inspect -f '{{json .NetworkSettings.Ports}}' my-web-app
6. docker logs
π – Retrieving Container Logs
This command fetches the logs of a container. It’s crucial for monitoring your application’s behavior and debugging issues.
-
Syntax:
docker logs [OPTIONS] CONTAINER
-
Key Options:
--follow
,-f
: π Follow log output (liketail -f
).- `–tail
`: π’ Output the specified number of lines from the end of the logs. --since <timestamp|duration>
: π°οΈ Show logs since a specific timestamp or relative duration (e.g.,10m
,1h
).--timestamps
,-t
: β±οΈ Show timestamps in the logs.
-
Usage Examples:
# 1. View all logs for a container docker logs my-web-app # 2. Follow logs in real-time docker logs -f my-web-app # 3. View the last 50 lines of logs docker logs --tail 50 my-web-app # 4. View logs since 1 hour ago with timestamps docker logs --since 1h -t my-web-app
7. docker network
π – Managing Container Networks
The docker network
command manages Docker networks, which enable communication between containers and the host.
-
Syntax:
docker network COMMAND [OPTIONS]
-
Common Subcommands:
ls
: List networks.create
: Create a new network.connect
: Connect a container to a network.disconnect
: Disconnect a container from a network.rm
: Remove one or more networks.prune
: Remove all unused networks.
-
Key Options (for
create
):- `–driver
`: π οΈ Specify the network driver (e.g., `bridge`, `host`, `overlay`). `bridge` is default. - `–subnet
`: π Define a subnet for the network. - `–gateway
`: πͺ Define the gateway for the network.
- `–driver
-
Usage Examples:
# 1. List all available networks docker network ls # 2. Create a new bridge network docker network create --driver bridge my-custom-network # 3. Inspect a network (e.g., 'bridge' network) docker network inspect bridge # 4. Connect a running container to a network docker network connect my-custom-network my-web-app # 5. Disconnect a container from a network docker network disconnect my-custom-network my-web-app # 6. Remove an unused network docker network rm my-custom-network # 7. Remove all unused networks docker network prune
8. docker ps
π – Listing Running Containers
This command lists the currently running Docker containers. It’s often the first command you’ll use to check your Docker environment.
-
Syntax:
docker ps [OPTIONS]
-
Key Options:
--all
,-a
: π Show all containers, including stopped ones.--quiet
,-q
: π€« Only display container IDs. Great for scripting.--filter
,-f <"key=value">
: π Filter output based on conditions (e.g.,status=exited
,name=my-app
).--format "{{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"
: π Pretty-print containers using Go templates.--size
,-s
: π Display total file sizes.
-
Usage Examples:
# 1. List all running containers docker ps # 2. List all containers (running and stopped) docker ps -a # 3. List only the IDs of running containers docker ps -q # 4. Filter containers by name (e.g., containing 'web') docker ps -f "name=web" # 5. Filter for exited containers docker ps -a -f "status=exited" # 6. List containers with custom format docker ps --format "{{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Image}}"
9. docker pull
β¬οΈ – Downloading Images
docker pull
downloads a Docker image from a registry (default is Docker Hub) to your local machine.
-
Syntax:
docker pull [OPTIONS] NAME[:TAG|@DIGEST]
-
Key Options:
- No commonly used options beyond the image name and tag.
-
Usage Examples:
# 1. Pull the latest Nginx image docker pull nginx:latest # 2. Pull a specific version of Ubuntu docker pull ubuntu:22.04 # 3. Pull an image from a private registry (after logging in) docker pull myregistry.com/my-team/my-app:v1.0
10. docker push
β¬οΈ – Uploading Images
docker push
uploads a Docker image from your local machine to a registry (default is Docker Hub). You must be authenticated to push to a private or public repository under your account.
-
Syntax:
docker push [OPTIONS] NAME[:TAG]
-
Key Options:
- No commonly used options beyond the image name and tag.
-
Usage Examples:
# (First, ensure you are logged in: docker login) # 1. Push an image to Docker Hub (must be tagged with your username/repo) docker push your_dockerhub_username/my-app:latest # 2. Push a specific version docker push your_dockerhub_username/my-app:v1.0 # 3. Push to a private registry docker push myregistry.com/my-team/my-app:v2.0
11. docker run
βΆοΈ – The Swiss Army Knife of Docker
This is arguably the most fundamental and versatile command. docker run
creates a new container from a specified image and runs a command in it. It has a vast array of options to configure the container’s environment, networking, volumes, and more.
-
Syntax:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
-
Key Options (a selection of the most common ones):
--detach
,-d
: πͺ Run container in the background (detached mode).--publish
, `-p: `: π Publish container ports to the host. --volume
, `-v: [: ]`: πΎ Mount a host path or named volume into the container. - `–name
`: π Assign a name to the container. Makes it easier to refer to. - `–network
`: π Connect the container to a specific network. --rm
: ποΈ Automatically remove the container when it exits. Great for temporary containers.--interactive
,-i
&--tty
,-t
: π¬π₯οΈ Run container in interactive mode with a pseudo-TTY. Essential for interactive shells (e.g.,docker run -it
).--env
,-e <key=value>
: βοΈ Set environment variables inside the container.--mount type=<bind|volume|tmpfs>,source=<src>,target=<dest>,[options]
: πΎ A more explicit and flexible way to mount (preferred over-v
for complex mounts).- `–restart
`: π Configure a restart policy (e.g., `no`, `on-failure`, `unless-stopped`, `always`).
-
Usage Examples:
# 1. Run a simple Nginx web server in detached mode, mapping port 8080 on host to 80 in container docker run -d -p 8080:80 --name my-nginx nginx:latest # 2. Run an interactive Ubuntu container and get a bash shell docker run -it --rm ubuntu:latest bash # 3. Run a container with a named volume for persistent data docker run -d -p 3306:3306 --name my-db -v my-db-data:/var/lib/mysql mysql:8.0 # 4. Run a container and mount a host directory docker run -d -p 3000:3000 --name my-node-app -v $(pwd):/app node:18-alpine npm start # 5. Run a container with environment variables docker run -d --name my-api -e API_KEY=abc123xyz -p 5000:5000 my-api-image:latest # 6. Run a container and connect to a custom network docker run -d --name my-backend --network my-custom-network my-backend-image:latest # 7. Run a container with a restart policy docker run -d --restart always --name my-always-on-app my-app-image:latest
12. docker rm
ποΈ – Removing Containers
This command removes one or more stopped containers.
-
Syntax:
docker rm [OPTIONS] CONTAINER [CONTAINER...]
-
Key Options:
--force
,-f
: π₯ Force the removal of a running container (sends SIGKILL). Use with caution!--volumes
,-v
: πΎ Remove anonymous volumes associated with the container.
-
Usage Examples:
# 1. Remove a single stopped container docker rm my-old-container # 2. Remove multiple stopped containers docker rm container1 container2 # 3. Force remove a running container (not recommended unless absolutely necessary) docker rm -f my-stuck-container # 4. Remove a container and its associated anonymous volumes docker rm -v my-temp-container # 5. Remove all exited containers (useful for cleanup) docker rm $(docker ps -a -q -f status=exited)
13. docker rmi
ποΈ – Removing Images
This command removes one or more Docker images.
-
Syntax:
docker rmi [OPTIONS] IMAGE [IMAGE...]
-
Key Options:
--force
,-f
: π₯ Force the removal of an image, even if it’s used by a container. Use with caution!--no-prune
: π³ Do not delete untagged parent images.
-
Usage Examples:
# 1. Remove an image by name and tag docker rmi my-app:latest # 2. Remove an image by ID docker rmi a1b2c3d4e5f6 # 3. Force remove an image that is currently in use by a container (be careful!) docker rmi -f old-image:v1 # 4. Remove all dangling images (untagged images not used by any container) docker rmi $(docker images -q -f "dangling=true")
14. docker stop
/ docker start
/ docker restart
ππ’π – Managing Container State
These commands control the lifecycle of your containers.
-
Syntax:
docker stop [OPTIONS] CONTAINER [CONTAINER...]
docker start [OPTIONS] CONTAINER [CONTAINER...]
docker restart [OPTIONS] CONTAINER [CONTAINER...]
-
Key Options (for
stop
andrestart
):--time
, `-t`: β³ Seconds to wait for stop before killing the container (default is 10 seconds).
-
Usage Examples:
# 1. Stop a running container docker stop my-web-app # 2. Start a stopped container docker start my-web-app # 3. Restart a running container docker restart my-web-app # 4. Stop a container, waiting only 3 seconds before killing docker stop -t 3 my-slow-container # 5. Stop all running containers docker stop $(docker ps -q)
15. docker system
π§Ήπ – Managing Docker System Resources
This command group provides utilities for managing your Docker installation and its resources.
-
Syntax:
docker system COMMAND [OPTIONS]
-
Common Subcommands:
df
: π Show Docker disk usage.info
: βΉοΈ Display system-wide information.prune
: π§Ή Remove unused Docker data (containers, images, volumes, networks).
-
Key Options (for
prune
):--all
,-a
: π₯ Remove all unused images not just dangling ones.--volumes
: πΎ Remove all unused volumes.
-
Usage Examples:
# 1. Show disk space used by Docker images, containers, and volumes docker system df # 2. Display detailed Docker system information docker system info # 3. Clean up unused containers, networks, and dangling images (prompt for confirmation) docker system prune # 4. Clean up all unused containers, networks, *all* unused images, and volumes (be careful!) docker system prune -a --volumes
16. docker volume
πΎ – Managing Data Volumes
The docker volume
command manages Docker volumes, which are the preferred mechanism for persisting data generated by and used by Docker containers.
-
Syntax:
docker volume COMMAND [OPTIONS]
-
Common Subcommands:
ls
: List volumes.create
: Create a new volume.inspect
: Display detailed information about a volume.rm
: Remove one or more volumes.prune
: Remove all unused volumes.
-
Key Options (for
create
):- `–name
`: π Specify a name for the volume.
- `–name
-
Usage Examples:
# 1. List all local volumes docker volume ls # 2. Create a named volume docker volume create my-app-data # 3. Inspect a specific volume docker volume inspect my-app-data # 4. Remove an unused volume docker volume rm my-old-data-volume # 5. Remove all unused local volumes docker volume prune
π‘ Beyond the Basics: Pro Tips!
- Aliasing Docker: For frequently used commands, consider creating shell aliases. For example, add
alias d='docker'
to your~/.bashrc
or~/.zshrc
to shorten commands. Then you can used ps
,d run
, etc. docker compose
: While this guide focuses on individualdocker
commands, for multi-container applications,docker compose
is indispensable. It allows you to define and run a multi-container Docker application using a YAML file. Learn it next!.dockerignore
: As mentioned earlier, use this file to exclude files and directories from the build context, making your builds faster and images smaller.- Official Documentation: The Docker official documentation is an excellent, up-to-date resource for every command and option: https://docs.docker.com/engine/reference/commandline/cli/
π Conclusion
You’ve now taken a comprehensive tour of the most critical Docker CLI commands! From building and running containers to managing networks, volumes, and cleaning up your system, these commands are the building blocks of efficient Docker workflows.
Practice these commands regularly, experiment with their options, and soon you’ll find yourself navigating the Docker ecosystem with confidence and speed. Happy containerizing! π§βπ»β¨