In this lesson, you will learn how to capture memory dumps and performance traces from inside a live, production-hardened .NET container without needing to modify your application code.
The Challenge of Container Isolation
When your .NET application runs inside a Docker container, it is isolated from the host environment. You cannot simply run a local profiler against the container’s process ID. Instead, you must leverage the dotnet-dump and dotnet-trace global tools, which are specifically designed to communicate with the .NET Runtime's diagnostic port within an isolated namespace.
Capturing Diagnostics
To profile a running container, you must first ensure the required diagnostic tools are available. Since production containers often use the lightweight runtime-deps image, you may need to install these tools globally using dotnet tool install -g dotnet-dump (or include them in your Dockerfile as a temporary diagnostic layer).
Once inside the container (using docker exec -it <container_id> /bin/bash), you can capture a memory dump of a specific process without stopping it:
# List running processes to get the PID
dotnet-dump ps
# Capture a full memory dump of the process
dotnet-dump collect -p <PID>
For performance analysis, dotnet-trace allows you to record CPU usage and wall-clock time:
# Collect a 30-second trace
dotnet-trace collect -p <PID> --duration 00:00:30
Critical Considerations
- Security: Ensure that the diagnostic port is not exposed externally. These tools require the
SYS_PTRACEcapability if you are running in a hardened environment (e.g., restricted Linux containers). You may need to start your container with--cap-add=SYS_PTRACE. - Persistence: Dumps generated inside a container are lost when the container is removed. Use a mounted volume (e.g.,
-v /host/path:/container/path) to store the resulting.dmpor.nettracefiles so you can analyze them on your local development machine using Visual Studio or PerfView. - Overhead: While trace collection is generally low-overhead, keep collection windows short to minimize performance degradation in high-throughput production environments.
Key Takeaway: By utilizing dotnet-dump and dotnet-trace with elevated Linux capabilities, you can extract runtime diagnostics from isolated containers without disrupting the application's availability.