Skip to content

Instantly share code, notes, and snippets.

@ilosamart
Forked from veuncent/docker_debugging.md
Created March 15, 2019 14:40
Show Gist options
  • Save ilosamart/252c7787d66dd29d9add934bac95b49d to your computer and use it in GitHub Desktop.
Save ilosamart/252c7787d66dd29d9add934bac95b49d to your computer and use it in GitHub Desktop.
Debugging Django apps running in Docker using ptvsd - Visual Studio (Code)

Remote debugging in Docker (for Django apps)

In order to enable debugging for your Django app running in a Docker container, follow these steps using Visual Studio (Code):

  1. Install ptvsd:
pip install ptvsd
  1. To your launch.json, add this:
  {
      "name": "Remote Django App",
      "type": "python",
      "request": "attach",
      "pathMappings": [
          {
              "localRoot": "${workspaceFolder}",
              "remoteRoot": "/remote_root/of/your/app"
          }
      ],
      "port": 3000,
      "host": "localhost"
  }

(Edit the remoteRoot option to reflect your app).

  1. To your manage.py, add this:
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")   # This already exists
  
  import ptvsd
  from your_project import settings
  
  if settings.DEBUG:
      import ptvsd
      ptvsd.enable_attach(address = ('0.0.0.0', 3000))
   
   execute_from_command_line(sys.argv)                                        # This already exists
  1. Be sure to open port 3000 in your docker command or docker-compose.yml

  2. Run your app:

  python manage.py runserver --noreload --nothreading 0.0.0.0:8000

The --noreload and --nothreading options are necessary for ptvsd, so at this point debugging with live reload is not possible with this method. See also this thread

Line-by-line debugging

Note: In some (non-Django) cases line-by-line debugging does not work, unless you use double backslashes (\) in your remoteRoot parameter (Viscual Studio Code), even though the remote server runs on Linux. E.g. "remoteRoot": "\\remote_root\\of\\your\\app"

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