15

I clearly don't understand something here. I am trying to run the pdb debugger interactively w/in a Docker Container.

Here is some code:

Dockerfile:

FROM python:3.6
ENV PROJECT_DIR=/opt/foo
WORKDIR $PROJECT_DIR
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "foo.py"]

foo.py:

def hello_world():
    print("hello world")
if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    hello_world()

If I run docker build -t foo . and then docker run foo, it prints out "hello world" as expected.

But if I uncomment out the call to pdb.set_trace() above and try again, I get the following error:

/opt/foo/foo.py(8)<module>()
-> hello_world()
(Pdb) 
Traceback (most recent call last):
  File "foo.py", line 8, in <module>
    hello_world()
  File "foo.py", line 8, in <module>
    hello_world()
  File "/usr/local/lib/python3.6/bdb.py", line 51, in trace_dispatch
    return self.dispatch_line(frame)
  File "/usr/local/lib/python3.6/bdb.py", line 70, in dispatch_line
    if self.quitting: raise BdbQuit
bdb.BdbQuit

What am I not getting?


edit: BbdQuit raised when debugging python is not a duplicate issue.

My issue, as @soundstripe correctly identified, was not providing interactive access w/in Docker for pdb.

trubliphone
  • 4,132
  • 3
  • 42
  • 66
  • Possible duplicate of [Bdbquit raised when debugging python](https://stackoverflow.com/questions/34914704/bdbquit-raised-when-debugging-python) – C.Nivs May 02 '19 at 16:41

2 Answers2

21

The tip from soundstripe did not work for me. However you can open a new terminal and type in

docker attach [container_name]

Now you should be able to use pdb.

You may need to add these to the service definition in your docker-compose yml file to make this work:

    stdin_open: true
    tty: true
Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • 2
    I have been looking everywhere for a way to run pdb from a container started from compose. This works! Add pdb line where needed. start compose with -d option. attach to the needed container. – Jack G Jan 16 '20 at 09:56
  • 1
    Adding to @Jonathan's answer, If you are doing ```docker-compose up``` in cmd then do ```docker attach container_id ``` only in cmd. It'll work – jeevu94 Jun 23 '22 at 13:10
  • 2
    To get out of the TTY when you have hit the breakpoint press `Ctrl`+`P` and then `Ctrl`+`Q`. **Do not** use `Ctrl`+`C`, it will kill the process. – Varun Kumar Jun 02 '21 at 03:34
20

pdb expects a usable terminal with a TTY. You can run pdb easily by telling Docker to attach an interactive TTY in the container to your terminal with -it:

docker run -it foo

I usually also add the --rm option to remove my temporary containers.

docker run -it --rm foo

But that is not always best during debugging as the container is gone when you are done.

soundstripe
  • 1,454
  • 11
  • 19