I am building an image from a Dockerfile using the docker python API.
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)
The operation finishes successfully, however I was not able to stream the logs. The API says:
Return a blocking generator you can iterate over to retrieve build output as it happens
when stream=True.
How can I get these logs in python?
You may use the low-level API client. The
build()
function will return a generator that you can iterate to grab chunks of the build log.The generator will yield a string containing a JSON object, you may call
json.loads()
on it or you can use thedecode=True
parameter in thebuild()
function that will do that for you.Once you grab the
'stream'
key from the yielded dictionary you may justprint()
it, but if you need to send it to a logger it may be better to do it line by line, as the chunk received will contain more than one line.One option of such code is as follows:
The docs state...
Have you tried that?
Streaming the docker build logs can be done using the low-level APIs given in docker-py as follows,
According to the docs, the image build now returns a tuple with both the image and the build logs
And modifying @havock solution accordingly:
Docker low level build has the ability to directly decode the output to a dictionary. For that use
decode=True
.I used mashumaro to convert the dictionary to a dataclass. This is useful if you like type hints. To use dataclasses you need at least python3.7.
Install mashumaro:
The dataclass:
Build your image:
Hope this helps.