Bootstrap FreeKB - Python (Scripting) - Getting Started with DockerClient
Python (Scripting) - Getting Started with DockerClient

Updated:   |  Python (Scripting) articles

DockerClient can be used to do something on Docker, such as list, start or stop containers.

Here is the minimal boilerplate code without any error handling to initialize the client.

#!/usr/bin/python3
import docker
client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
print(client)

 

Or, using TCP.

#!/usr/bin/python3
import docker
client = docker.DockerClient(base_url='tcp://127.0.0.1:1234')
print(client)

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import docker
import sys

try:
    client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
except Exception as exception:
    print(exception)
else:
    print(client)

 

If the client is successfully initialized, something like this should be returned.

<docker.client.DockerClient object at 0x7fe584972cd0>

 

And here is an example of how to list containers using containers.list.

#!/usr/bin/python3
import docker
import sys

try:
    client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
except Exception as exception:
    print(exception)
else:
    print(client)

try:
    containers = client.containers.list(all=True)
except Exception as exception:
    print(exception)
else:
    print(containers)

 

Something like this should be returned, the ID of each container.

[<Container: d9facc570d98>, <Container: 301cb96aaef0>, <Container: 644cb1728845>, <Container: b2499df7a9fe>, <Container: f00d97c27974>]

 

Each response will be a class that contains key/value pairs. Here is how you could return the status of the container, such as "running" or "stopped".

#!/usr/bin/python3
import docker
import sys

try:
    client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
except Exception as exception:
    print(exception)
    sys.exit(1)

try:
    containers = client.containers.list(all=True)
except Exception as exception:
    print(exception)
    sys.exit(1)


for container in containers:
    try:
        container.status
    except Exception as exception:
        print(exception)
        sys.exit(1)
    else:
        if container.status != "running":
            print(f"Docker container {container.name}is NOT running")
        else:
            print(f"Docker container {container.name} is running")
sys.exit(0)

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a484d7 in the box below so that we can be sure you are a human.