Search code examples
dockerdocker-composedocker-volume

Container not writing data to physical disk file


Python Code:

import datetime,os
data = ""
with open("D://PythonService//Test.txt", "w") as outFile:
    outFile.write(data + "Service started at - {}\n".format(datetime.datetime.now()))
    outFile.close()

Dockerfile

FROM python:latest
COPY requirements.txt .
RUN python -m pip install -r requirements.txt
WORKDIR /app
COPY . /app
CMD ["python", "WriteData.py"]

docker-compose.yml

version: '3.4'
services:
    newfoldercopy:
        image: newfoldercopy
        build:
          context: .
          dockerfile: ./Dockerfile
        volumes:
          - D:/PythonService:/var/lib/data/

I am trying to mount my physical file system path to the container. But the container is not writing data on a physical file, the container is writing data on a container virtual file.


Solution

  • Change:

    with open("D://PythonService//Test.txt", "w") as outFile:
    

    to:

    with open("/var/lib/data/Test.txt", "w") as outFile:
    

    because of this line in your docker-compose.yml:

            volumes:
              - D:/PythonService:/var/lib/data/
    

    Also instead of:

    outFile.write(data + "Service started at - {}\n".format(datetime.datetime.now()))
    

    You can use f-string:

    outFile.write(f'{data} Service started at - {datetime.datetime.now()}\n')
    

    which makes your code more readable.

    Also as I understood, using with open() closes your file automatically, so you can change your Python code from:

    with open("D://PythonService//Test.txt", "w") as outFile:
        outFile.write(data + "Service started at - {}\n".format(datetime.datetime.now()))
        outFile.close()
    

    to:

    with open("/var/lib/data/Test.txt", "w") as outFile:
        outFile.write(f'{data} Service started at - {datetime.datetime.now()}\n')