Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile contains a python script that writes to an output file, but the output file is not being created on the container

It's my first question, so be gentle :)

I've got a Dockerfile as follows:

FROM centos:latest
Maintainer Liz Miller
LABEL description="Image Built with Dockerfile."
RUN yum -y update
RUN yum -y install python-setuptools
RUN easy_install supervisor
RUN mkdir -p /var/log/supervisor
RUN yum -y install which
RUN yum -y install git
RUN yum install python
COPY  myscript.py myscript.py
CMD ["python", "/myscript.py"]

And the myscript.py python script is:

text_file = open('output.txt', 'w')
text_file.write('Hello World')
text_file.close()

When I build the image from this Dockerfile, the image is being built with the script and runs it, I don't see the output.txt. It's just not being created. What is missing? How do I solve this?

like image 800
Liz M Avatar asked Oct 31 '25 01:10

Liz M


2 Answers

  1. Change your text_file to /log/output.txt

  2. Build image doesn't run CMD.

  3. After your build the image, you run your container, do

    docker run -it --rm -v $(pwd)/log:/log imagename
    

Your script write inside the container and exit right the way. So you won't see it in your current directory. The way to solve this is mount a host directory into the container, and let the script write inside it, so that the data can be persistent.

like image 116
benjah1 Avatar answered Nov 01 '25 15:11

benjah1


So I've managed to solve the issue. CMD indeed doesn't run commands, but RUN does.

I've changed my CMD line to this line: RUN python myscript.py

That solved my issue, I was able to see the output file from the python script, on the container after building.

like image 41
Liz M Avatar answered Nov 01 '25 15:11

Liz M