简体   繁体   中英

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

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM