Docker interactive mode and executing script Docker interactive mode and executing script python python

Docker interactive mode and executing script


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


You can run a docker image, perform a script and have an interactive session with a single command:

sudo docker run -it <image-name> bash -c "<your-script-full-path>; bash"

The second bash will keep the interactive terminal session open, irrespective of the CMD command in the Dockerfile the image has been created with, since the CMD command is overwritten by the bash - c command above.

There is also no need to appending a command like local("/bin/bash") to your Python script (or bash in case of a shell script).

Assuming that the script has not yet been transferred from the Docker host to the docker image by an ADD Dockerfile command, we can map the volumes and run the script from there:sudo docker run -it -v <host-location-of-your-script>:/scripts <image-name> bash -c "/scripts/<your-script-name>; bash"

Example: assuming that the python script in the original question is already on the docker image, we can omit the -v option and the command is as simple as follows:sudo docker run -it image bash -c "python myscript.py; bash"


Why not this?

docker run --name="scriptPy" -i -t image /bin/bash python myscript.pydocker cp scriptPy:/path/to/newfile.txt /path/to/hostvim /path/to/host

Or if you want it to stay on the container

docker run --name="scriptPy" -i -t image /bin/bash python myscript.pydocker start scriptPydocker attach scriptPy

Hope it was helpful.