Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python docker client only listing running containers

Tags:

python

docker

I am facing a strange issue. I have 3 docker container like this -

root@dimension-VirtualBox:/home/dimension/neo4j# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS                                                      NAMES
eee581b2f493        neo4j:3.3.3         "/docker-entrypoint.…"   3 months ago        Up 22 minutes               0.0.0.0:7474->7474/tcp, 7473/tcp, 0.0.0.0:7687->7687/tcp   skill-ontology
bb99a4eb65ad        neo4j:3.3.3         "/docker-entrypoint.…"   3 months ago        Exited (0) 22 minutes ago                                                              skill-ontology-old
2a3a1e300782        neo4j:3.3.3         "/docker-entrypoint.…"   3 months ago        Exited (0) 30 hours ago                                                                romantic_mccarthy

I wrote a simple python script to list my docker containers using python library for docker. I am using docker==3.7.0 version of the library. Here is my code. I am using ubuntu 18.04 machine

import docker
# same result with below line
#cli = docker.client.DockerClient(base_url='tcp://127.0.0.1:2375')
cli = docker.DockerClient(base_url='tcp://127.0.0.1:2375')
containers = cli.containers.list()

cont =containers[0]
print(len(containers))
print(cont.short_id)

and the result is

1
eee581b2f4

It prints 1 as the output, but it supposed to print 3.

I have set my ExecStart param to ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock in my /lib/systemd/system/docker.service file

Do I need to connect to docker in some different manner in order to get info of all my docker containers.

like image 729
Anurag Sharma Avatar asked Jul 21 '26 15:07

Anurag Sharma


2 Answers

Try:

containers = cli.containers.list(all=True)

From the docs:

list(**kwargs)

List containers. Similar to the docker ps command.
Parameters: 

    all (bool) – Show all containers. Only running containers are shown by default

https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.ContainerCollection.list

like image 122
Dmytro Prylipko Avatar answered Jul 23 '26 06:07

Dmytro Prylipko


Nice thing is:

stopped_docker_container = cli.containers.list(all=True, filters={'name':'stopped_container_name'})

shows stopped container as

stopped_docker_container = cli.containers.list(filters={'name':'stopped_container_name'})

wouldn't show stopped container.

That's not so clear in the documentation, but key point is

cli.containers.list(all=True)

Thanks to @Dmytro Prylipko

like image 24
Vodyanikov Andrew Avatar answered Jul 23 '26 08:07

Vodyanikov Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!