当前位置: 首页 > 工具软件 > Docker-py > 使用案例 >

[Docker] 通过python操作Docker

韩梓
2023-12-01

通过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}
 类似资料: