Aaditya R Krishnan
Aaditya R Krishnan

Reputation: 505

How to get container name from container ID using python docker module

I would like to get the container name by passing container id. I have tried below for getting that but unfortunately it didn't worked for me.

 import docker
 def get_container_details(self,container=123456789992):
     self.client = docker.from_env()
     print(self.client.containers.get(container))

May I know what is missing and how to get the container name from container ID

Upvotes: 2

Views: 1906

Answers (2)

Blue Bird
Blue Bird

Reputation: 321

The list method of containers gives the Id of the container only. To get the corresponding name, you have to use name attribute, like below --

client = docker.from_env()

def get_all_container_list():
    containers = client.containers.list()
    for i in containers:
        print(i.name, i)

More to follow at official documentation

Upvotes: 0

Gandharva S Murthy
Gandharva S Murthy

Reputation: 315

You were just a step away. Look at the snippet below,

>>> import docker
>>> client = docker.from_env()
>>> client.containers.list()
[<Container: 1c9276a9ca>]
>>> client.containers.get('1c9276a9ca').name
u'unruffled_mahavira'

Upvotes: 3

Related Questions