Debugging a Python script executed in a Docker container with VSCode?

Viewed 542

Let's say I have a Docker image called my_image and a Python script called my_code.py. That is, normally I would run something like this command to run the file:

docker run my_image /usr/bin/python3 my_code.py

Now I want to do this inside an interactive debugging environment in VSCode. Every guide online seems to refer to Dockerfiles and requires a bunch of configs that I'm not familiar with. For example, the Docker extension generated this tasks.json for me:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "docker-build",
            "label": "docker-build",
            "platform": "python",
            "dockerBuild": {
                "tag": "myworkspace:latest",
                "dockerfile": "${workspaceFolder}/Dockerfile",
                "context": "${workspaceFolder}",
                "pull": true
            }
        },
        {
            "type": "docker-run",
            "label": "docker-run: debug",
            "dependsOn": [
                "docker-build"
            ],
            "python": {
                "file": "my_code.py"
            }
        }
    ]
}

But I don't have a Dockerfile and I'm not interested in building a Docker container, because I already have the image and I can always start it without debugging on command as above without needing any intermediate steps or other configs. I simply want to place breakpoints in the script that my container happens to be executing, and subsequently debug those with VSCode. Perhaps it's as simple as somehow pointing the above config to the image name that I want to use (i.e. my_image), but I can't even figure out where to put it. Any pointers?

1 Answers

We can use command Docker: Add Docker Files to Workspace... to create a Docker launch configuration to build and run your container in debug mode.

  1. Navigate to the file that contains your app's startup code, and set a breakpoint.
  2. Navigate to Run and Debug and select Docker: Python - General, Docker: Python - Django, or Docker: Python - Flask, as appropriate.
  3. Start debugging using the F5 key.

You can also refer to this document for more details about docker and debug in docker

Related