通过python操作Docker
安装docker python包
pip install docker
创建client
- 从environment里面拿
import docker
client = docker.from_env()
- 指定服务
from docker import DockerClient
client2 = DockerClient(base_url='unix://var/run/docker.sock')
运行容器
命令:client.containers.run()
-
Returns:
-
The container logs, either STDOUT, STDERR, or both, depending on the value of the stdout and stderr arguments.
-
STDOUT and STDERR may be read only if either json-file or journald logging driver used. Thus, if you are using none of these drivers, a None object is returned instead. See the Engine API documentation for full details.
-
If detach is True, a Container object is returned instead.
-
-
Raises:
- docker.errors.ContainerError – If the container exits with a non-zero exit code and detach is False.
- docker.errors.ImageNotFound – If the specified image does not exist.
- docker.errors.APIError – If the server returns an error.
- 默认等container运行完并返回logs, 类似docker run。
client.containers.run('<image>', '<command>')
example:
client.containers.run('alpine, 'echo hello world')
- 如果detach是True,会运行container并立即返回Container对象,类似docker run -d.
container = client.containers.run('<image>', detach=True)
container.logs()
- 查看log
- 得到byte类型log
container.logs()
- 得到可遍历log
logs = container.logs(stream=True)
for line in logs:
print(output)
- 查看返回转态码
exit_code = container.wait()
print(exit_code)
output:
{'Error': None, 'StatusCode': 0}
本文介绍了如何使用Python与Docker进行交互,包括安装docker python包、创建客户端、运行容器等步骤。通过client.containers.run()命令启动容器,并讨论了不同参数设置下的行为,如detach为True时返回Container对象。此外,还讲解了如何查看容器日志和获取退出状态码。
9058

被折叠的 条评论
为什么被折叠?



