Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the container ID from docker-py

I'm trying to check whether a docker container is up or not using filter of docker-py module. However able to check whether it is up or down. For reference :

def checkDockerContainerStatus( container):
    client = docker.from_env()
    cli = docker.APIClient()
    if client.containers.list(filters={'name': container}):
        response = client.containers.list(filters={'name': container})
        return 'Up'
    else:
        return 'Down'

checkDockerContainerStatus('app-container')

and I got response as [<Container: eb42d23b6f>] How to retrieve the container id from this response inorder to check it is log .

I tried response['container'] , but it didn't work out. May I know to get the result as my requirement

like image 477
Aaditya R Krishnan Avatar asked Dec 29 '25 04:12

Aaditya R Krishnan


1 Answers

The a lot of id's is confusing in docker.

You can read about types of id's here.

When you understand what is short form and long form of container id your code can be something like:

import docker

def checkDockerContainerStatus( container):
    client = docker.from_env()
    #cli = docker.APIClient()
    if client.containers.list(filters={'name': container}):
        response = client.containers.list(filters={'name': container})
        return str(response[0].id)[:12]
    else:
        return None

running_id = checkDockerContainerStatus('app-container')

if running_id is not None:
    print(f"Found! {running_id}")
else:
    print("Container app-container is not found")

Also I would recommend to use docker SDK instead docker-py.

Your code wont run on docker-py and run properly on docker SDK.

like image 164
ozlevka Avatar answered Dec 31 '25 00:12

ozlevka