Python (Scripting) - Restart Docker Container 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 restart the Docker container named 'hello-world'.
#!/usr/bin/python3
import docker
client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
container = client.containers.get('hello-world')
container.restart()
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:
container = client.containers.get('hello-world')
except Exception as exception:
print(exception)
sys.exit(1)
try:
container.restart()
except Exception as exception:
print(exception)
sys.exit(1)
else:
print(f"restart appears to have been successful"
sys.exit(0)
Did you find this article helpful?
If so, consider buying me a coffee over at