I just started dockerizing my Django apps so far all is going well but I need to know is it best practice to run the Django commands inside the container
docker container exec -it con_name python manage.py startup app_name
or I should just run it outside the container
python manage.py startup app_name
thank you
2
Answers
In my case I run admin commands like "startapp" locally during development, then I run makemigrations and migrate inside the container during the deploy phase and finally I run periodic tasks in a second container (same image) managed by celery.
As much as possible, I’d avoid using
docker exec
. It’s super useful as a debugging tool, but it shouldn’t be the normal way to interact with containers.You talk specifically about launching the application. It’s fine to use an ordinary Python virtual environment here, ignoring Docker, even if you’re going to eventually deploy via a container; a host development environment paired with a container database can also be a good combination.
Otherwise, running the server should be the Dockerfile CMD. The server will be the single process the container runs, and if the server exits the container exits too.
There are various support commands the
manage.py
script can run, like running database migrations. There are a couple of approaches to this. One straightforward one is to run a new container, with the same network settings and database configuration, but an alternate command. If you’re using Compose to launch the main server, there is adocker-compose run
command that does exactly this:(There’s a style question about using
CMD
vs.ENTRYPOINT
in the Dockerfile. The command I show here replaces theCMD
; the syntax to also replaceENTRYPOINT
is much more awkward. This is one of a couple of reasons I tend to preferCMD
if there’s a choice.)For these support commands it’s also possible to run them from the host, but things like the database configuration will be different. Especially commands like
./manage.py makemigrations
that want to write back to the original source tree are better run from the host.