When working with Docker, you may often need to retrieve the container ID using its name. The container ID is essential for performing various management tasks like inspecting, stopping, or restarting containers.
This guide will show you simple and effective methods to get the container ID from a container name.
Table of Contents
Prerequisites
Before we dive in, make sure you have the following:
- A basic understanding of Docker.
- Docker installed on your system.
- A running Docker container with a name assigned to it.
Step 1: List Running Docker Containers
First, let’s see the containers running on your system. You can list all active containers with the following command:
# docker ps
The output will look something like this:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a1b2c3d4e5f6 nginx:latest "nginx -g '…" 3 hours ago Up 3 hours 80/tcp my_container
Here, you can see the NAMES and CONTAINER ID columns. The name my_container is what you assigned when starting the container. The container ID a1b2c3d4e5f6 is what Docker assigned automatically.
Step 2: Retrieve Docker Container ID from Container Name
You can use the docker inspect command to get the container ID using its name. Here’s the command:
# docker inspect --format="{{.Id}}" my_container
You will see the container ID:
a1b2c3d4e5f6
Step 3: Alternative Methods to Get Docker Container ID
While the docker inspect method is straightforward, there are other ways to retrieve the container ID.
1. Using docker ps with filtering
You can filter the output of docker ps to get just the ID of a specific container:
# docker ps -qf "name=my_container"
This command will return the container ID:
a1b2c3d4e5f6
You can also get the container ID of a stopped container using:
# docker ps -a -q --filter "name=my_container"
2. Using docker container ls
docker container ls is essentially the same as docker ps. You can use it with the same options:
# docker container ls -qf "name=my_container"
This will also give you the container ID:
a1b2c3d4e5f6
Step 4: Using Docker Scripts for Automation
You can automate this with a simple script if you frequently need to retrieve container IDs. Here’s an example in Bash:
#!/bin/bash
container_name=$1
container_id=$(docker inspect --format="{{.Id}}" $container_name)
echo "The container ID for $container_name is $container_id"
This script does the following:
- Takes the container name as an argument.
- Uses docker inspect to get the container ID.
- Outputs the container ID.
To use the script, save it as get_container_id.sh, make it executable, and run it like this:
# ./get_container_id.sh my_container
The output will be:
The container ID for my_container is a1b2c3d4e5f6
Conclusion
Knowing how to get a Docker container ID from its name is essential for managing your containers. Whether you use docker inspect, docker ps, or a script, these methods will help you quickly find the necessary information.