DEV Community

lightkun
lightkun

Posted on

Remote Debug Django3(Docker) with VSCode

sample github

https://github.com/katsuya-n/pub_docker_django

environment

mysql 5.7
python 3.9
django 3

install Python extension for Visual Studio Code

Install VSCode python library. Reopen VSCode after install.

docker-compose

Django project needs to allow port 3000 to use remote debug, so write - "3000:3000".

 web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
      - "3000:3000"
    depends_on:
      - db
Enter fullscreen mode Exit fullscreen mode

my sample docker-compose.yml

launch.json

Create file .vscode/launch.json. Port sets 3000. [your docker project remote root path] changes yourself.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "attach",
            "port": 3000,
            "host": "localhost",
            "pathMappings": [
                {
                    "localRoot": "${workspaceRoot}",
                    "remoteRoot": "[your docker project remote root path]"
                }
            ],
            "django": true
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

※When request change from attach to launch, you may not success remote debug.

...
"request": "launch",
"program": manage.py",
...
Enter fullscreen mode Exit fullscreen mode

my sample launch.json

Dockerfile(Django)

Install python library called ptvsd. It has been developed by Microsoft company, but github's star is few...

RUN pip install ptvsd
Enter fullscreen mode Exit fullscreen mode

my sample Dockerfile

start project

$ docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

enable ptvsd

Edit manage.py

# add
import ptvsd
...
# add, port=3000
ptvsd.enable_attach(address=('0.0.0.0', 3000))
Enter fullscreen mode Exit fullscreen mode

my sample manage.py(remove comment out L23)

Attention! Docker container can't seem to start if you enable ptvsd before start docker container.

start debug

Enter fn + F5(Mac OS). Under bar color changes from blue to orange.

exec_debug_mode

check break point

break_point

Attention! Break point can't seem to use some of other files(etc. polls/url.py, manage.py ...). Sorry, I don't know the reason.

access URL

Access your project url(etc. http://127.0.0.1:8000/polls/), and program will stop break point.

stop break point

stop_break_point

Discussion (0)