[Docker] 通过python操作Docker

本文介绍了如何使用Python与Docker进行交互,包括安装docker python包、创建客户端、运行容器等步骤。通过client.containers.run()命令启动容器,并讨论了不同参数设置下的行为,如detach为True时返回Container对象。此外,还讲解了如何查看容器日志和获取退出状态码。

通过python操作Docker

安装docker python包

pip install docker

创建client

  1. 从environment里面拿
import docker
client = docker.from_env()
  1. 指定服务
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.
  1. 默认等container运行完并返回logs, 类似docker run。
client.containers.run('<image>', '<command>')

example:

client.containers.run('alpine, 'echo hello world')
  1. 如果detach是True,会运行container并立即返回Container对象,类似docker run -d.
container = client.containers.run('<image>', detach=True)
container.logs()
  1. 查看log
  • 得到byte类型log
container.logs()
  • 得到可遍历log
logs = container.logs(stream=True)
for line in logs:
	print(output)
  1. 查看返回转态码
exit_code = container.wait()
print(exit_code)

output:

{'Error': None, 'StatusCode': 0}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值