简体   繁体   中英

Container content is not being copied to docker host using docker volume

I'm running python script inside container which is generating output.txt file. I want to run this python script just once in container and output.txt should be available in my Docker host, but running below docker volume commands file is not being copied.

My Dockerfile

[root@server test]# cat Dockerfile
FROM centos
RUN yum install -y https://centos7.iuscommunity.org/ius-release.rpm
RUN yum install -y python36u python36u-libs python36u-devel python36u-pip
RUN ln -sf /usr/bin/python3.6 /usr/bin/python
RUN mkdir /app
COPY 16-reading_and_writing_file.py /app
RUN python --version
CMD ["python", "/app/16-reading_and_writing_file.py"]

My python script

target3 = open("output.txt",'w')
line1 = "Hello"
line2 = "How Are You"
target3.write(line1)
target3.write("\n")
target3.write(line2)
target3.write("\n")
target3.close()
print ("Hello")

docker run command

[root@server test]# docker run -it -v /jaydeep/docker_practice/test/:/app jaydeepuniverse/jira
Hello
[root@server test]#

I need to have output.txt here in docker volume path given in command

[root@server test]# pwd
/jaydeep/docker_practice/test
[root@server test]# ls -ltrh
total 8.0K
-rwxr-xr-x 1 root root 183 May 17 08:25 16-reading_and_writing_file.py
-rw-r--r-- 1 root root 510 May 17 23:35 Dockerfile
[root@server test]#

Please advise.

Thanks

When you are running CMD ["python", "/app/16-reading_and_writing_file.py"] , Your current working directory is / .

So output.txt file be created under / not in /app

So it's better to use WORKDIR in your Dockerfile to mention your working directory

FROM centos
RUN yum install -y https://centos7.iuscommunity.org/ius-release.rpm
RUN yum install -y python36u python36u-libs python36u-devel python36u-pip
RUN ln -sf /usr/bin/python3.6 /usr/bin/python
RUN mkdir /app
WORKDIR /app
COPY 16-reading_and_writing_file.py .
RUN python --version
CMD ["python", "16-reading_and_writing_file.py"]

Now the file will be created under /app

OR

In your python code, you can use the os module to form the path

import os

output_file_path  = os.path.join(os.path.abspath(__file__), 'output.txt')
target3 = open(output_file_path,'w')
line1 = "Hello"
line2 = "How Are You"
target3.write(line1)
target3.write("\n")
target3.write(line2)
target3.write("\n")
target3.close()
print ("Hello")

This will help you create your output.txt in the same directory where 16-reading_and_writing_file.py is present, no matter wherever you are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM