Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Near32/0866d3319fe04034855830d66974ebe2 to your computer and use it in GitHub Desktop.
Save Near32/0866d3319fe04034855830d66974ebe2 to your computer and use it in GitHub Desktop.
Debugging Python within Docker

Debugging Python within Docker

Often you need to run debugger within docker. It many cases it looks like this:

import pdb; pdb.set_trace()

Or:

import ipdb; ipdb.set_trace()

The following method works well in combination with docker-compose up:

1. Add the following line to your docker .yml file

stdin_open: true
tty: true

Example:

services:
  backend:
    stdin_open: true
    tty: true
    build: backend/
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./backend:/backend
    ports:
      - "8000:8000"
    expose:
      - "8000"

2. Attach your running container

Running the docker ps command:

docker ps

And you would get something like this:

CONTAINER ID        IMAGE               COMMAND
abcdef012345        frontend            "npm run start"
ghijkl678910        backend             "python manage.py ..."

Note the backend <container id>.

Then run the docker attach command:

docker attach ghijkl678910

Now you can add pdb/ipdb set_trace statements in your code:

def view_index(request):
    # ...
    import ipdb; ipdb.set_trace()
    # ...

If you somehow get errors on Python 2.7, try replacing pdb/ipdb with pdbpp (pip install pdbpp).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment