用于Python的Docker SDK

Docker Engine API的Python库。它可以让你做任何 docker 命令可以做的事情,但可以从Python应用程序内部-运行容器、管理容器、管理群集等。

有关引擎API的详细信息,请参见 see its documentation

安装

最新的稳定版本 is available on PyPI 。要么添加 docker 致您的 requirements.txt 使用pip::文件或安装

pip install docker

快速入门

要与Docker守护进程对话,您首先需要实例化一个客户端。您可以使用 from_env() 要使用环境中的默认套接字或配置进行连接,请执行以下操作:

import docker
client = docker.from_env()

现在您可以运行容器:

>>> client.containers.run("ubuntu", "echo hello world")
'hello world\n'

您可以在后台运行容器:

>>> client.containers.run("bfirsh/reticulate-splines", detach=True)
<Container '45e6d2de7c54'>

您可以管理容器:

>>> client.containers.list()
[<Container '45e6d2de7c54'>, <Container 'db18e4f20eaa'>, ...]

>>> container = client.containers.get('45e6d2de7c54')

>>> container.attrs['Config']['Image']
"bfirsh/reticulate-splines"

>>> container.logs()
"Reticulating spline 1...\n"

>>> container.stop()

您可以流式处理日志:

>>> for line in container.logs(stream=True):
...   print(line.strip())
Reticulating spline 2...
Reticulating spline 3...
...

您可以管理镜像:

>>> client.images.pull('nginx')
<Image 'nginx'>

>>> client.images.list()
[<Image 'ubuntu'>, <Image 'nginx'>, ...]

这只是您对用于Python的Docker SDK所能做的事情的初步体验。如需更多信息, take a look at the reference