Django shell mode in docker
Solution 1
I use this command (when run with compose)
docker-compose run <service_name> python manage.py shell
where <service name>
is the name of the docker service(in docker-compose.yml).
So, In your case the command will be
docker-compose run web python manage.py shell
https://docs.docker.com/compose/reference/run/
When run with Dockerfile
docker exec -it <container_id> python manage.py shell
Solution 2
- Run
docker exec -it --user desired_user your_container bash
Running this command has similar effect then runingssh
to remote server - after you run this command you will be inside container's bash terminal. You will be able to run all Django's manage.py commands. - Inside your container just run
python manage.py shell
Solution 3
You can use docker exec in the container to run commands like below.
docker exec -it container_id python manage.py shell
Solution 4
If you're using docker-compose
you shouldn't always run
additional containers when it's not needed to, as each run will start new container and you'll lose a lot of disk space. So you can end up with running multiple containers when you totally won't have to. Basically it's better to:
- Start your services once with
docker-compose up -d
- Execute (instead of running) your commands:
docker-compose exec web ./manage.py shell
or, if you don't want to start all services (because, for example - you want to run only one command in Django), then you should pass --rm
flag to docker-compose run
command, so the container will be removed just after passed command will be finished.
docker-compose run --rm web ./manage.py shell
In this case when you'll escape shell, the container created with run
command will be destroyed, so you'll save much space on your disk.
Justin Li
By day: Software Engineer in a bay area big company. Help deliver ads. By night: Write whatever my girlfriend wants to build, or sleep when I do not have one. And I do not have one.
Updated on June 05, 2022Comments
-
Justin Li almost 2 years
I am learning how to develop Django application in docker with this official tutorial: https://docs.docker.com/compose/django/
I have successfully run through the tutorial, and
docker-compose run web django-admin.py startproject composeexample .
creates the imagedocker-compose up
runs the applicationThe question is:
I often use
python manage.py shell
to run Django in shell mode, but I do not know how to achieve that with docker.