[Django]-Django shell mode in docker

33👍

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

12👍

  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

3👍

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

docker exec -it container_id python manage.py shell

3👍

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.

0👍

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.

Leave a comment