Skip to content

BuggyApp · Build & Debug

Task · Build & Debug BuggyApp with Docker

Objective

In this task you will:

  • Build a simple “buggy” .NET 8 web API from scratch
  • Package it in a debug-ready Docker container
  • Run it with plain Docker - no Kubernetes, no cluster
  • Attach VS Code’s debugger with breakpoints

Prerequisites

Tool Purpose
.NET 8 SDK Build the application locally
Docker Build and run the container
VS Code extension: C# (ms-dotnettools.csharp) Provides the coreclr debug type and pipeTransport support

Install the C# extension from the VS Code marketplace or run:

code --install-extension ms-dotnettools.csharp

The finished source is included

The complete source for this task ships in src/buggyapp/ (plus a one-shot demo.sh). You can follow the steps below to build it yourself, or inspect the finished version as you go.


Step 1: Create the .NET Project

Create a new minimal API project:

mkdir -p src/buggyapp && cd src/buggyapp
dotnet new web -n BuggyApp --no-https

This generates:

  • A BuggyApp.csproj targeting .NET 8
  • A basic Program.cs
1.1 - Edit the project file

Open BuggyApp.csproj and ensure it looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <RootNamespace>BuggyApp</RootNamespace>
  </PropertyGroup>
</Project>

Why:

  • The Microsoft.NET.Sdk.Web SDK brings in ASP.NET Core automatically.
  • net8.0 is the target framework.
  • ImplicitUsings saves us from writing using statements for common namespaces.

Step 2: Write the Application Code

Create the Program.cs file with the following content:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole(opts => opts.TimestampFormat = "[HH:mm:ss] ");

var app = builder.Build();

app.MapGet("/health", () => Results.Ok(new { status = "healthy", service = "BuggyApp" }));

// This endpoint has a bug: it throws when i == 5
app.MapGet("/process", () =>
{
    var results = new List<string>();

    for (int i = 0; i < 10; i++)
    {
        if (i == 5)
        {
            throw new InvalidOperationException($"Bug! Unexpected value: {i}");
        }
        results.Add($"Processed item {i}");
    }

    return Results.Ok(results);
});

app.Run();
2.1 - Understanding the code
Line Purpose
WebApplication.CreateBuilder(args) Sets up the ASP.NET Core host with default configuration
builder.Logging.AddConsole(...) Adds timestamped console logging so we can see requests in container logs
app.MapGet("/health", ...) A health endpoint - always returns 200 OK
app.MapGet("/process", ...) The buggy endpoint - iterates 0-9 but throws an exception when i == 5
2.2 - The Bug
  • The /process endpoint throws InvalidOperationException when the loop counter reaches 5.
  • This simulates a real-world bug - a condition that crashes the request under certain inputs.
  • Our goal is to catch this with a debugger breakpoint.

Step 3: Write the Dockerfile

Create Dockerfile in the src/buggyapp/ directory:

# ---- Build stage ----
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY BuggyApp.csproj .
RUN dotnet restore
COPY . .
# Publish in Debug configuration so we get PDBs (required for breakpoints)
RUN dotnet publish -c Debug -o /app --no-restore

# ---- Runtime stage ----
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final

#################################################################################################
# Install vsdbg - the .NET debugger used by VS Code
# We use the official Microsoft script to download the correct version for Linux x64 or ARM64
# The debugger will be installed at /vsdbg/vsdbg inside the container
# This is crucial for enabling remote debugging from VS Code into the containerized app !!!!!!!!
#################################################################################################
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl unzip \
    && curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v latest -l /vsdbg \
    && apt-get purge -y curl unzip \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=build /app .
EXPOSE 80
ENV ASPNETCORE_URLS=http://+:80
ENTRYPOINT ["dotnet", "BuggyApp.dll"]
3.1 - Why -c Debug instead of -c Release?
Mode PDB Files Optimizations Breakpoints Work?
Debug ✅ Full symbols ❌ None ✅ Yes
Release ❌ Stripped/portable ✅ Aggressive ❌ No - code is reordered/inlined
  • The .pdb (Program Database) files contain the mapping between compiled IL bytecode and your C# source lines.
  • Without them, the debugger cannot map execution points back to your source code.
  • Breakpoints appear as hollow/unverified circles.

debug builds are not for production

  • Important: Never use Debug builds in production.
  • This Dockerfile is for development/troubleshooting only.
3.2 - Why do we need https://aka.ms/getvsdbgsh?
  • This URL downloads vsdbg - Microsoft’s cross-platform .NET debugger.
  • Here’s what it does:
flowchart TD
    A["https://aka.ms/getvsdbgsh"] --> B["getvsdbgsh (shell script)"]
    B --> C["1. Detects OS & CPU architecture\n(linux/arm64 or linux/x64)"]
    C --> D["2. Downloads correct vsdbg binary\nfrom Microsoft's CDN"]
    D --> E["3. Extracts to specified path (-l /vsdbg)"]
    E --> F["4. vsdbg binary at /vsdbg/vsdbg"]
Why is vsdbg needed inside the container?
  • VS Code cannot directly debug a process running inside a container.
  • Instead, it uses a pipe transport mechanism:
