How can I run commands in a docker container when the process for the main command is not running or has ended?


Usually, I can set up a command for a container. E.g. if I create a container based on python 2.7 and running django code, my command would come like this:

$ docker container create --name my-django-proj -v path/to/my/proj:/project -ti python:2.7 "cd /project && python runserver"

(please this is just an example! I know I could use gunicorn instead, and so, but the topic is not about django specifically, but docker. Also, Let's assume there is an actual Django project in path/to/my/proj)

This command has a caveat: If I want to perform maintenance tasks in my Django server, and have to kill the process, the container will stop.

So, something I thought is: Make the container execute bash, and once in bash, execute manually those two commands. Indeed, that option serves me well. I can do it:

$ docker container create --name my-django-proj -v path/to/my/proj:/project -ti python:2.7 bash


$ docker container start -i


# cd /project
# python runserver

And if somehow I have to perform maintenance tasks (specially the first time! when no requirements will be yet installed and I must manually run packages installs with -in this example- pip), I can kill the server, do stuff, and then restart the server.

If I don't want to be in front of the console and want to run it as daemon, I can remove the -i flag, add the -d flag and later send commands to start and stop the server like this:

docker exec -it my-django-proj cd /project && python runserver

Since the main command is bash, I know the container is alive until I stop it.

But my issue is: I'd like that command (this two commands) be run right inside the bash command, and when those commands end (in this case: when the django server is stopped), keep the bash alive so the container can be still running and can perform more tasks interactively or via docker exec.

Briefly: I know how to do this manually - How can I do this automatically?

Edit I found that I can use bash "cd /project ; python runserver ; bash". Is there a way to do that without having a second bash process?