Reputation: 531
I'm having trouble getting the output of a Python script I'm running in a docker container using the docker-py module in Python.
First, some context:
I've created a Dockerfile and built my image (with id 84730be6107f) in the normal way via the command line (docker build -t myimage /path/to/dockerfile
). The Python script is executed as the ENTRYPOINT
command in the Dockerfile:
ENTRYPOINT ["python", "/cont_dirpath/script.py"]
The directory containing the script is added (bound) to the container upon running it.
When I do this via the usual docker command line (in Ubuntu) using:
docker run -v /host_dirpath:/cont_dirpath 84730be6107f
I get the expected Python script output printed to stdout (displayed in the terminal - the script ends with a print result
command). This is exactly the output I'm trying to get while doing this from within Python.
However, when trying to do this from within Python using the docker-py package, I am unable to view the results - the logs
method returns an empty string. Here's the Python code I'm using:
from docker import Client
docker = Client(base_url='unix://var/run/docker.sock',
version='1.10',
timeout=10)
contid = docker.create_container('84730be6107f', volumes={"/cont_dirpath":""})
docker.start(contid, binds={"/host_dirpath": {"bind": "/cont_dirpath"} })
print "Docker logs: \n" + str(docker.logs(contid))
I just get an empty string. I've tried piping the output of the script to echo
and cat
in the ENTRYPOINT
command but to no avail. How can I get the output of script.py run in the ENTRYPOINT
command to be part of the log for that container so I can read it using the docker-py Python methods? I've also tried the docker-py attach
method (I think logs
is just a wrapped version of this) with the same result.
I've considered just writing the script output to a file instead of stdout, but it isn't clear how I would access and read that file using the docker-py methods.
Any insights or suggestions would be greatly appreciated!
Upvotes: 6
Views: 3094
Reputation: 4289
What happens when you try to view the logs with kubectl
?
kubectl logs $CONTAINERID
I'm guessing you'll see nothing.
What is your workload inside the container?
Python does something weird with buffers when run headless if your code looks like this:
import time
while True:
print('something')
time.sleep(1)
To make it work, you need to manually flush the looped print statements:
import time
import sys
while True:
print('something')
sys.stdout.flush()
time.sleep(1)
Upvotes: 2