简体   繁体   中英

Python script not executed inside docker container

I have the following simple python script which runs fine locally:

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:

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? 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 :)

Your container exits because your script.py script exits immediately. 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.

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 -

FROM python:3
ADD script.py /
RUN python ./script.py && \
    cat data.txt
CMD tail -f /dev/null

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