Ben Chuanlong Du's Blog

It is never too late to learn.

Tips on docker-py Library

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

In [3]:
import docker

Get a Container

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

Get a container by ID.

In [7]:
client.containers.get("2b5cdb0477")
Out[7]:
<Container: 2b5cdb0477>

Get a container by name.

In [8]:
client.containers.get("nervous_germain")
Out[8]:
<Container: 2b5cdb0477>
In [9]:
dir(client.containers.get("nervous_germain"))
Out[9]:
['__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']
In [10]:
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.

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

Comments