Essential Docker Commands: A Guide


Essential Docker Commands: A Guide


Last week, I spent considerable time exploring Docker and typing various commands in the Linux command line. I thought it would be helpful to compile a comprehensive list of Docker commands to share with you. So, here’s the post for you—enjoy your reading!


Introduction

Docker has revolutionized how developers package, distribute, and run applications. With its lightweight containers, Docker makes it possible to ensure that an application runs the same, no matter where it is deployed. However, to leverage Docker’s full potential, you need to be comfortable with the command line. This guide provides a dive into the most useful and commonly used Docker commands, with additional examples using specific flags and parameters.


What is Docker?


Docker is an open-source platform that automates the deployment, scaling, and management of applications through containerization. A container is a lightweight, standalone executable package that includes everything an application needs to run. Docker containers ensure consistent environments from development to production, making it a powerful tool for modern DevOps practices.


The Basics of Docker Commands

Docker commands are crucial for interacting with Docker images, containers, volumes, and networks. Before diving into the specifics, it’s essential to understand how the Docker CLI (Command Line Interface) works.


The Docker CLI is the primary way users interact with Docker. Whether you're creating, starting, stopping, or removing containers, all actions are done through the command line.

Getting Help in Docker

docker --help

Running this command provides a complete list of available Docker commands and options. It’s a useful starting point for anyone new to Docker or someone who needs a refresher.


Docker Commands for Images

Docker images are read-only templates used to create containers. Managing Docker images effectively is essential for developing, testing, and deploying applications. Here are some critical Docker commands for working with images:

1. Pull an Image

docker pull <image-name>

This command downloads an image from a Docker registry (like Docker Hub). For example, to pull the official Python image, you would run:

docker pull python

Additional Parameters:

<image-name>:<tag>: You can specify a tag to pull a specific version of the image. For example:

docker pull python:3.9

This will pull the Python image tagged with version 3.9.

Use Case: You use `docker pull` when you need to download a specific image for local development or deployment.

2. List Available Images

docker images

The `docker images` command displays all the images stored locally on your machine. This is useful for checking which images are available for use or which ones can be cleaned up to save disk space.

Additional Parameters:

-a: Shows all images, including intermediate images created during builds.

docker images -a

This will display both final and intermediate layers.

--filter: Filters images by certain criteria. For example:

docker images --filter "dangling=true"

This will show only dangling images (i.e., images not tagged and not associated with a container).

3. Remove an Image

docker rmi <image-id>

The `docker rmi` command allows you to remove images that are no longer needed. This is a handy way to free up space on your system.

docker rmi a23e15d9b592

Additional Parameters:

-f: Force removal of an image, even if it is in use by stopped containers.

docker rmi -f a23e15d9b592

This will forcibly remove the image, even if it's being used.

--no-prune: Prevents the removal of untagged parent images.

docker rmi --no-prune a23e15d9b592

4. Remove All Images

To remove all Docker images from the system, use this command:

docker rmi $(docker images -q)

The `docker images -q` command returns the IDs of all images stored locally, and `docker rmi` removes them.

5. Remove Images Based on Name Tag

If you want to remove images based on their name tag, you can filter and remove them using the following command:

docker images --filter=reference='<image-name>:<tag>' -q | xargs docker rmi

For example, to remove all images tagged as `latest` for the `nginx` image:

docker images --filter=reference='nginx:latest' -q | xargs docker rmi

This command first filters the images based on the reference (name and tag) using `docker images --filter`, then pipes the result to `docker rmi` to remove them.

Docker Commands for Containers


Containers are runtime instances of Docker images. They are isolated, lightweight, and portable, making them perfect for running applications in various environments. Here are some of the most used Docker commands for managing containers:

1. Create and Start a Container

docker run <image-name>

The `docker run` command creates a new container from an image and starts it. For example, to create a container from the official Nginx image, you would run:

docker run nginx

Additional Parameters:

-d: Run the container in detached mode (in the background).

docker run -d nginx

This is useful for running services that should stay active, like web servers.

-p <host-port>:<container-port>: Maps a port on the host to a port on the container.

docker run -d -p 8080:80 nginx

This will map port 80 of the Nginx container to port 8080 on the host machine.

-v <host-path>:<container-path>: Mounts a volume from the host to the container.

docker run -d -v /my/data:/var/lib/mysql mysql

