2

I have a Python script which runs a query and prints the output to a text file. When I Dockerize it the output file is not getting created. The Dockerfile is as follows:

FROM python:3
ADD cert_lamp.py /
ADD certificates.txt /
RUN pip install pyOpenSSL
RUN pip install numpy
RUN pip install cryptography
RUN pip install idna
CMD [ "python", "./cert_lamp.py" ]

cert.txt is the file where I need the output to be added. This is referenced in the script. How do I add this to the Dockerfile?

David Maze
  • 130,717
  • 29
  • 175
  • 215
Dexter
  • 45
  • 7
  • I would suggest adding WORKDIR /app after FROM python:3 to change the working directory from / to /app – Ouss May 04 '21 at 11:48
  • Is the file getting created inside the Docker container at all? – Ouss May 04 '21 at 11:49
  • You know you can use: "docker exec -it /bin/bash " to ssh into your container and execute the python script and see if the file is being generated correctly... if that was the case then the answer aSaffary is the way to get access to it from the host outside the container. – Ouss May 04 '21 at 11:58
  • Do you need the file to be in the built image (in which case you can `COPY` it in or `RUN` the script at build time) or is it the output of your script (in which case a Python virtual environment might be an easier setup)? – David Maze May 04 '21 at 13:42
  • sorry, I'm a little lost. Can you please clarify if you just need an empty file into your docker container? if yes a simple `touch` should be ok. Otherwise can can you clarify better the question? does this file contain something? do you need to expose it outside the container to get the output? – verodigiorgio May 04 '21 at 21:05

1 Answers1

1

you need to use VOLUME to map your docker files to your host files.

FROM python:3
ADD cert_lamp.py /
ADD certificates.txt /
RUN pip install pyOpenSSL
RUN pip install numpy
RUN pip install cryptography
RUN pip install idna
VOLUME /path/to/cert.txt
CMD [ "python", "./cert_lamp.py" ]

and when running your container:

docker run -v hostdirecotry:dockerdirectory my_image_name

P.S. docker image is created layer by layer, it's not really a good practice to write so many lines for a dockerfile. COPY your whole project directory instead of ADD-ing them one by one. and use a requirement.txt file to install the pip packages all at once.

aSaffary
  • 793
  • 9
  • 22
  • `VOLUME` in the Dockerfile is unnecessary and mostly has confusing side effects (leaking anonymous volumes and preventing `RUN` directives from changing that directory). – David Maze May 04 '21 at 13:41
  • @DavidMaze it's not required, but it's certainly better to have it than not to https://stackoverflow.com/questions/34809646/what-is-the-purpose-of-volume-in-dockerfile – aSaffary May 05 '21 at 06:01