G: Welcome, fellow developers and tech enthusiasts! 👋 Are you ready to unlock the true power of Docker from the command line? The Docker CLI (Command Line Interface) is your indispensable tool for building, running, and managing your containerized applications. Whether you’re a beginner just dipping your toes into containerization or an experienced user looking to sharpen your skills, this comprehensive guide will take you from the absolute essentials to advanced command-line wizardry.
We’ll explore the most vital Docker commands, complete with clear explanations, practical examples, and tips & tricks gathered from the latest best practices. Let’s dive in! 🚀
🌟 Why Master the Docker CLI?
The Docker CLI is the direct interface to the Docker Engine. While GUIs and orchestration tools exist, the command line offers:
- Precision and Control: Fine-tune every aspect of your containers and images.
- Automation: Script repetitive tasks for CI/CD pipelines.
- Troubleshooting: Diagnose issues by inspecting containers, logs, and networks.
- Efficiency: Quickly manage resources and clean up your Docker environment.
🚀 Section 1: The Absolute Essentials – Getting Started with Docker
Let’s begin with the fundamental commands you’ll use daily. Think of these as your Docker survival kit! 🛠️
1.1 docker version
& docker info
– Checking Your Setup
Before anything else, let’s verify Docker is installed and running correctly.
-
docker version
: Displays Docker client and server version information.docker version
Example Output:
Client: Docker Engine - Community Version: 24.0.5 ... Server: Docker Engine - Community Engine: Version: 24.0.5 ...
👉 This tells you about your local Docker client and the Docker daemon (server) it’s communicating with.
-
docker info
: Provides a detailed summary of your Docker environment, including images, containers, storage drivers, and more.docker info
Example Output:
Containers: 3 Running: 1 Paused: 0 Stopped: 2 Images: 15 Server Version: 24.0.5 Storage Driver: overlay2 ...
👉 Great for a quick overview of your Docker system’s health and resources.
1.2 docker pull
– Fetching Images from Docker Hub
Images are the blueprints for your containers. docker pull
downloads an image from a registry (like Docker Hub) to your local machine.
- Syntax:
docker pull [OPTIONS] NAME[:TAG|@DIGEST]
- Example: Pulling the latest Ubuntu image.
docker pull ubuntu:latest
Explanation:
ubuntu
is the image name, andlatest
is the tag (version). If you omit the tag,latest
is assumed.docker pull alpine # equivalent to docker pull alpine:latest
👉 Always specify a tag for production to ensure reproducibility! E.g.,
node:18-alpine
instead ofnode:latest
.
1.3 docker run
– Launching Your First Container
This is arguably the most important command. docker run
creates and starts a new container from a specified image.
-
Syntax:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
-
Example 1: Interactive Shell
docker run -it ubuntu:latest bash
Explanation:
-i
: (interactive) Keeps STDIN open even if not attached.-t
: (tty) Allocates a pseudo-TTY. Together,-it
allows you to interact with the container’s shell.ubuntu:latest
: The image to use.bash
: The command to run inside the container (starts a bash shell).- You’ll see your prompt change, indicating you’re now inside the container! Type
exit
to leave.
-
Example 2: Detached Mode & Port Mapping Let’s run a simple Nginx web server in the background.
docker run -d -p 8080:80 --name my-nginx nginx:latest
Explanation:
-d
: (detached) Runs the container in the background. You’ll get the container ID back.-p 8080:80
: (publish) Maps port 8080 on your host to port 80 inside the container. Now you can access Nginx viahttp://localhost:8080
in your browser! 🌐--name my-nginx
: Assigns a readable name to your container. This is much easier to remember than a random ID!nginx:latest
: The Nginx web server image.
1.4 docker ps
– Listing Running Containers
docker ps
shows you all currently running containers.
- Syntax:
docker ps [OPTIONS]
- Example:
docker ps
Example Output (for
my-nginx
):CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a1b2c3d4e5f6 nginx:latest "nginx -g 'daemon of…" 2 minutes ago Up 2 minutes 0.0.0.0:8080->80/tcp my-nginx
docker ps -a
: Shows all containers, including stopped ones. Very useful for seeing what’s accumulated! 🗑️docker ps -s
: Shows the size of each container.
1.5 docker stop
, docker start
, docker restart
– Managing Container Lifecycle
These commands control the running state of your containers. Use either the container ID or the name.
docker stop my-nginx
: Gracefully stops themy-nginx
container.docker start my-nginx
: Starts a stoppedmy-nginx
container.docker restart my-nginx
: Stops and then starts themy-nginx
container.
1.6 docker rm
– Removing Containers
Once you’re done with a container, it’s good practice to remove it to free up resources.
- Syntax:
docker rm [OPTIONS] CONTAINER [CONTAINER...]
- Example:
docker stop my-nginx # Stop it first if it's running docker rm my-nginx
👉 Tip: You can force remove a running container with
docker rm -f my-nginx
, but it’s generally better to stop it first. 👉 Mass Removal:docker rm $(docker ps -aq)
will remove all stopped containers. Be careful!
1.7 docker rmi
– Removing Images
When you no longer need an image, remove it to save disk space.
- Syntax:
docker rmi [OPTIONS] IMAGE [IMAGE...]
- Example:
docker rmi ubuntu:latest
Note: You can’t remove an image if it’s being used by a container (even a stopped one). You’ll need to remove the container(s) first. 👉 Force Remove:
docker rmi -f ubuntu:latest
will forcefully remove the image, even if containers are using it. Use with caution!
1.8 docker logs
– Viewing Container Output
Containers often output valuable information to their standard output (stdout) and standard error (stderr). docker logs
lets you see it.
- Syntax:
docker logs [OPTIONS] CONTAINER
- Example: Viewing logs for our Nginx server.
docker logs my-nginx
docker logs -f my-nginx
: Follows the logs in real-time (liketail -f
). Excellent for debugging! 🐛docker logs --tail 10 my-nginx
: Shows only the last 10 lines of logs.
1.9 docker exec
– Running Commands Inside a Container
docker exec
allows you to run a new command inside an already running container. This is incredibly useful for debugging or performing administrative tasks.
- Syntax:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
- Example 1: Open a Bash Shell
docker exec -it my-nginx bash
Explanation: This will open a new bash shell inside your running Nginx container, allowing you to explore its filesystem, install packages, etc. Type
exit
to return to your host terminal. - Example 2: Check Nginx Version
docker exec my-nginx nginx -v
Explanation: Runs the
nginx -v
command inside the container and prints its output to your host terminal.
🧱 Section 2: Managing Images – Build, Tag, and Share
Images are the foundation of Docker. Let’s look at commands to build your own, list them, and push them to a registry.
2.1 docker build
– Creating Your Own Images
You’ll create custom Docker images using a Dockerfile
. This command reads a Dockerfile
and builds an image.
- Syntax:
docker build [OPTIONS] PATH | URL | -
- Example: Assume you have a
Dockerfile
in your current directory:# Dockerfile FROM alpine:latest RUN apk add --no-cache curl CMD ["curl", "https://www.example.com"]
Now, build it:
docker build -t my-custom-app:1.0 .
Explanation:
-t my-custom-app:1.0
: (tag) Tags the image with a name (my-custom-app
) and a version (1.0
)..
: The build context. This tells Docker to look for theDockerfile
in the current directory. The build context is also sent to the Docker daemon.
2.2 docker images
– Listing Local Images
This command shows all images stored on your local machine.
- Syntax:
docker images [OPTIONS] [REPOSITORY]
- Example:
docker images
Example Output:
REPOSITORY TAG IMAGE ID CREATED SIZE my-custom-app 1.0 abcdef123456 5 seconds ago 7.5MB nginx latest ghijkl678901 2 weeks ago 142MB ubuntu latest mnopqrstuvwx 3 weeks ago 77.8MB
docker images -a
: Shows all images, including intermediate ones from multi-stage builds.docker images --digests
: Shows image digests (SHA256 hash).
2.3 docker tag
– Aliasing Images
docker tag
allows you to create an alias (another name and tag) for an existing image. This is particularly useful before pushing an image to a private registry.
- Syntax:
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
- Example: Tagging our custom app for a fictitious registry.
docker tag my-custom-app:1.0 myregistry.com/my-user/my-custom-app:v1.0
Now, if you run
docker images
, you’ll see two entries pointing to the sameIMAGE ID
.
2.4 docker push
– Uploading Images to a Registry
Share your custom images with the world (or your team!) by pushing them to a Docker registry.
- Syntax:
docker push [OPTIONS] NAME[:TAG]
- Example: Pushing the tagged image.
docker push myregistry.com/my-user/my-custom-app:v1.0
Note: You’ll need to
docker login
to the registry first if it’s private.
2.5 docker image prune
– Cleaning Up Dangling Images
Over time, you’ll accumulate “dangling” images – layers that are no longer associated with a tagged image. These take up disk space.
- Syntax:
docker image prune [OPTIONS]
- Example:
docker image prune
Explanation: This will prompt you to confirm removal of dangling images.
docker image prune -a
: Removes all unused images (not just dangling ones). Use with caution!
💾 Section 3: Managing Volumes – Data Persistence
Containers are ephemeral by nature. If a container stops or is removed, any data written inside it is lost. Volumes solve this by persisting data outside the container’s lifecycle.
3.1 docker volume create
– Creating a Named Volume
Named volumes are Docker’s preferred way to persist data. Docker manages their location on the host.
- Syntax:
docker volume create [OPTIONS] VOLUME
- Example:
docker volume create my-app-data
3.2 docker volume ls
– Listing Volumes
See all named volumes on your system.
- Syntax:
docker volume ls [OPTIONS]
- Example:
docker volume ls
Example Output:
DRIVER VOLUME NAME local my-app-data
3.3 docker volume inspect
– Inspecting Volume Details
Get detailed information about a specific volume, including its mount point on the host.
- Syntax:
docker volume inspect [OPTIONS] VOLUME [VOLUME...]
- Example:
docker volume inspect my-app-data
Example Output (excerpt):
[ { "Name": "my-app-data", "Driver": "local", "Mountpoint": "/var/lib/docker/volumes/my-app-data/_data", ... } ]
3.4 docker run
with Volumes – Attaching Data
Now, let’s attach our volume to a container.
-
Syntax (Named Volume):
docker run -v my-app-data:/app/data IMAGE
Example:docker run -d --name my-data-app -v my-app-data:/app/data alpine:latest sh -c "echo 'Hello from volume!' > /app/data/message.txt && tail -f /dev/null"
Explanation: The
my-app-data
volume is mounted inside the container at/app/data
. If you remove and recreate the container, themessage.txt
file will still exist in the volume. -
Syntax (Bind Mount):
docker run -v /host/path:/container/path IMAGE
Example:mkdir ./my-local-data echo "Local file content" > ./my-local-data/local_message.txt docker run -it --name my-bind-app -v $(pwd)/my-local-data:/app/data alpine:latest sh
Now, inside the container,
cat /app/data/local_message.txt
will show “Local file content”. Changes made from inside the container to/app/data
will reflect on your host in./my-local-data
.
3.5 docker volume rm
– Removing Volumes
Be careful when removing volumes, as this permanently deletes the data!
- Syntax:
docker volume rm [OPTIONS] VOLUME [VOLUME...]
- Example:
docker volume rm my-app-data
👉 Force Remove:
docker volume rm -f my-app-data
to remove a volume even if it’s in use. Not recommended unless you know what you’re doing! - Cleanup Dangling Volumes:
docker volume prune
removes all unused local volumes.
🌐 Section 4: Managing Networks – Container Communication
Docker containers can communicate with each other through networks. By default, containers use a bridge
network, but custom networks offer better isolation and name resolution.
4.1 docker network create
– Creating a Custom Network
- Syntax:
docker network create [OPTIONS] NETWORK
- Example: Create a custom bridge network.
docker network create my-app-network
👉 Why custom networks? Containers on the same custom network can resolve each other by name! No need for IP addresses.
4.2 docker network ls
– Listing Networks
- Syntax:
docker network ls [OPTIONS]
- Example:
docker network ls
Example Output:
NETWORK ID NAME DRIVER SCOPE abcde12345 bridge bridge local fghij67890 host host local klmno12345 my-app-network bridge local pqrst67890 none null local
4.3 docker network inspect
– Inspecting Network Details
- Syntax:
docker network inspect [OPTIONS] NETWORK [NETWORK...]
- Example:
docker network inspect my-app-network
Explanation: You’ll see details like connected containers, subnet, gateway, etc.
4.4 docker run
with Networks – Connecting Containers
Let’s run two containers and connect them to our custom network.
- Example:
docker run -d --name web-server --network my-app-network nginx:latest docker run -it --name api-client --network my-app-network alpine/curl sh
Now, from inside the
api-client
container, you can access theweb-server
by its name:# Inside api-client container curl http://web-server
This will successfully fetch the Nginx default page! 🎉
4.5 docker network connect
/ docker network disconnect
– Dynamic Network Changes
You can connect or disconnect running containers from networks.
docker network connect my-app-network existing-container
docker network disconnect my-app-network existing-container
4.6 docker network rm
– Removing Networks
- Syntax:
docker network rm [OPTIONS] NETWORK [NETWORK...]
- Example:
docker network rm my-app-network
Note: You can’t remove a network if containers are still connected to it.
🎩 Section 5: Advanced Docker CLI Tricks & Tips
You’re now proficient with the core commands. Let’s explore some more advanced utilities that can save you time and help with deeper insights.
5.1 docker stats
– Real-time Resource Usage
Monitor CPU, memory, network I/O, and disk I/O for your running containers in real-time.
- Syntax:
docker stats [OPTIONS] [CONTAINER...]
- Example:
docker stats
Example Output (updates every second):
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS a1b2c3d4e5f6 web-server 0.00% 2.169MiB / 7.738GiB 0.03% 1.51kB / 0B 0B / 0B 6
👉 Press
Ctrl+C
to exit.
5.2 docker inspect
– Deep Dive into Docker Objects
Get low-level information about Docker objects (containers, images, volumes, networks) in JSON format. Invaluable for debugging!
- Syntax:
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
- Example: Inspecting our Nginx container.
docker inspect web-server
Explanation: You’ll see a large JSON output containing details like IP address, mounted volumes, environment variables, network settings, and much more. 👉 You can combine this with
grep
orjq
for specific data. E.g.,docker inspect web-server | grep IPAddress
5.3 docker system prune
– The Ultimate Cleanup Tool! 🧹
This command cleans up unused Docker objects: stopped containers, dangling images, unused networks, and dangling build cache.
- Syntax:
docker system prune [OPTIONS]
- Example:
docker system prune
Explanation: This will prompt you to confirm. It’s a great way to reclaim disk space.
docker system prune -a
: Removes all unused images (not just dangling) and all stopped containers. Use with extreme caution as it can remove images you might use later!docker system prune --volumes
: Also removes unused volumes (requires careful consideration as it deletes data!).
5.4 docker top
– Processes Inside a Container
See the processes running inside a specific container, similar to the top
command on Linux.
- Syntax:
docker top CONTAINER [ps OPTIONS]
- Example:
docker top web-server
Example Output:
UID PID PPID C STIME TTY TIME CMD root 1 0 0 10:00 ? 00:00:00 nginx: master process nginx -g daemon off; nginx 6 1 0 10:00 ? 00:00:00 nginx: worker process nginx 7 1 0 10:00 ? 00:00:00 nginx: worker process
5.5 docker cp
– Copying Files Between Host and Container
Move files in and out of your running containers.
- Syntax (Host to Container):
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
- Syntax (Container to Host):
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
- Example 1: Host to Container
echo "New config content" > ./new_config.txt docker cp ./new_config.txt web-server:/etc/nginx/conf.d/new_config.conf
- Example 2: Container to Host
docker cp web-server:/var/log/nginx/access.log ./nginx_access.log
5.6 docker search
– Finding Images on Docker Hub
Search Docker Hub for images directly from your terminal.
- Syntax:
docker search [OPTIONS] TERM
- Example:
docker search wordpress
Example Output:
NAME DESCRIPTION STARS OFFICIAL AUTOMATED wordpress The WordPress content management system 12000 [OK] bitnami/wordpress Bitnami WordPress Docker Image 1000 [OK] ...
📦 Section 6: Introduction to Docker Compose – Multi-Container Applications
While not a docker
command itself, docker-compose
is an essential tool for managing multi-container Docker applications. It allows you to define your entire application stack (web server, database, cache, etc.) in a single YAML file.
6.1 docker-compose.yml
– Defining Your Stack
Here’s a simple docker-compose.yml
for a web app with a database:
# docker-compose.yml
version: '3.8' # Specify the Compose file format version
services:
web:
build: . # Build from Dockerfile in current directory
ports:
- "80:80"
volumes:
- ./app:/var/www/html # Mount local app code into container
depends_on:
- db # Ensure db starts before web
environment:
MYSQL_HOST: db # Env var for web to connect to db
networks:
- my-app-network
db:
image: mysql:8.0 # Use official MySQL image
environment:
MYSQL_ROOT_PASSWORD: supersecretpassword
MYSQL_DATABASE: my_database
volumes:
- db_data:/var/lib/mysql # Persistent data for database
networks:
- my-app-network
volumes:
db_data: # Define the named volume
networks:
my-app-network: # Define the custom network
driver: bridge
6.2 docker-compose up
– Starting Your Application Stack
This command builds, creates, starts, and attaches to containers for all services defined in your docker-compose.yml
.
- Syntax:
docker-compose up [OPTIONS]
- Example:
docker-compose up -d
Explanation:
-d
: Runs the containers in detached mode (background).- Without
-d
, you’ll see logs from all services in your terminal.
6.3 docker-compose down
– Stopping and Removing Your Stack
Stops and removes containers, networks, and (optionally) volumes created by docker-compose up
.
- Syntax:
docker-compose down [OPTIONS]
- Example:
docker-compose down --volumes
Explanation:
--volumes
: Also removes the named volumes (db_data
in our example). Be careful, this deletes your data!
6.4 docker-compose ps
– Listing Compose Services
Similar to docker ps
, but shows containers managed by Docker Compose.
- Syntax:
docker-compose ps [OPTIONS]
- Example:
docker-compose ps
6.5 docker-compose logs
– Viewing All Service Logs
View consolidated logs from all services in your Compose application.
- Syntax:
docker-compose logs [OPTIONS] [SERVICE...]
- Example:
docker-compose logs -f
Explanation:
-f
: Follows the logs in real-time.
6.6 docker-compose exec
– Running Commands in a Service Container
Execute a command inside a running service container.
- Syntax:
docker-compose exec [OPTIONS] SERVICE COMMAND [ARGS...]
- Example: Open a bash shell in the
web
service container.docker-compose exec web bash
🎉 Conclusion: Your Docker CLI Journey Continues!
Congratulations! You’ve navigated through the essential and advanced Docker CLI commands. From pulling images and running containers to managing volumes, networks, and even orchestrating multi-container applications with Docker Compose, you now have a solid foundation to master Docker.
Remember, practice makes perfect! Try out these commands on your own projects. Experiment with different options and scenarios. The Docker documentation is also an excellent resource for deeper dives into specific commands and flags.
What’s next? As your applications grow in complexity, you might explore:
- Docker Swarm: Docker’s native orchestration tool for managing a cluster of Docker hosts.
- Kubernetes: The industry standard for container orchestration at scale.
Keep building, keep learning, and happy containerizing! 🐳✨