Python file writing is not working inside docker

Viewed 2052

I'm a trying to dockerize a python script in which file writing of a text file and CSV file is there. but it is not working, the file is not getting generated.

For reference my code is

FROM python:3



ADD ./HMS.py /
ADD ./constants.py /
ADD ./Docker.py /
ADD ./SNT.py /
ADD ./Utility.py /


RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org docker
RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org grepfunc
RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org requests


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

However, when I run the python script outside am able to generate the files. May I know why it is not getting generated inside the work directory.

UPDATE

    def write_log(self, filename, message, type='info'):
        with open(filename, 'a') as log:
            log.write('\n' + message)

    def write_csv(self, filepath, data):
        with open(filepath, 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(data)

constant file contain the path

LOG_FILE='./snt_alarm_log.txt'
COMPONENT_NAME='SNT Alarm'
DB_FILE='./snt.csv'
1 Answers

Containers are ephemeral by nature. If you want to retain files generated inside a container you need to mount your host file system to the file system of the container. There are many ways to mount a volume, but a common way is a bind mount

docker run -v /path/to/host:/project sntalarmdocker_snt

Whatever gets saved to /project will be visible in /path/to/host even after the container is killed

Related