"Launching containers before starting a debug session in VS Code"

This article is a little reminder to myself on how to launch needed docker containers before a debug session is started in VS Code. At the same time, I had a hard time finding any sort of documentation on how to do it. So I thought I would put some short notes out there about it.

I had a Flask app relying on a redis container, in order to support sessions across several instances. For running tests, I used the Test Containers project.

VS Code tasks

VS code has a concept of tasks defined in a tasks.json. It has a type of "docker-run", able to start up a docker container.

preLaunchTask in launch.json

Debug configurations can contain tasks to be carried out before and after the debug has run.

These tasks can be named and called as a preLaunchTask from a debug configuration in launch.json.

I created two tasks, one for launching a rediscontainer and one for killing the container again, once the debug session is over:

    "version": "2.0.0",
    "tasks": [
        {
            "label": "redis",
            "type": "docker-run",
            "dockerRun": {
                "image": "redis:7.0.12",
                "ports": [
                    {
                        "containerPort": 6379,
                        "hostPort": 6379
                    }
                ],
                "remove": true,
                "containerName": "redis",
            }
        },
        {
            "label": "kill-redis",
            "type": "shell",
            "command": "docker stop redis"
        }
    ]
}
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "lfweb.app.py",
                "FLASK_DEBUG": "1"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true,
            "justMyCode": true,
            "preLaunchTask": "redis",
            "postDebugTask": "kill-redis"
        }
    ]
}

That is it really, it turned out to be rather simple, and it works quite well. The container is spinning up before my flask app starts, in order for the app to store session data in redis.

links

social