This mounts the `/my/data` directory on the host to the MySQL data directory inside the container.

-t and -i: These options are used to allocate a pseudo-TTY and keep stdin open, allowing you to interact with the container.

docker run -it ubuntu

This command starts an Ubuntu container and gives you an interactive bash session.

2. List Running Containers

docker ps

The `docker ps` command shows all currently running containers. To list all containers, whether they are running or not, use:

docker ps -a

Additional Parameters:

-q: Shows only the container IDs.

docker ps -q

This is useful for scripting and when you only need the container IDs for further processing.

--filter: Filters the containers by specific criteria. For example, to show only stopped containers:

docker ps -a --filter "status=exited"

This will list only the containers that have stopped.

3. Stop a Running Container

docker stop <container-id>

If you need to stop a running container, use the `docker stop` command, followed by the container ID or name.

docker stop e5ae5a1c87b4

Additional Parameters:

-t <seconds>: Specifies how many seconds to wait before forcefully killing the container if it doesn’t stop.

docker stop -t 10 e5ae5a1c87b4

This waits for 10 seconds before stopping the container forcefully.

4. Remove a Container

docker rm <container-id>

Once a container is stopped, you can remove it using the `docker rm` command. This will permanently delete the container from your system.

docker rm e5ae5a1c87b4

Additional Parameters:

-f: Forces the removal of a running container (stops it first).

docker rm -f e5ae5a1c87b4

This force-removes the container, even if it’s currently running.

-v: Removes the volumes associated with the container.

docker rm -v e5ae5a1c87b4

This removes both the container and its associated volumes.

5. Remove All Containers

To remove all Docker containers (both running and stopped), you can use the following commands:

Stop all containers:

docker stop $(docker ps -aq)

This command stops all running containers. The `docker ps -aq` command returns the IDs of all containers, while `docker stop` stops them.

Remove all containers:

docker rm $(docker ps -aq)

This will remove all containers, regardless of their state (running or stopped).

6. Remove All Containers and Images Simultaneously

To stop and remove all containers and then remove all images, you can run:

docker rm $(docker ps -aq) && docker rmi $(docker images -q)

This stops and removes all containers and then removes all images.

7. Force Removal (Including Volumes and Networks)

If you want to forcefully remove all containers and images, including their associated volumes and networks, you can use the `-f` option:

docker rm -f $(docker ps -aq) && docker rmi -f $(docker images -q)

This forcibly removes all containers and images, even if they are still running or in use.

8. Using `docker system prune -a` for Full Cleanup

The `docker system prune -a` command is a powerful way to remove not only all stopped containers and images but also volumes, networks, and build cache:

docker system prune -a

This command removes:
  • All stopped containers
  • All unused images (both dangling and unused images)
  • All unused networks
  • All unused volumes (with the `--volumes` flag)
Important: Running this command can be quite destructive, as it removes everything not actively in use by a running container.

Summary of Commands:

  1. Stop all containers: `docker stop $(docker ps -aq)`
  2. Remove all containers: `docker rm $(docker ps -aq)`
  3. Remove all images: `docker rmi $(docker images -q)`
  4. Complete system cleanup: `docker system prune -a`
  5. Remove images by name tag: `docker images --filter=reference='<image-name>:<tag>' -q | xargs docker rmi`

Docker Commands for Volumes


Volumes are persistent storage mechanisms in Docker. They allow data generated by and used by Docker containers to be stored on the host machine.

1. Create a Volume

docker volume create <volume-name>

Volumes are particularly useful for databases or applications that need to store data persistently.

docker volume create my_volume

2. List Volumes

docker volume ls

This command lists all volumes on your Docker host.

3. Remove a Volume

docker volume rm <volume-name>

If you no longer need a volume, you can remove it using the `docker volume rm` command.

docker volume rm my_volume

Docker Commands for Networks

Networking is a core feature in Docker that allows containers to communicate with each other. Here are the most useful networking commands in Docker:

1. Create a Network

docker network create <network-name>

Docker automatically creates some networks for you, but you can create custom networks for specific purposes.

docker network create my_network

2. List Networks

docker network ls

This command lists all the networks available on your Docker host.

3. Connect a Container to a Network

docker network connect <network-name> <container-id>

If a container needs to join a network, you can use the `docker network connect` command.


Docker Commands to execute commands inside running container


