How do you use the Docker SDK for Python?
BeginnerConceptKubernetes, Docker & SSH clients
Answer
import docker
dc = docker.from_env() # honours DOCKER_HOST, defaults to the Unix socket
dc.images.pull("nginx", tag="1.27-alpine")
c = dc.containers.run("nginx:1.27-alpine", detach=True, name="web",
ports={"80/tcp": 8080}, mem_limit="256m")
print(c.status, c.logs(tail=20).decode())
for ct in dc.containers.list(filters={"status": "exited"}):
ct.remove()
Remember that access to the Docker socket is equivalent to root on the host, so a tool using the SDK must be treated as privileged.
More on Kubernetes, Docker & SSH clients
How does the official Kubernetes Python client authenticate?BeginnerHow do you list pods with high restart counts using the Python client?BeginnerHow do you patch or scale a Deployment with the Python client?IntermediateHow does `watch.Watch()` work, and what is a `410 Gone`?AdvancedHow do you apply a YAML manifest from Python?AdvancedHow do you clean up dangling Docker images and stopped containers with Python?Intermediate