Python API : is it possible to narrow returned contents with containers.list()

Hey folks

For the purpose of monitoring, I need to regularly probe the complete set of docker containers - several thousands in my case - but I need only a small subset of data about each container (mostly port numbers)

Using the python API, I found containers.list(all=True) that suits my needs, except that it takes a very long time to complete - in the 10s - and my guess is it is slow because it gathers a whole lot of details that I do not care about.

So I was looking for a means to filter out results, not on a specific subset of containers, but rather on the amount of data returned about each of them; much like what docker ps --format would do; I found about the filter kwdarg that list() accepts, but it seems to be only oriented to narrowing to a subset of containers.

At this point it feels like the most effective method for me would be to subprocess a call to docker ps --format{{}}, but that feels backwards. I can’t believe I can do more with a command that wraps an API than with the API itself…

Am I missing something ? Any hint as to other methods would be appreciated; I don’t mind having to split this into several requests if that helps reduce the total amount of time needed.

many thanks in advance

The API documentation can be found here https://docs.docker.com/engine/api/v1.29/#operation/ContainerList. You can use filters to find what you need:

import docker
client = docker.from_env()

for container in client.containers.list(all=True, filters={"name":"star_with_"}):
  print container.name

actually no, the filters let me see information on fewer containers, that’s not what I need.
I need to get only some attributes of all the containers

Aah, I see. I thought that you want to filter out certain containers.

Sorry for the misunderstanding. You can’t get only certain attribute. The elements in the list() will return all the attributes.