VS Code Python Django debugging in a dev container - python

I am developing a Python Django app in a Dockerized container. I have successfully setup remote debugging to attach to my Django server inside of a container. Me configuration is as follows.
launch.json
{
"name": "Remote Django App",
"type": "python",
"request": "attach",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"port": 9001,
"host": "localhost"
}
manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'llf_api.settings')
try:
from django.core.management import execute_from_command_line
from django.conf import settings
if settings.DEBUG:
if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
import ptvsd
ptvsd.enable_attach(address=('0.0.0.0', 8001))
print("Attached remote debugger")
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
docker-compose.yml
services:
api:
image: ${DOCKER_IMAGE_BASE}:${DOCKER_TAG}
build:
context: .
dockerfile: ./Dockerfile.development
env_file:
- .env
environment:
- DATABASE_URL=postgres://username:password#db/db_name
volumes:
- .:/app
command: >
bash -c "wait-for-it --service db:5432
&& python3 manage.py runserver 0.0.0.0:8000"
ports:
- "9000:8000"
- "9001:8001"
depends_on:
- db
tty: true
stdin_open: true
The problem is that I run VS Code inside of a dev container (the Dockerfile.development above). So VS Code is essentially running within the same container the Django server is running which would make me think I need to attach to the local port (8001) the ptvsd is running on by setting my launch.json to the following:
launch.json
{
"name": "Local Django App",
"type": "python",
"request": "attach",
"host": "api",
"port": 8001
}
However this doesn't work. When I try to attach the debugger in VS Code it appears to eventually timeout. Does anyone know how this could be accomplished?

My understanding of how VS Code and my server were running was inherently wrong. The server and VS Code are running off of the same image but NOT the same containers. The containers are running side by side and therefore the local networking is not available to either.
To make this work I realized I needed the VS Code container to access the server's container via the debugging port opened on the host. The only way I know how to do that is by using docker.for.mac.localhost as the host. So all that needed to change from my original setup was the launch.json configuration.
launch.json
{
"name": "Remote Django App",
"type": "python",
"request": "attach",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"port": 9001,
"host": "docker.for.mac.localhost"
}
VS Code now attaches to port 9001 which has been exposed on the host and connects to the host using docker.for.mac.localhost. It works!

Related

How to debug a Flask app which runs with gunicorn in a container?

I have been looking for a way to start a python debugger so I can debug my flask app which is being executed with gunicorn inside a docker container and then connect to it with my VSCode from outside.
But I dont find any solutions. In fact someone here suggests that it is not possible at all?
Is there a way to debug my flask app executed by gunicorn?
So it looks like this is very difficult, if not impossible atm, to do with gunicorn. So what I did was
Create a degub_app.py file in my project with :
from myapp.api import create_app
if __name__=="__main__":
app = create_app()
app.run('0.0.0.0', 8000, debug=False)
I created a debug container which runs nothing on start it just waiting idle like this in my docker-compose file:
api-debug:
image: "myapp:latest"
restart: on-failure:3
environment:
volumes:
- ./:/usr/src/app
depends_on:
- rabbitmq
- redis
- mongo
tty: true
stdin_open: true
command: tail -F anything
ports:
- 8000:8000
Then using VSCode with the Remote Container pluggin i attached to that container. This starts a new VSCode window and shows you the files inside the container.
Note Since the VSCode is now connected to the container I had to re-install the Python extension (you can look this up but it is easy just go to pluggins and re-install to container)
I created a launch.json inside the container to run the degub_app.py that I mentioned above like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Debug API",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}my_path/debug_api.py",
"console": "integratedTerminal",
"justMyCode": false
}
]
}

Attach a debugger to Azure Function App running in a container

I am curious to know if anyone successfully attached a debugger to a python script -
which is actually an Azure Function App running in a container.
I have all the VSCODE extensions but still can't seem to connect to the running container.
I've run the container from docker-compose.debug and from Bash cmd:
$ docker run -p 5678:5678 -it -e AzureWebJobsStorage="UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://host.docker.internal" nfunc:latest
NB I have to set an environment variable AzureWebJobsStorage for the storage.
My launch.json as follows:
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "0.0.0.0",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
]
},
What am I missing please ..
Can Functions Apps be debugged at all in a container?
Why does it not hit a breakpoint ?
Thank you
In this case, I believe you'll have to do the profiling. You will have to follow these:
If its not a blessed image, then first you would have to install SSH
if you want to get into the container.
Then you will have to make use of tools such as cProfile or other related python modules to profile the code.
Here is a documentation for windows application. You might want to take a look :
https://azureossd.github.io/2017/09/01/profile-python-applications-in-azure-app-services/index.html
This issue has been tracked : https://github.com/Azure/azure-functions-docker/issues/17

Remote debugging Docker container with ptvsd doesn't stop on breakpoint

