Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

python - Docker interactive mode and executing script

I have a Python script in my docker container that needs to be executed, but I also need to have interactive access to the container once it has been created ( with /bin/bash ).

I would like to be able to create my container, have my script executed and be inside the container to see the changes/results that have occurred (no need to manually execute my python script).

The current issue I am facing is that if I use the CMD or ENTRYPOINT commands in the docker file I am unable to get back into the container once it has been created. I tried using docker start and docker attach but I'm getting the error:

sudo docker start containerID
sudo docker attach containerID
"You cannot attach to a stepped container, start it first"

Ideally, something close to this:

sudo docker run -i -t image /bin/bash python myscript.py

Assume my python script contains something like (It's irrelevant what it does, in this case it just creates a new file with text):

open('newfile.txt','w').write('Created new file with text
')

When I create my container I want my script to execute and I would like to be able to see the content of the file. So something like:

root@66bddaa892ed# sudo docker run -i -t image /bin/bash
bash4.1# ls
newfile.txt
bash4.1# cat newfile.txt
Created new file with text
bash4.1# exit
root@66bddaa892ed#

In the example above my python script would have executed upon creation of the container to generate the new file newfile.txt. This is what I need.

question from:https://stackoverflow.com/questions/25101596/docker-interactive-mode-and-executing-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My way of doing it is slightly different with some advantages. It is actually multi-session server rather than script but could be even more usable in some scenarios:

# Just create interactive container. No start but named for future reference.
# Use your own image.
docker create -it --name new-container <image>

# Now start it.
docker start new-container

# Now attach bash session.
docker exec -it new-container bash

Main advantage is you can attach several bash sessions to single container. For example I can exec one session with bash for telling log and in another session do actual commands.

BTW when you detach last 'exec' session your container is still running so it can perform operations in background


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...