Home > Net >  Unable to save a matplotlib plot via docker
Unable to save a matplotlib plot via docker

Time:10-27

I am trying to save a figure to my local after I build and run my docker file. My docker File is this

FROM python:3.7   
WORKDIR /usr/src/app
    
    # copy all the files to the container  
COPY . .  
RUN mkdir -p /root/.config/matplotlib  
RUN echo "backend : Agg" > /root/.config/matplotlib/matplotlibrc
    
RUN pip install pandas matplotlib==2.2.4
    
CMD ["python", "./main.py"]

My main.py is this

import matplotlib

import matplotlib.pyplot as plt
import pandas as pd

data = pd.read_csv('data/coding-environment-exercise.csv')
st_name=data['student']
marks=data['mark']
x=list(st_name)
y=list(marks)
print(x)
out_path = '/output/your_filename.png'
plt.plot(x,y)

plt.savefig("test2.png",format="png")

However after I run this docker file via these commands I can't find the png. It tried my code in local python ide. It saves the figure however I couldn't do it via docker.

docker build -t plot:docker . 
docker run -it plot:docker

CodePudding user response:

A Docker container has it's own separate file system from the host running the container. In order to obtain the image from the host you must mount a so called volume within the container which you can do using the -v option. You must mount the directory which should contain your image.

docker run -it -v /path/on/host:/path/in/container plot:docker

Please see the Docker documentation on volumes for more details.

Another option to obtain the image is the use of the docker cp command as long as the container is not yet removed which allows you to copy files from within the container to the host (and the other way round).

docker cp <container-name>:/path/to/file/in/container.png /target/path/on/host.png

You can set the container name using the --name flag in the docker run commmand.

docker run --name my-container -it plot:docker
  • Related