I try to debug program which is launched on Docker container using VS Code and ptvsd.
Debugger configuration:
"name": "Attach (Remote Debug)",
"type": "python",
"request": "attach",
"port": 9091,
"host": "localhost",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/usr/src"
}
]
File which should be debugged:
import ptvsd
ptvsd.enable_attach(address=('0.0.0.0', 9091))
ptvsd.wait_for_attach()
while True:
print('elo') # breakpoint is set here
I run container with open port 9091 and code inside container. Then start debugger.
Debugger is attached but it doesn't stop on breakpoint and runs infinite loop.
ptvsd is installed on local and remote with the same version - 4.2.7
What should be changed to make debugger stop on breakpoint?
I also faced the same issue, but here the work around.
Try the following:-
import ptvsd
ptvsd.enable_attach(address=('0.0.0.0', 9091))
ptvsd.wait_for_attach()
while True:
breakpoint() #this command will add the breakpoint which will detected by debugger
print('elo')

Unable to debug Django process from vs code

Im trying to debug my Django process from vs code. But I am not able to get it to work. In my manage.py:
import ptvsd
try:
ptvsd.enable_attach("my_secret", address=('localhost', 3000))
except:
pass
In my docker-compose:
version: '3'
services:
db:
image: postgres
web:
build: .
command: python3 manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
- "3000:3000"
depends_on:
- db
And my debug info in launch.json:
{
"name": "Attach (Remote Debug)",
"type": "python",
"request": "attach",
"localRoot": "${workspaceFolder}",
"remoteRoot": "/code",
"port": 3000,
"secret": "my_secret",
"host": "localhost"
},
Dockerfile:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
EXPOSE 3000
When starting the debug session I get a message saying: "debug adapter process has terminated unexpectedly". Does anyone have any tips on how to get this working? Im running ptvsd 3.0.0 both on my computer and in the docker container.
Three points to check to debug Django in a Docker environment with VSCode:
VSCode remote debugging works only with ptvsd==3.0.0 for now (cf. VSCode documentation)
With docker-compose, ptvsd needs to be attached to the default route 0.0.0.0 in order to be reached from the host machine (like the Django development server)
ptvsd rely on sockets (which can be attached only once to a port) and Django development server reloads the manage.py file after each code changes in the project. So after each code modification, the debug server will fail to attach. To work around this problem, the best solution is to attach the ptvsd debugger in the wsgi.py file, which is only loaded once.
In order to enable remote debugging for Django apps in VS Code (e.g. when debugging docker containers), do the following:
Add ptvsd to your requirements.txt file
ptvsd == 4.3.2
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).
To your manage.py, add this:
if __name__ == "__main__": # This already exists
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings") # This already exists
from django.core.management import execute_from_command_line # This already exists
from django.conf import settings
if settings.DEBUG:
if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
import ptvsd
ptvsd.enable_attach(address = ('0.0.0.0', 3000))
print "Attached remote debugger"
execute_from_command_line(sys.argv) # This already exists
Note: The third if statement here ensures the debugger does not get attached again after a live reload.
Be sure to open port 3000 in your docker command or docker-compose.yml
Run your app:
python manage.py runserver 0.0.0.0:8000
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"
Sources
Source 1
Source 2
Your problem is likely that the webserver is reloading your file and killing your connection. Put a print or log statemet in the start of your settings.py code and see if it is being loaded twice. Then run it with a no-reload flag. ptvsd==3.0.0 does work for as long as it is installed both on host and remote machine.

Visual Studio Code gets stuck during attaching remote debugging to flask application in docker container

i'm currently to switching from atom to visual studio code - partly because of the debugging feature.
Unluckily i can't get remote debugging running in the following setup:
web/app.py
from flask import Flask
app = Flask(__name__)
import ptvsd
try:
ptvsd.enable_attach(secret=None, address = ('0.0.0.0', 3000))
ptvsd.wait_for_attach()
ptvsd.break_into_debugger()
except:
pass
#app.route('/')
def hello_world():
return 'Flask Dockerized'
if __name__ == '__main__':
app.run(debug=False,host='0.0.0.0', port=5000)
docker-compose.yml
web:
build: ./web
ports:
- "5000:5000"
- "3000:3000"
volumes:
- .:/code
launch.json
{
"name": "Attach (Remote Debug)",
"type": "python",
"request": "attach",
"localRoot": "${workspaceRoot}",
"remoteRoot": "${workspaceRoot}",
"port": 3000,
"secret": "",
"host": "localhost"
}
Problem: When i run docker-compose i get:
starting container flaskdocker ...
starting container flaskdocker ... done
attaching to flaskdocker
It just gets stuck there and i can not access the flask app on port :5000 (worked perfectly before attaching debugging to it).
Why? :/ Please help!
I'm on macOS with Visual Studio Code 1.15.1.
There have been some problems reported regarding remote debugging from Visual Studio Code using ptvsd > 3.0.0.
The issue mentioned most often is that VSC 'just hangs' when trying to connect to your remote debugger.
For now, use ptvsd 3.0.0:
pip install ptvsd==3.0.0

Categories