Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在docker python API中流式传输日志?

(其他 - How to stream the logs in docker python API?)

发布于 2017-04-21 10:24:59

我正在使用docker python API从Dockerfile构建映像。

import os
import sys
import os.path
import docker


client = docker.from_env()
try:
    here = os.path.dirname(__file__)
    no_cache = False
    dockerfile = os.path.join(here, 'app', 'nextdir')
    image = client.images.build(path=dockerfile, tag='app:v.2.4', nocache=no_cache, stream=True)

该操作成功完成,但是我无法流式传输日志。API说:

返回一个阻塞生成器,你可以对其进行迭代以在生成构建输出时对其进行检索

当stream = True时。

如何在python中获取这些日志?

Questioner
cateof
Viewed
11
605 2018-09-15 12:54:59

可以使用docker-py中提供的低级API来流式传输Docker构建日志,如下所示:

        here = os.path.dirname(__file__)
        dockerfile = os.path.join(here, 'app', 'nextdir')
        docker_client = docker.APIClient(base_url='unix://var/run/docker.sock')
        generator = docker_client.build(path=dockerfile, tag='app:v.2.4', rm=True)
        while True:
            try:
                output = generator.__next__
                output = output.strip('\r\n')
                json_output = json.loads(output)
                if 'stream' in json_output:
                    click.echo(json_output['stream'].strip('\n'))
            except StopIteration:
                click.echo("Docker image build complete.")
                break
            except ValueError:
                click.echo("Error parsing output from docker image build: %s" % output)