In this article, we will see how to get the docker container ID from the container name by using docker CLI and docker SDK.

Using the docker PS command

By using the docker PS command, we can retrieve the Docker container ID from the container name. This command displays the information about the running containers and their corresponding details, including container ID, container name, and other relevant information.

Open the terminal and run the following command to get the container ID from the container name. Don’t forget to replace the “container_name” with the name of the container you want to retrieve the ID.

docker ps -aqf "name=container_name"

Using the docker SDK

When we are working with Docker programmatically, by using the Docker SDK of the preferred programming language, we can simplify the process of retrieving the container ID from the container name.

Docker SDKs provide high-level abstractions and functions to interact with Docker programmatically.

Following is an example of using Docker SDK with Python:

Install the docker

pip install docker

Python script to retrieve the docker container ID

import docker

client = docker.from_env()
container = client.containers.get('container_name')
container_id = container.id
print(container_id)

In the above example, replace the container_name with the name of the container that you wanted to get the ID.

Categorized in:

Tagged in: