How to use PyCharm to remotely debug your Flask app running in Docker

Alexander Baumann
4 min readApr 30, 2021

--

Goals:

  • Developer ergonomics
  • Reducing dev cycle time
  • TDD

Table of Contents:

  • PyCharm Setup
  • Running your application in debug mode
  • Running Tests With Debugger

We run our Flask application with a Gunicorn web server, in docker. For local development, we use docker-compose to create a contained ecosystem of the different dockerized modules and services needed to for the application to run (Redis, local Postgres DB, main app (api)).

Instead of running our application through an IDE to gain access to debug features, PyCharm has an ability to use a Python interpreter running on a docker container

What I’m using:

  • MacOS v10.15.7
  • PyCharm v2021.1
  • Docker v20.10.5
  • Docker-Compose
  • Python 3.6.4

PyCharm Setup

  1. Set your Python Interpreter to Docker Compose for the service you wish you debug (my service is called api )
Set your python interpreter to use Docker Compose

2. Map your paths — edit the interpreter “Path mappings:” to map your local code to the code’s path inside the docker container

3. Check “Gevent compatible” in “Build, Execution, Deployment”
(this is a precaution, not needed if you don’t use Gevent)

enable Gevent compatible if you use Gevent

4. Add Python Run Configuration for your app
Check the image below to make sure your script path, parameters, interpreter, working directory, and path mappings are correctly to your project’s paths.

Run your application in debug mode

  1. Before running you newly added Python run configuration, start up your docker services as your normally would:
> docker-compose up

2. After our docker containers are running, it’s time to run our application in the IDE, in “debug” mode

3. Watch the logs. PyCharm will kill and restart your existing application’s container

4. Check that your application is running. I have my host port 5000 bound to 80 in my docker-compose.yml, so I can check localhost:5000/health

5. Now it’s time to test the debugger! Place a breakpoint at some entry point (like the /health resource). Hit the endpoint, and check that your debugger halts the process

6. Now you can use the wonder “Evaluation Tool” (little calculator icon) to gain insight to imports and modules in scope, and execute expressions!

Running Tests With Debugger

You can setup a similar config to run tests in debug mode, enabling quick TDD with low cycle time.

  1. Make sure your default test runner is set in PyCharm (we use pytest)

2. Go to a test

3. Click the green arrow to auto-create a test config

4. Edit the test’s Run Configuration:
! Important: the Working Directory needs to be the root app directory, not a sub module or test directory. PyCharm fills this in, and will need to be changed.

5. Enjoy the debugger:

That’s it. Let me know what I missed.

--

--