Creating files (pdf, xls) with a python script inside a docker container

by cheesus   Last Updated July 13, 2019 01:26 AM

Trying to create simple files with a python script called "scriptfile.py". When I run it, it outputs a pdf with a sine wave and an xls file containing a 3x10 dataframe that was initially imported from a csv file called "csv_file.csv". In addition, the sine wave plot is shown. This all works fine.

Now I've created a Dockerfile, based on the app.py example in the Docker documentation. I build an image using

sudo docker build --tag=testrun .

and run it using

sudo docker run -p 4000:80 testrun

The console output is normal, but no files are created and no plot displayed. The code of the Dockerfile and the scriptfile.py are given below.

It reads

FROM python:3

WORKDIR /app
COPY . /app

ADD scriptfile.py /

RUN pip install matplotlib
RUN pip install xlwt
RUN pip install pandas

EXPOSE 80

ENV NAME DockerTester

CMD ["python","/scriptfile.py"]

The scriptfile.py reads

import math
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('csv_file.csv', sep=",", header=None)
df.to_excel(r'xlx_file.xls')

print("plotting ...")

sinusoid=[]
for i in range(100):
    sinusoid.append(math.sin(i))

f = plt.figure()
plt.plot(sinusoid)
plt.show()
f.savefig("sin.pdf")
plt.close()

print("... success")

Question: Where are the files?

Tags : python docker


Answers 1


There are multiple ways to do this, here are some.

Using docker cp

First figure out your containerid by using docker ps -a, then do:

docker cp <containerid>:/app /tmp/mydir

You will find the content on your host at /tmp/mydir.

Using Dockerfile VOLUME

Add this line to your Dockerfile after your COPY:

VOLUME /app

Now run your container like you are:

docker run -p 4000:80 testrun

Now do:

docker inspect -f '{{ .Mounts }}' <containerid>

Where <containerid> is obtained from docker ps -a. You will see something like:

[{volume 511961d95cd5de9a32afe3358c7b9af3eabd50179846fdebd9c882d50c7ffee7 /var/lib/docker/volumes/511961d95cd5de9a32afe3358c7b9af3eabd50179846fdebd9c882d50c7ffee7/_data /app local  true }] 

As you can see there is a path:

/var/lib/docker/volumes/511961d95cd5de9a32afe3358c7b9af3eabd50179846fdebd9c882d50c7ffee7/_data

That is where the container's /app directory contents are located.

Using docker run -v

Change your python script to write a location other than /app, something like f.savefig("/tmp/sin.pdf").

Then run docker like this:

docker run -it -v /tmp/share/:/tmp -p 4000:80 testrun

Now you will find your file on your host at /tmp/share/

Perplexabot
Perplexabot
July 13, 2019 00:47 AM

Related Questions


Docker Engine API connect to an existing network

Updated June 26, 2018 09:26 AM