pythondockerdocker-composedockerpy

List containers in the same docker-compose


I am working on an application that takes advantage of docker-compose. One of the containers is a watchdog component, that runs a small python script periodically to get the states of the sibling containers, and takes action if one of the containers stopped.

To this point I used a list of all container names that should be watched, but now I was wondering it I could just watch all containers created by the same docker-compose command.

Previously, the code looked something like this:

watched_containers = ["component-a", "component-b"]
def inspect_containers():
    containers = {
        (container["Names"][0].lstrip("/"), container)
        for container in docker.Client().containers(all=True)
    }

    for container_name in watched_containers:
        if containers.get(container_name, {}).get("State") != "running":
            alert_container_stopped(container_name)

I found that dockerpy does not know about docker-compose, so I created a function that filters the containers based on docker-compose project name label (com.docker.compose.project), but now I have a hardcoded project name instead of container names. Is there a way to get the current project name, or are there other ways to obtain the list of containers in the same compose?

Thanks


Solution

  • This is just a quick idea off the top of my head.

    As you're using the Docker client library in the watchdog container, I'm assuming that you have access to the host's Docker API from within the watchdog container. As each container's hostname is the container ID by default, you can use this to have the watchdog container look up its own labels from the Docker API.

    Below is an example using the Docker CLI; the Python SDK should work exactly the same way:

    $ COMPOSE_PROJECT=$(docker inspect -f '{{ (index .Config.Labels "com.docker.compose.project") }}' $HOSTNAME)
    

    Then use the project name to get the remaining containers:

    $ docker ps -aq -f label=com.docker.compose.project=$COMPOSE_PROJECT