Visual Studio 2022 & ASP.NET Core 6:查看应用连接数及排查NGINX连接耗尽问题
Got it, let's break down exactly how you can monitor every type of connection for your ASP.NET Core 6 app on AWS Elastic Beanstalk—critical for troubleshooting that NGINX worker_connections exhaustion and validating no connection leaks during your load tests.
First, leverage ASP.NET Core's built-in tools to track connections directly from your app:
Enable Health Checks & Metrics Endpoints
Add this to yourProgram.csto expose real-time metrics:builder.Services.AddHealthChecks(); builder.Services.AddMetrics(); // For .NET 6's built-in System.Diagnostics.Metrics // Map endpoints to access the data app.MapHealthChecks("/health"); app.MapMetrics();Hit the
/metricsendpoint to pull key stats like:aspnetcore_requests_in_progress: Current active client request connectionssystem_net_connections_established: Total active network connections from the app
Real-Time CLI Monitoring
If you can access your EB instances via SSH, use these dotnet commands:- Run
dotnet counters monitor --process-id <YOUR_APP_PID>and selectSystem.Net.Sockets+Microsoft.AspNetCore.Hostingcounters to watch live connection counts and throughput. - Use
dotnet trace collect --process-id <YOUR_APP_PID>then analyze the trace with PerfView to dig into connection lifecycle details (great for spotting leaks).
- Run
Whether you're using EF Core or raw SqlClient, here's how to track pool and active connections:
EF Core Connection Pool Insights
Configure your DbContext to log pool activity (add toProgram.cs):builder.Services.AddDbContext<YourDbContext>(options => options.UseSqlServer("YOUR_CONNECTION_STRING") .UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole())));Check your logs for lines like
Connection pool returned a connectionor use metrics:microsoft_entityframeworkcore_connections_active: Live database connections in usemicrosoft_entityframeworkcore_connections_idle: Idle connections sitting in the pool
Database-Side Checks (For AWS RDS)
If you're using RDS, check the CloudWatch metricDatabase Connectionsfor your instance. Alternatively, run this SQL query directly on your database:SELECT DB_NAME(dbid) AS DBName, COUNT(dbid) AS ActiveConnections, loginame AS AppLogin FROM sys.sysprocesses WHERE dbid > 0 AND loginame = 'YOUR_APP_DB_USER' GROUP BY dbid, loginame;This filters connections to only those from your app, so you can spot unexpected spikes.
If you're using IHttpClientFactory (the recommended approach for ASP.NET Core), track its connection pool like this:
Built-In Metrics
With metrics enabled, you’ll get these stats from/metrics:system_net_http_client_connections_established: Active connections from your HttpClient instancessystem_net_http_client_connections_pending: Connections waiting to be established (a red flag if this stays high)
Debug Logging for Connection Lifecycle
Add logging to your HttpClient setup inProgram.csto track reuse and closure:builder.Services.AddHttpClient("YourExternalApiClient") .AddLogging(logging => logging.AddConsole().SetMinimumLevel(LogLevel.Debug));Look for logs like
Connection establishedorConnection reusedto confirm connections are being properly recycled.
Since your app sits behind NGINX on EB, you need to check the proxy layer too:
Enable NGINX Status Page
Create a config file at.ebextensions/nginx/conf.d/status.confin your project with:server { listen 80; server_name localhost; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } }Deploy this, then SSH into an EB instance and run
curl http://localhost/nginx_statusto get:Active connections: Total connections NGINX is handling right nowReading: Connections where NGINX is waiting for client request dataWriting: Connections where NGINX is sending responses to clientsWaiting: Idle keep-alive connections (high numbers here might mean you need to tweak keep-alive settings)
CloudWatch Metrics for EB & ALB
Check these in the AWS Console:- ALB Metrics:
RequestCountPerTarget(verify even traffic across your 8 instances),ConnectionCount(total active connections through the load balancer),TargetResponseTime(slow responses can lead to connection backlogs) - EB Instance Metrics:
TCPConnections(total active TCP connections on each instance),CPUUtilization(high CPU can cause connection processing delays)
- ALB Metrics:
With your 500 RPS load, keep an eye on these during testing:
- Ensure NGINX's
Active connectionsdoesn’t keep climbing indefinitely (a sign of unclosed connections from the app) - Confirm database connection counts stay within your pool limits (default is 100; adjust via
Max Pool Sizein your connection string if needed) - Check that ASP.NET Core's
aspnetcore_requests_in_progressaligns with your RPS and average response time (e.g., 500 RPS with 100ms avg response time = ~50 active requests)
内容的提问来源于stack exchange,提问作者user3459555

