Python (Scripting) - List Docker Containers using Python DockerClient
by
Jeremy Canfield |
Updated: April 20 2024
| Python (Scripting) articles
DockerClient can be used to do something on Docker, such as list, start or stop containers. If you are not familar with the DockerClient, check out my article Python (Scripting) - Getting Started with DockerClient.
Here is the minimal boilerplate code without any error handling to list all of the Docker containers on your system.
#!/usr/bin/python3
import docker
client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
containers = client.containers.list(all=True)
for container in containers:
print(container.name)
print(container.status)
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)
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