Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

** Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement! **

import docker

Get a Container

client = docker.from_env()
client.containers.list()
[<Container: 2b5cdb0477>]

Get a container by ID.

client.containers.get("2b5cdb0477")
<Container: 2b5cdb0477>

Get a container by name.

client.containers.get("nervous_germain")
<Container: 2b5cdb0477>
dir(client.containers.get("nervous_germain"))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attach', 'attach_socket', 'attrs', 'client', 'collection', 'commit', 'diff', 'exec_run', 'export', 'get_archive', 'id', 'id_attribute', 'image', 'kill', 'labels', 'logs', 'name', 'pause', 'ports', 'put_archive', 'reload', 'remove', 'rename', 'resize', 'restart', 'short_id', 'start', 'stats', 'status', 'stop', 'top', 'unpause', 'update', 'wait']
client.containers.get("nervous_germain").stop()

Pushing Docker Images

The stream=True option streams the output as a blocking generator, which is much eaiser to parse. The option decode=True decodes the blocking output as a dict, which makes it easie to parse. You can refer to dsutil.docker for a real example of parsing the streaming output of pushing Docker images using docker-py.

client = docker.from_env()
for line in client.images.push(
    "dclong/jupyterhub-ds", "latest", stream=True, decode=True
):
    print(line)