"How can I debug an Flask application that runs inside Docker's container?" If you're asking the same question then this post might help you to answer that question.
Note: This is my very first post to Dev.to. Please pardon my English.
Debugger:
We spend most of you time to track down and kill bugs, debugger can help you nothing but do it faster. The primary advantage to a true debugger is the ability to set breakpoints and begin to step through the code line by line or function by function, and see how the variables change, until you identify what is not working as you expected.
You can debug a python web application such as Flask, Django, or event just a python script in VSCode. To start debug you app you need to install Python extension and write a description to tell VSCode to launch the project.
Install Python extension and start debugging.
Docker
Docker has become one of the most popular technologies in Devops. It provide many benefits such as
- Consistent Environment: Containers give developers the ability to create consistent environments that are isolated from others. You can make several containers that are fit the purpose, you can have three containers for development, one for testing, and one for production
- Version Control: Containers can also include software dependencies needed by the application, such as specific versions of programming language and other software libraries.
- Run Anywhere: It doesn’t matter the vehicle, it perfectly works everywhere.
- Isolation: Dependencies or settings within a container will not affect any installations or configurations on your computer, or on any other containers that may be running.
Docker and Debugger
Dockerize an app is fun but It will be a paint to debug. Good new is you still can debug an app inside a container with VSCode but it requires more works. You will need a python library called "ptvsd" for the job.
You can check out my sample code in Github
I'm using docker version 19.03.1 and docker-compose version 1.24.1
I will assume that you main application file is called app.py
First, add these lines to the top of app.py
:
import ptvsd
try:
ptvsd.enable_attach(address=('0.0.0.0', 4000))
ptvsd.wait_for_attach()
except Exception as ex:
raise e
This will let you run attach debug to port 4000, you can feel free to change the port but make sure you expose it to you local.
Second, start you services
Third, add this config into the launch.json
{
"name":"Attach Debug",
"type":"python",
"request":"attach",
"port":4000,
"host":"0.0.0.0",
"pathMappings":[{
"localRoot":"path to where the app.py lives on your local",
"remoteRoot":"path to where the app.py lives in app container"
}]
}
port value has to match the exposed port in your container.
Feel free to leave a comment if you need help.
Top comments (0)