2

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

Aaditya R Krishnan
  • 495
  • 1
  • 10
  • 31
  • It's a list/array of containers (or container objects) not a dict. So you've to loop over it to access each container object. – Oli Aug 22 '20 at 09:14
  • 1
    There's information on the [Container object](https://docker-py.readthedocs.io/en/stable/containers.html#container-objects) properties in the docker-py documentation. – David Maze Aug 22 '20 at 11:35

1 Answers1

4

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.

ozlevka
  • 1,988
  • 16
  • 28