容器内容未使用Docker卷复制到Docker主机

时间:2019-05-20 05:29:06

标签: docker docker-volume

我正在容器内运行python脚本,该脚本正在生成output.txt文件。我想在容器中只运行一次该python脚本,并且我的Docker主机中应该有output.txt,但是在docker volume命令文件下运行不会被复制。

我的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"]

我的python脚本

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命令

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

我需要在命令

中给出的docker卷路径中具有output.txt
[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]#

请告知。

谢谢

1 个答案:

答案 0 :(得分:1)

运行CMD ["python", "/app/16-reading_and_writing_file.py"]时,当前工作目录为/

因此,output.txt文件将在/下而不是/app下创建

因此,最好在WORKDIR中使用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
WORKDIR /app
COPY 16-reading_and_writing_file.py .
RUN python --version
CMD ["python", "16-reading_and_writing_file.py"]

现在,文件将在/app下创建

OR

在您的python代码中,您可以使用 os 模块来形成路径

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")

无论您身在何处,这都将帮助您在存在 16-reading_and_writing_file.py 的目录下创建output.txt