[英]Python script not executed inside docker container
I have the following simple python script which runs fine locally: 我有以下简单的python脚本,可以在本地正常运行:
script.py script.py
with open('data.txt', 'a+') as f:
data = 'some data to be written to the file'
f.write(data)
I have created a docker image using the below: 我使用以下代码创建了一个docker镜像:
FROM python:3
ADD script.py /
CMD ["python","./script.py"]
I can launch the container in interactive mode and can see my script in there, but it doesn't appear to have executed, as there is no data.txt file? 我可以以交互方式启动容器,并且可以在其中看到我的脚本,但是由于没有data.txt文件,它似乎没有执行过? I'm at a loss.
我很茫然。
PS C:\Docker\docker_chemtrail> docker run -it python-image-test /bin/bash
root@dea1f3583dd9:/# ls -l
total 68
drwxr-xr-x 1 root root 4096 May 8 01:41 bin
drwxr-xr-x 2 root root 4096 Mar 28 09:12 boot
drwxr-xr-x 5 root root 360 Jun 3 06:11 dev
drwxr-xr-x 1 root root 4096 Jun 3 06:11 etc
drwxr-xr-x 2 root root 4096 Mar 28 09:12 home
drwxr-xr-x 1 root root 4096 May 8 01:41 lib
drwxr-xr-x 2 root root 4096 May 6 00:00 lib64
drwxr-xr-x 2 root root 4096 May 6 00:00 media
drwxr-xr-x 2 root root 4096 May 6 00:00 mnt
drwxr-xr-x 2 root root 4096 May 6 00:00 opt
dr-xr-xr-x 118 root root 0 Jun 3 06:11 proc
drwx------ 1 root root 4096 May 8 05:27 root
drwxr-xr-x 3 root root 4096 May 6 00:00 run
drwxr-xr-x 1 root root 4096 May 8 01:40 sbin
-rwxr-xr-x 1 root root 102 Jun 3 05:40 script.py
drwxr-xr-x 2 root root 4096 May 6 00:00 srv
dr-xr-xr-x 13 root root 0 Jun 3 06:03 sys
drwxrwxrwt 1 root root 4096 May 8 05:30 tmp
drwxr-xr-x 1 root root 4096 May 6 00:00 usr
drwxr-xr-x 1 root root 4096 May 6 00:00 var
root@dea1f3583dd9:/#
It should be noted I'm a beginner at Python, Docker and Linux :) I apologise in advance :) 应当指出,我是Python,Docker和Linux的初学者:)我事先表示歉意:)
Your container exits because your script.py
script exits immediately. 您的容器退出,因为您的
script.py
脚本立即退出。 In order to keep a container up & running, you must keep a process in foreground. 为了保持容器的正常运行,您必须使进程处于前台。
I tried changing the script a bit by adding sleep function & it worked - 我尝试通过添加睡眠功能来稍微更改脚本,并且它起作用了-
import time
with open('data.txt', 'a+') as f:
data = 'some data to be written to the file'
f.write(data)
time.sleep(60)
Now, if you do a docker ps
, you must be able to see your container up & running but that's only for a minute because post that your script will exit. 现在,如果您执行
docker ps
,您必须能够看到您的容器已启动并正在运行,但这仅需一分钟,因为发布脚本将退出。
Think of your container also a single process, if the process has done it's job it's supposed to exit. 将您的容器也视为一个单一的过程,如果该过程完成了它的工作,则应该退出。
If by any chance you want to run the script, see the output but still want to container to stay up & running, you can do something like below(hack) in the Dockerfile - 如果您有机会运行脚本,请查看输出,但仍希望容器保持正常运行,则可以在Dockerfile中执行以下操作(hack)-
FROM python:3
ADD script.py /
RUN python ./script.py && \
cat data.txt
CMD tail -f /dev/null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.