flowchart LR
    subgraph mac["VS Code (your Mac)"]
        vscode["VS Code\nC# Extension"]
    end
    subgraph container["Docker container"]
        vsdbg["vsdbg\n/vsdbg/vsdbg"]
        dotnet["dotnet process\nPID 1"]
        vsdbg -->|"ptrace()"| dotnet
    end
    vscode <-->|"docker exec -i\nstdin/stdout pipe\nDebug Adapter Protocol"| vsdbg
  1. VS Code spawns docker exec -i buggyapp /vsdbg/vsdbg
  2. This opens a bidirectional pipe (stdin/stdout) into the container
  3. VS Code sends Debug Adapter Protocol (DAP) commands through the pipe
  4. vsdbg receives commands like setBreakpoints, continue, stepIn
  5. vsdbg uses the Linux ptrace() syscall to control the dotnet process
  6. When a breakpoint is hit, vsdbg sends back variable values, call stack, etc.

Without vsdbg, no debugging!

Without vsdbg in the container, there is nothing to receive and execute debug commands.

3.3 - Multi-stage build explanation
Stage Base Image Purpose
build dotnet/sdk:8.0 (≈900MB) Has the compiler, NuGet, everything needed to build
final dotnet/aspnet:8.0 (≈220MB) Only has the runtime - much smaller, more secure
  • The final image contains only the compiled app + vsdbg.
  • The SDK is not shipped.
  • Compare this with the one-liner Dockerfiles of App1 - multi-stage is what you use when the build toolchain is much bigger than the runtime.

Step 4: Build the Docker Image

cd src/buggyapp
docker build -t buggyapp:latest .
4.1 - Verify the build
# Check the image exists
docker images buggyapp

# Verify PDB files are present
docker run --rm buggyapp:latest ls /app/BuggyApp.pdb

# Verify vsdbg is installed
docker run --rm buggyapp:latest ls /vsdbg/vsdbg

Step 5: Run the Container (this replaces the K8s deployment)

docker run -d --name buggyapp \
  -p 8091:80 \
  --cap-add=SYS_PTRACE \
  -e DOTNET_EnableDiagnostics=1 \
  buggyapp:latest

# Confirm it is up
docker ps --filter name=buggyapp
5.1 - Why --cap-add=SYS_PTRACE?
  • The Linux kernel blocks one process from inspecting another’s memory by default (security protection).
  • The SYS_PTRACE capability allows vsdbg to:
    • Attach to the running dotnet process using the ptrace() system call
    • Read/write process memory (to set breakpoints by inserting INT 3 trap instructions)
    • Inspect register values and call stacks
    • Pause and resume execution

Without SYS_PTRACE, attachment fails!

Without SYS_PTRACE, the debugger fails with: "Operation not permitted".

Same idea, different syntax

In Kubernetes this is a securityContext.capabilities.add in the pod spec. In Docker it is a single flag on docker run (or cap_add in docker-compose.yml). The Linux capability itself is identical.

5.2 - Why DOTNET_EnableDiagnostics=1?
  • This environment variable tells the .NET runtime to create a diagnostic IPC socket at /tmp/dotnet-diagnostic-{PID}-{timestamp}-socket.
  • This Unix domain socket is how vsdbg discovers and connects to the runtime’s internal debugging interface.

Without diagnostics enabled, attachment fails!

If this is set to 0 (or DOTNET_EnableDiagnostics_IPC is disabled), vsdbg cannot find the runtime and attach fails.

5.3 - No registry, no pull policy
  • The image was built locally, so docker run uses it directly.
  • No imagePullPolicy gymnastics needed - one of the small joys of Docker-only workflows.

Step 6: Verify Inside the Container

# Check PID 1 is dotnet
docker exec buggyapp cat /proc/1/cmdline | tr '\0' ' '
# Expected: dotnet BuggyApp.dll

# Check diagnostic socket exists
docker exec buggyapp sh -c 'ls /tmp/dotnet-diagnostic-*'
# Expected: /tmp/dotnet-diagnostic-1-XXXXXXXX-socket

# Check vsdbg exists
docker exec buggyapp ls /vsdbg/vsdbg
# Expected: /vsdbg/vsdbg

# Check PDB file exists
docker exec buggyapp ls /app/BuggyApp.pdb
# Expected: /app/BuggyApp.pdb

Step 7: Test and Trigger the Bug

# Test health endpoint
curl http://localhost:8091/health
# Expected: {"status":"healthy","service":"BuggyApp"}

# Trigger the bug
curl http://localhost:8091/process
# Expected: 500 Internal Server Error

# See the stack trace in the container logs
docker logs --tail 20 buggyapp

Step 8: Configure VS Code Debug Launch

