In the last post I described how to setup Django and Apache in Docker container. In this post I will describe how to remote debug the Django application running in the same setup. If you look at the Dockerfile of the project (in the last post), you would see that it installs ptvsd package – this package helps to debug Django applications running remotely using Visual Studio Code.
Install Visual Studio Code, if you haven’t installed it already. Then install VS Code extension for Python. I have installed this extension by Don Jayamanne, and it supports debugging of Python applications. If you don’t know how to install extensions in VS Code, this video might help you.
To enable remote debugging of Django application, or Python applications in general, you need to run ptvsd server on the machine where Django is configure, which in our case is a Docker container. You need to embed following code snippet in your Django app, and it needs to run only once, because it listens to a port.
import ptvsd
ptvsd.enable_attach("my_secret", address = ('0.0.0.0', 3500))
The above snippet starts ptsvd server, that listens on port 3500. We configured Python to run in Apache2 using mod-wsgi in the Docker container, but I haven’t found a way to embed the above code in a Django application in this setup, where it would run only once (if it is run multiple times, it will try to attach to the same port and that would fail). So far the best way I have found to debug Django application remotely in Docker is to start Django development server on a different port (than one where Apache is listening) and embed the debugger code in manage.py. You run the development server by running manage.py, for example – Continue reading “Remote Debugging Django Project in Docker”