docker-py是Docker Engine API的Python类库,它可以完成任何docker命令所做的工作,比如在Python应用中运行容器、管理容器、管理Swarm等。
安装
最新版的docker-py可以在PyPI获取
pip install docker
如果打算通过TLS链接docker主机
pip install docker[tls]
使用
连接docker,使用默认的socket,或环境的配置
import docker
client = docker.from_env()
运行docker容器
>>> client.containers.run("ubuntu:latest", "echo hello world")
'hello world\n'
后台运行docker容器
>>> 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'>, ...]
【参考】
1。github:docker-py:https://github.com/docker/docker-py
2。docker-py:文档:https://docker-py.readthedocs.io/en/stable/