Create or update .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach to BuggyApp in Docker",
      "type": "coreclr",
      "request": "attach",
      "processId": "1",
      "justMyCode": true,
      "pipeTransport": {
        "pipeProgram": "docker",
        "pipeArgs": ["exec", "-i", "buggyapp"],
        "debuggerPath": "/vsdbg/vsdbg",
        "pipeCwd": "${workspaceFolder}",
        "quoteArgs": false
      },
      "sourceFileMap": {
        "/src": "${workspaceFolder}/src/buggyapp"
      }
    }
  ]
}
8.1 - Configuration explained
Field Value Why
type coreclr Tells VS Code to use the .NET debugger engine
request attach We attach to an already-running process (not launching one)
processId "1" In a container, the ENTRYPOINT process is always PID 1
pipeProgram docker VS Code spawns docker as a child process for the debug pipe
pipeArgs exec -i buggyapp Opens an interactive pipe into the running container (container name comes straight from docker run --name buggyapp / container_name in compose).
Note: docker exec does not support the -- separator the way kubectl exec does - the debugger path itself is the command.
debuggerPath /vsdbg/vsdbg Path to vsdbg inside the container (installed in Step 3)
sourceFileMap /src → src/buggyapp The code was compiled at /src inside Docker but lives at src/buggyapp on your machine.
This mapping lets VS Code open the correct local file when a breakpoint hits

Kubernetes vs Docker, one line apart

The K8s version of this configuration uses "pipeProgram": "kubectl" with exec -i -n workshop deploy/buggyapp --. Swap the pipe program for docker exec and everything else stays identical - the debug protocol does not care how the pipe gets into the container.


Step 9: Attach the Debugger and Hit a Breakpoint

9.1 - Set a breakpoint
  1. Open src/buggyapp/Program.cs in VS Code
  2. Click in the gutter (left margin) on the line: if (i == 5)
  3. A red dot appears - this is your breakpoint
9.2 - Start debugging
  1. Press F5 (or Run → Start Debugging)
  2. Select “Attach to BuggyApp in Docker” from the dropdown
  3. Wait 3-5 seconds. VS Code connects via docker exec into the container.
  4. The status bar turns orange. The debug session is active.
9.3 - Trigger the breakpoint

In a terminal:

curl http://localhost:8091/process
  • VS Code pauses execution at your breakpoint.
  • You will see:

  • The current line highlighted in yellow

  • The VARIABLES panel showing i = 0 (first hit)
  • The CALL STACK showing the ASP.NET pipeline
9.4 - Debug actions
Action Shortcut What happens
Continue F5 Resume until next breakpoint hit (loop continues, i increments)
Step Over F10 Execute current line, move to next
Step Into F11 Dive into method calls
Inspect variable Hover over i Shows current value
Watch expression Add in Watch panel e.g., results.Count, i == 5
Debug Console Type expression Evaluate results to see items collected so far
  • Press F5 repeatedly to watch i increment: 0, 1, 2, 3, 4, 5.
  • Then observe the exception being thrown.

Step 10: Understand and Fix the Bug

  • Now that you’ve seen i == 5 causes the crash.
  • Fix it:
for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        // Fixed: skip instead of throw
        continue;
    }
    results.Add($"Processed item {i}");
}

Rebuild and rerun:

cd src/buggyapp
docker build -t buggyapp:latest .
docker rm -f buggyapp
docker run -d --name buggyapp \
  -p 8091:80 \
  --cap-add=SYS_PTRACE \
  -e DOTNET_EnableDiagnostics=1 \
  buggyapp:latest

# Verify the fix
curl http://localhost:8091/process
# Expected: 200 OK with all 10 items

Using the compose stack instead

The stack in docker-compose.yml already defines buggy with SYS_PTRACE and DOTNET_EnableDiagnostics for you. After changing code:

docker compose up -d --build buggy
curl http://localhost:5006/process

One-Shot Script

Everything above, scripted: src/buggyapp/demo.sh

cd src/buggyapp
bash demo.sh

It builds the image, runs the container, verifies PID 1 / PDB / vsdbg and triggers the bug - so you can jump straight into Step 8 (VS Code).


Summary

Step What you did Key concept
1 Created .NET project Minimal API with dotnet new web
2 Wrote buggy code Intentional exception for debugging practice
3 Wrote Dockerfile Debug build (-c Debug) + vsdbg installation
4 Built Docker image Multi-stage build with PDB symbols
5 Ran the container --cap-add=SYS_PTRACE + DOTNET_EnableDiagnostics
6 Verified inside the container docker exec checks: PID 1, socket, vsdbg, PDB
7 Tested + triggered the bug Verified the bug exists (500 error)
8 Configured launch.json pipeTransport via docker exec
9 Attached debugger Set breakpoint, hit it, inspected variables
10 Fixed the bug Rebuild + rerun cycle

Key Takeaways

  1. vsdbg (https://aka.ms/getvsdbgsh) is the bridge between VS Code and your .NET process in a container. Without it, remote debugging is impossible.
  2. PDB files (from -c Debug) map compiled code back to source lines. Without them, breakpoints don’t bind.
  3. SYS_PTRACE is the Linux kernel permission that allows debugger attachment - in Docker it is just --cap-add=SYS_PTRACE at runtime.
  4. pipeTransport tunnels the debug protocol through docker exec. No network ports needed, works through firewalls.
  5. sourceFileMap connects container paths to local paths so VS Code opens the right files.