Justin Li
Justin Li

Reputation: 1105

Django shell mode in docker

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 image docker-compose up runs the application

The 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.

Upvotes: 28

Views: 18667

Answers (5)

David Shi
David Shi

Reputation: 206

If you're using Docker Compose (using command docker compose up) to spin up your applications, after you run that command then you can run the interactive shell in the container by using the following command:

docker compose exec <container id or name of your Django app> python3 <path to your manage.py file, for example, src/manage.py> shell

Keep in mind the above is using Python version 3+ with python3.

Upvotes: 0

anmolakhilesh
anmolakhilesh

Reputation: 1683

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

Upvotes: 34

rafaljusiak
rafaljusiak

Reputation: 1090

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:

  1. Start your services once with docker-compose up -d
  2. 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.

Upvotes: 4

SuperNova
SuperNova

Reputation: 27466

You can use docker exec in the container to run commands like below.

docker exec -it container_id python manage.py shell

Upvotes: 3

Jan Giacomelli
Jan Giacomelli

Reputation: 1339

  1. Run docker exec -it --user desired_user your_container bash
    Running this command has similar effect then runing ssh 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.
  2. Inside your container just run python manage.py shell

Upvotes: 13

Related Questions