Home > Blockchain >  Container not writing data to physical disk file
Container not writing data to physical disk file

Time:05-08

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.

CodePudding user response:

As I understand

D:/PythonService - local path

/var/lib/data/ - path inside container

In Python code you should use container path (/var/lib/data/) not local path (D:/PythonService)

CodePudding user response:

Your code should be something like with open("/var/lib/data/Test.txt", "w") as outFile:

all files written at /var/lib/data folder inside the container will be available to D:/PythonService

volumes:
  - <host directory>:<container directory>

CodePudding user response:

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')
  • Related