DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

How to Check if a Docker Container Running with Python

We can use python's subprocess module for this, however using docker python-sdk would be more convenient way.

You can install it via pip:

$ pip install docker
Enter fullscreen mode Exit fullscreen mode

Then we can use a module like below:

# check_container.py
from typing import Optional

import docker


def is_container_running(container_name: str) -> Optional[bool]:
    """Verify the status of a container by it's name

    :param container_name: the name of the container
    :return: boolean or None
    """
    RUNNING = "running"
    # Connect to Docker using the default socket or the configuration
    # in your environment
    docker_client = docker.from_env()
    # Or give configuration
    # docker_socket = "unix://var/run/docker.sock"
    # docker_client = docker.DockerClient(docker_socket)

    try:
        container = docker_client.containers.get(container_name)
    except docker.errors.NotFound as exc:
        print(f"Check container name!\n{exc.explanation}")
    else:
        container_state = container.attrs["State"]
        return container_state["Status"] == RUNNING


if __name__ == "__main__":
    container_name = "localredis"
    result = is_container_running(container_name)
    print(result)
Enter fullscreen mode Exit fullscreen mode

After you run you will get:

$ python check_container.py
True
Enter fullscreen mode Exit fullscreen mode

If you use it with not-existing container name it will give:

$ python check_container.py
Check container name!
No such container: redislocal
None
Enter fullscreen mode Exit fullscreen mode

All done!

Top comments (0)