简体   繁体   中英

How to run pdb inside a Docker Container

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.

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.

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

Adding to Jonathan's answer - 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM