Interview Prep/Python for DevOps/Kubernetes, Docker & SSH clients

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.

All Python for DevOps questions Roadmap: Python for automation

More on Kubernetes, Docker & SSH clients