Getting a django shell from a Docker container

J Fowler - Sep 3 - - Dev Community

The Django shell is a powerful development tool. Comes in handy when you want to try operations without having to hit REST endpoints or access pages.

As trend to containerize projects continues, you will find yourself needing visibility into what's going on in your Django code inside a container.

Not to worry, the Django shell is available in the container. Let's see how to get to it.

Suppose you have a docker-compose file looking something like:

services:
  # Django web server
  web:
    image: web:local
    build:
      context: ./django
      dockerfile: Dockerfile
    hostname: web
    volumes:
      - ./django:/app
Enter fullscreen mode Exit fullscreen mode

To get a shell in a container, we use

docker exec -it <name_or_id> /bin/sh
Enter fullscreen mode Exit fullscreen mode

can be the container id which is a cryptic string or the name which is the form of 'folder-servicename-number'. So for this project, we use:

docker exec -it folder-web-1 /bin/sh
/app #
Enter fullscreen mode Exit fullscreen mode

Great so I have a shell in the container, now we want to start the django shell:

/app # ./manage.py shell
Enter fullscreen mode Exit fullscreen mode

Pretty simple.

If the folder name is long or we don't know the number attached, we can use the name given in the docker compose file to find the id.

docker ps --filter ancestor=web:local --format "{{.ID}}"
32930efb8133
Enter fullscreen mode Exit fullscreen mode

Now you copy and paste the id into the docker exec command

docker exec -it 32930efb8133 /bin/sh
/app #
Enter fullscreen mode Exit fullscreen mode

If you want a one-liner:

docker exec -it $(docker ps --filter ancestor=web:local --format "{{.ID}}") /bin/sh
Enter fullscreen mode Exit fullscreen mode

Have any tips you want to add, put in the comments below.

Thanks!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player