To execute commands inside a running Docker container, you can use the `docker exec` command. This is particularly useful when you want to interact with a container to troubleshoot, inspect files, or run specific commands without restarting or modifying the container. The basic syntax for this command is:

docker exec -it <container-id> <command>

The `-it` flag ensures that you are running the command interactively (with a pseudo-TTY) and can input/output to the container. Let’s go through some common examples.

1. Listing Files in a Directory

To list the files in a specific directory, such as `/usr/local/tomcat/logs` inside a running container, you can run:

docker exec -it 88fbea709ae9 ls /usr/local/tomcat/logs

In this example, `88fbea709ae9` is the container ID, and `ls /usr/local/tomcat/logs` lists all files in the Tomcat logs directory.

2. Reading Log Files

To view the contents of a specific log file, such as `catalina.out`, inside the Tomcat container, you can use the `cat` command:

docker exec -it 88fbea709ae9 cat /usr/local/tomcat/logs/catalina.out

This command displays the entire content of the `catalina.out` log file. If the file is large and you want to view only the last few lines, you can use `tail` instead:

docker exec -it 88fbea709ae9 tail -n 100 /usr/local/tomcat/logs/catalina.out

This command shows the last 100 lines of the log file.

3. Entering a Shell Session

You can also start an interactive shell session inside a container to explore and run multiple commands manually. For example, to start a bash session:

docker exec -it 88fbea709ae9 /bin/bash

This will give you an interactive bash shell inside the container, allowing you to navigate through directories, inspect logs, or run any other commands as needed.

If the container does not have bash installed, you can use `sh`:

docker exec -it 88fbea709ae9 /bin/sh

4. Inspecting Environment Variables

To view the environment variables inside a container, use:

docker exec -it 88fbea709ae9 env

This command lists all environment variables currently set inside the container.

5. Checking Memory or Disk Usage

You can also use `docker exec` to check the memory or disk usage within a container. For example, to check disk space:

docker exec -it 88fbea709ae9 df -h

This command displays the available disk space in a human-readable format. Similarly, to check the memory usage:

docker exec -it 88fbea709ae9 free -m

This command displays the memory usage in megabytes.

These examples illustrate how powerful and flexible `docker exec` can be for interacting with running containers. Whether you’re listing files, checking logs, or troubleshooting in a shell session, `docker exec` allows you to work within containers seamlessly.


Creating Custom Docker Images


The `docker commit` command is used to create a new image from the changes made to an existing Docker container. This command allows you to capture the current state of a container, including all modifications such as installed software, configuration changes, and file additions, and save it as a new Docker image. This is particularly useful for saving the state of a container that has been manually modified, so you can recreate that state in the future without having to redo all the steps.

The basic syntax is:

docker commit [OPTIONS] <container-id> <new-image-name>

For example, if you have a running container with ID `c3f279d17e0a` that you’ve configured with specific settings and you want to save this configuration as a new image called `my-custom-image`, you would use:

docker commit c3f279d17e0a my-custom-image

You can also add options to the command, such as `-m` to include a commit message describing the changes, or `-a` to specify the author of the image:

docker commit -m "Added new configurations" -a "John Doe" c3f279d17e0a my-custom-image:v1.1

This command creates a new image `my-custom-image:v1.1` based on the current state of the container, with the specified commit message and author information. The `docker commit` command is a powerful tool for managing and versioning your container configurations, enabling you to preserve and share specific states across different environments.


Conclusion


Docker commands provide a powerful way to manage containerized applications. By mastering these essential commands—whether you're dealing with images, containers, volumes, or networks—you'll be well-equipped to streamline your development, testing, and deployment workflows.


I Want to Hear From You!

Have you tried any of these Docker commands? Do you have a favorite trick or command that we missed? Share your experiences, tips, or questions in the comments below! Your insights could help others, and I am here to discuss any challenges or ideas you have.

About Me

I am passionate about IT technologies. If you’re interested in learning more or staying updated with my latest articles, feel free to connect with me on:

Feel free to reach out through any of these platforms if you have any questions!

I am excited to hear your thoughts! 👇

Comments

Popular posts from this blog

Monitoring and Logging with Prometheus: A Practical Guide

Creating a Complete CRUD API with Spring Boot 3: Authentication, Authorization, and Testing

Why Upgrade to Spring Boot 3.4.5: Performance, Security, and Cloud‑Native Benefits