A gRPC service can work perfectly on a developer's machine but fail immediately after deployment behind Nginx.
The application starts successfully, the Kestrel server listens on its configured port, and the service works when called directly. However, once traffic passes through Nginx, clients start receiving errors such as HTTP 502, unavailable service responses, or messages indicating that an HTTP/2 connection could not be established.
These problems are often caused by incorrect reverse proxy configuration.
Unlike a traditional REST API, gRPC relies on HTTP/2 for communication. It also uses HTTP trailers to communicate the final status of an RPC call. A reverse proxy that forwards requests using an incompatible HTTP protocol can break the communication between the client and the ASP.NET Core service.
Nginx supports gRPC through its dedicated ngx_http_grpc_module and the grpc_pass directive. However, configuring Nginx alone is not enough. The Kestrel endpoint must also support the HTTP/2 protocol expected by the proxy.
This article explains how gRPC communication works behind Nginx, how to configure Kestrel and Nginx correctly, how to enable TLS, and how to troubleshoot common deployment problems.
Understanding Why gRPC Requires HTTP/2
gRPC is a remote procedure call framework that allows applications to communicate through strongly typed service contracts.
Instead of exposing conventional REST endpoints such as:
GET /api/customers/101
a gRPC service exposes methods defined in a Protocol Buffers contract.
For example:
syntax = "proto3";
option csharp_namespace = "CustomerService";
service CustomerGrpc {
rpc GetCustomer (CustomerRequest)
returns (CustomerResponse);
}
message CustomerRequest {
int32 customerId = 1;
}
message CustomerResponse {
int32 id = 1;
string name = 2;
string email = 3;
}
A client invokes the method using a generated client:
var response = await client.GetCustomerAsync(
new CustomerRequest
{
CustomerId = 101
});
The gRPC framework handles the underlying communication.
Traditional gRPC uses HTTP/2 for several important capabilities:
Multiplexing multiple RPC calls over one connection.
Streaming requests and responses.
Efficient binary message framing.
HTTP/2 flow control.
Communication of final RPC status through HTTP trailers.
HTTP/2 is therefore not simply an optional performance improvement. It is part of the transport requirements for traditional gRPC.
Why a normal reverse proxy configuration can fail
Consider a typical ASP.NET Core deployment:
gRPC Client
|
v
Nginx
|
v
ASP.NET Core
Kestrel
|
v
gRPC Service
A normal Nginx reverse proxy configuration often uses:
location / {
proxy_pass http://127.0.0.1:5000;
}
This configuration is commonly used for HTTP applications.
However, proxy_pass belongs to Nginx's HTTP proxy module. It is not the correct mechanism for forwarding traditional gRPC traffic.
The gRPC module provides a dedicated directive:
grpc_pass grpc://127.0.0.1:5000;
This allows Nginx to communicate with the upstream server using HTTP/2 and forward gRPC requests appropriately.
The distinction is important because gRPC depends on HTTP/2 framing and trailers.
A reverse proxy must preserve the protocol behavior required by the gRPC client and server.
Understanding the Two HTTP/2 Connections
When Nginx sits between a gRPC client and Kestrel, there are two separate network connections.
Both need to be configured correctly.
<text color="secondary" size="sm">Client-to-proxy connection</text>
gRPC Client
|
| HTTPS + HTTP/2
|
v
Nginx
<text color="secondary" size="sm">Proxy-to-application connection</text>
Nginx
|
| HTTP/2
|
v
Kestrel
The first connection is normally protected using TLS.
The client connects to Nginx using HTTPS, and HTTP/2 is negotiated through Application-Layer Protocol Negotiation (ALPN) during the TLS handshake.
The second connection depends on how the application is configured.
For a common deployment where Nginx and Kestrel run on the same machine, Nginx can communicate with Kestrel using HTTP/2 over cleartext TCP, also known as h2c.
For this arrangement, Kestrel must explicitly support HTTP/2 on the upstream endpoint.
If either connection uses the wrong protocol, the gRPC request can fail.
Creating an ASP.NET Core gRPC Service
Before configuring Nginx, let's create a simple ASP.NET Core gRPC application.
You can use the .NET gRPC project template:
dotnet new grpc -n CustomerGrpcService
Move into the project directory:
cd CustomerGrpcService
The template provides the basic structure for a gRPC service.
A typical project contains:
CustomerGrpcService/
|
|-- Protos/
| |-- greet.proto
|
|-- Services/
| |-- GreeterService.cs
|
|-- Program.cs
|
|-- appsettings.json
|
|-- CustomerGrpcService.csproj
The project uses the ASP.NET Core gRPC integration.
For the examples in this article, the important package is:
<PackageReference Include="Grpc.AspNetCore" />
The project template normally includes the necessary package and Protocol Buffers tooling configuration.
Define a gRPC service
Create a Protocol Buffers file named customer.proto:
syntax = "proto3";
option csharp_namespace = "CustomerGrpcService";
package customer;
service CustomerGrpc {
rpc GetCustomer (CustomerRequest)
returns (CustomerResponse);
}
message CustomerRequest {
int32 customerId = 1;
}
message CustomerResponse {
int32 id = 1;
string name = 2;
string email = 3;
}
This contract defines a service with one method named GetCustomer.
The method receives a customer ID and returns customer information.
Implement the service
Create CustomerGrpcService.cs:
using Grpc.Core;
namespace CustomerGrpcService.Services;
public class CustomerGrpcServiceImpl
: CustomerGrpc.CustomerGrpcBase
{
private readonly ILogger<CustomerGrpcServiceImpl> _logger;
public CustomerGrpcServiceImpl(
ILogger<CustomerGrpcServiceImpl> logger)
{
_logger = logger;
}
public override Task<CustomerResponse> GetCustomer(
CustomerRequest request,
ServerCallContext context)
{
_logger.LogInformation(
"Retrieving customer {CustomerId}",
request.CustomerId);
var customer = new CustomerResponse
{
Id = request.CustomerId,
Name = "Rahul",
Email = "[email protected]"
};
return Task.FromResult(customer);
}
}
The service inherits from the generated CustomerGrpc.CustomerGrpcBase class.
The generated base class comes from the .proto definition.
Register the service in Program.cs
Configure the application:
using CustomerGrpcService.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
var app = builder.Build();
app.MapGrpcService<CustomerGrpcServiceImpl>();
app.MapGet("/", () =>
"This server hosts a gRPC service.");
app.Run();
The application is now ready to host the gRPC service.
The next step is configuring Kestrel so that it accepts HTTP/2 traffic from Nginx.
Configuring Kestrel for HTTP/2
This is one of the most important parts of the deployment.
When Nginx uses grpc_pass grpc://..., it communicates with Kestrel using HTTP/2 without TLS.
Kestrel must be configured to accept that protocol.
A common mistake is leaving the endpoint configured with:
options.Protocols = HttpProtocols.Http1AndHttp2;
This configuration works when TLS is enabled because ALPN can negotiate the protocol.
However, on an endpoint without TLS, there is no ALPN negotiation.
Kestrel cannot automatically determine whether an incoming connection should use HTTP/1.1 or HTTP/2. An unsecured endpoint configured for both protocols defaults to HTTP/1.1.
Traditional gRPC requests then fail.
For an h2c upstream connection, configure the endpoint as HTTP/2 only.
Configure Kestrel in Program.cs
Update the application:
using CustomerGrpcService.Services;
using Microsoft.AspNetCore.Server.Kestrel.Core;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(5000, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
});
var app = builder.Build();
app.MapGrpcService<CustomerGrpcServiceImpl>();
app.MapGet("/", () =>
"This server hosts a gRPC service.");
app.Run();
The important configuration is:
listenOptions.Protocols = HttpProtocols.Http2;
This tells Kestrel to accept HTTP/2 on port 5000.
The ListenLocalhost method restricts the endpoint to loopback interfaces.
When Nginx runs on the same machine, this is a useful security measure because the unencrypted upstream endpoint does not need to be publicly accessible.
Configure Kestrel using appsettings.json
You can also configure the endpoint outside the application code.
For example, use appsettings.Production.json:
{
"Kestrel": {
"Endpoints": {
"Grpc": {
"Url": "http://127.0.0.1:5000",
"Protocols": "Http2"
}
}
}
}
This keeps environment-specific endpoint configuration separate from application logic.
The application can then use the normal hosting configuration:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
var app = builder.Build();
app.MapGrpcService<CustomerGrpcServiceImpl>();
app.Run();
When configuring Kestrel endpoints explicitly, remember that endpoint configuration takes precedence over URL settings such as ASPNETCORE_URLS.
Use one clear endpoint configuration strategy to avoid confusion.
Configuring Nginx to Forward gRPC Requests
Now that Kestrel accepts HTTP/2, configure Nginx to forward requests to the application.
The important Nginx directive is:
grpc_pass grpc://127.0.0.1:5000;
This tells Nginx to forward gRPC requests to the Kestrel endpoint using HTTP/2 over a cleartext connection.
Create an Nginx server configuration
For example, create a configuration file:
/etc/nginx/conf.d/grpc.conf
Add the following configuration:
server {
listen 443 ssl;
http2 on;
server_name grpc.example.com;
ssl_certificate
/etc/letsencrypt/live/grpc.example.com/fullchain.pem;
ssl_certificate_key
/etc/letsencrypt/live/grpc.example.com/privkey.pem;
location / {
grpc_pass grpc://127.0.0.1:5000;
grpc_set_header Host $host;
grpc_set_header X-Real-IP $remote_addr;
grpc_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
grpc_set_header X-Forwarded-Proto $scheme;
grpc_read_timeout 300s;
grpc_send_timeout 300s;
}
}
This configuration establishes the public HTTPS endpoint and forwards gRPC traffic to the local ASP.NET Core application.
The http2 on; directive enables HTTP/2 on the TLS listener.
It is supported by Nginx versions that provide the newer HTTP/2 configuration syntax. On older versions, the equivalent configuration is:
listen 443 ssl http2;
Check the installed Nginx version before choosing the syntax.
Understanding the important Nginx directives
Directive | Purpose |
|---|
listen 443 ssl
| Accepts HTTPS connections |
http2 on
| Enables HTTP/2 on the TLS listener |
server_name
| Identifies the public hostname |
ssl_certificate
| Specifies the TLS certificate |
ssl_certificate_key
| Specifies the certificate's private key |
grpc_pass
| Forwards requests to the gRPC backend |
grpc_set_header
| Sets headers sent to the upstream |
grpc_read_timeout
| Limits the time between successive upstream read operations |
grpc_send_timeout
| Limits the time between successive upstream write operations |
The timeout settings deserve special attention.
They are not overall maximum durations for an entire RPC call. They control inactivity between successive read or write operations.
For streaming RPCs, choose timeout values that match the application's expected communication pattern.
A long-running stream that periodically sends messages may remain active for much longer than the configured timeout.
However, a stream that remains silent for longer than the read timeout can still be closed.
Configuring TLS Between Nginx and Kestrel
The previous example uses TLS between the client and Nginx but cleartext HTTP/2 between Nginx and Kestrel.
This is a common architecture when both components run on the same trusted machine.
However, some deployments require encryption between the reverse proxy and the application.
For example:
Nginx and Kestrel run on different servers.
The application is hosted in a separate network.
Infrastructure policies require encryption between services.
Traffic crosses an untrusted or shared network.
In these cases, configure Kestrel with an HTTPS HTTP/2 endpoint and use grpcs:// in Nginx.
Configure an HTTPS HTTP/2 endpoint in Kestrel
For example:
using Microsoft.AspNetCore.Server.Kestrel.Core;
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5001, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
listenOptions.UseHttps(
"/etc/ssl/private/grpc-server.pfx",
"certificate-password");
});
});
The example demonstrates the configuration shape. In production, retrieve certificate passwords from a secure configuration provider rather than storing them in source code.
The Kestrel endpoint now supports HTTP/2 over TLS.
Update the Nginx configuration
Change the upstream directive:
location / {
grpc_pass grpcs://grpc-backend:5001;
grpc_ssl_verify on;
grpc_ssl_trusted_certificate
/etc/nginx/certs/backend-ca.pem;
grpc_ssl_server_name on;
grpc_ssl_name grpc-backend.internal;
grpc_read_timeout 300s;
grpc_send_timeout 300s;
}
The grpcs:// scheme tells Nginx to establish a TLS connection to the upstream.
Certificate verification should remain enabled.
The trusted certificate file must contain the appropriate certificate authority, and the configured server name must match the certificate identity.
Do not disable upstream certificate verification as a permanent production workaround.
Handling Large gRPC Messages
A gRPC service might work correctly for small requests but fail when clients send larger messages.
This often happens because the application and reverse proxy have different message-size limits.
ASP.NET Core gRPC has a default maximum receive message size of 4 MB.
You can configure the limit when registering gRPC:
builder.Services.AddGrpc(options =>
{
options.MaxReceiveMessageSize = 16 * 1024 * 1024;
options.MaxSendMessageSize = 16 * 1024 * 1024;
});
This example allows messages up to 16 MB in both directions.
These settings have different meanings:
They are not the same as the overall HTTP request body limit.
Configure Nginx request-size limits
Nginx also applies request-body restrictions.
For example, if the application accepts larger request payloads, configure an appropriate limit:
location / {
client_max_body_size 20m;
grpc_pass grpc://127.0.0.1:5000;
}
The configured limit should account for the complete HTTP request body, not just the application message payload.
For streaming RPCs, think carefully about the difference between the size of an individual gRPC message and the total data transferred across a stream.
A client-streaming or bidirectional call may contain many individual messages. The total stream size can be much larger than the maximum size of one message.
Do not increase limits without considering memory usage, network capacity, and abuse protection.
Supporting HTTP/1.1 Health Checks Alongside gRPC
A common deployment challenge appears after configuring Kestrel to accept HTTP/2 only.
Traditional gRPC works, but a normal health-check request fails.
For example, a monitoring system might send:
GET /health HTTP/1.1
The problem is that the gRPC endpoint accepts HTTP/2 only.
A normal HTTP/1.1 request cannot use that endpoint.
One solution is to expose a separate HTTP/1.1 health endpoint.
Configure separate Kestrel endpoints
For example:
using Microsoft.AspNetCore.Server.Kestrel.Core;
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(5000, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
options.ListenLocalhost(5002, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1;
});
});
The application now has two endpoints:
Port | Protocol | Purpose |
|---|
5000 | HTTP/2 | gRPC communication |
5002 | HTTP/1.1 | Health checks |
Map a health endpoint:
app.MapGet("/health", () =>
Results.Ok(new
{
Status = "Healthy"
}));
Nginx can expose this endpoint separately if required.
For production applications, use ASP.NET Core health checks and distinguish between application liveness and dependency readiness.
For example, a liveness check can indicate whether the process is running, while a readiness check can indicate whether the service is ready to accept application traffic.
Keep internal health endpoints protected from unnecessary public access.
Troubleshooting Common gRPC Errors Behind Nginx
Even after configuring both services, deployment problems can still occur.
The most effective troubleshooting approach is to identify which network connection is failing.
Start by checking:
Whether the client can establish HTTP/2 with Nginx.
Whether Nginx can establish HTTP/2 with Kestrel.
Whether Kestrel has mapped the requested gRPC service.
Whether the request is rejected by a size limit or timeout.
The following errors are particularly common.
Error: Unable to establish HTTP/2 connection
A .NET client might report an error similar to:
Error starting gRPC call.
HttpRequestException:
Requesting HTTP version 2.0 with version policy
RequestVersionOrHigher while unable to establish HTTP/2 connection.
Possible causes include:
HTTP/2 is not enabled on the Nginx TLS listener.
The TLS handshake does not negotiate the h2 protocol.
The Kestrel upstream endpoint does not accept HTTP/2.
A proxy or load balancer between the client and service changes the protocol.
First, inspect the Nginx configuration.
Verify that the public listener enables HTTP/2.
Then inspect the Kestrel endpoint and confirm that the upstream port uses HttpProtocols.Http2.
Error: HTTP/1.1 response received instead of HTTP/2
A gRPC client might report that the response protocol was downgraded to HTTP/1.1.
This usually indicates that one of the connections is using the wrong HTTP protocol.
Common causes include:
Using proxy_pass instead of grpc_pass.
Configuring Kestrel for Http1AndHttp2 on an unsecured endpoint.
Forwarding traffic to the wrong application port.
Routing requests to a different Nginx location.
Check the upstream configuration first:
grpc_pass grpc://127.0.0.1:5000;
Then confirm that port 5000 is configured for HTTP/2 only.
Error: 502 Bad Gateway
An HTTP 502 response usually indicates that Nginx could not communicate successfully with the upstream application.
Possible causes include:
The ASP.NET Core process is not running.
Kestrel is listening on another port.
Nginx is using an incorrect upstream address.
The upstream protocol does not match the Kestrel endpoint.
A firewall blocks the connection.
The backend TLS certificate cannot be validated.
Start by checking the application process and listening ports.
On Linux:
sudo ss -lntp
Check whether Kestrel is listening on the expected address and port.
Then inspect the Nginx error log:
sudo tail -f /var/log/nginx/error.log
Also inspect the ASP.NET Core application logs.
The Nginx error log often provides a more useful explanation than the HTTP 502 response returned to the client.
Error: 404 Not Found
A gRPC request uses a method path generated from the Protocol Buffers service definition.
For example:
/customer.CustomerGrpc/GetCustomer
If Nginx routes the request to an incorrect location or another application, the service may return an HTTP 404 response.
Check that the correct gRPC service is mapped:
app.MapGrpcService<CustomerGrpcServiceImpl>();
Also verify that Nginx forwards the complete request path.
Avoid rewriting the gRPC method path unless the application architecture explicitly requires it.
Error: ResourceExhausted
A gRPC client may receive:
StatusCode = ResourceExhausted
This can happen when a request or response exceeds the configured message-size limit.
Review:
Do not confuse the size of one gRPC message with the total size of a streaming call.
Error: DeadlineExceeded
A client might receive:
StatusCode = DeadlineExceeded
This indicates that the RPC exceeded its deadline.
Investigate:
Client-side deadlines.
Database query duration.
Downstream service latency.
Nginx read and send timeouts.
Server-side processing delays.
Nginx's grpc_read_timeout and grpc_send_timeout are inactivity timeouts between successive operations, not substitutes for gRPC deadlines.
Set the client deadline according to the operation's expected duration, and ensure proxy timeouts do not unexpectedly terminate legitimate long-running calls.
Testing the Nginx and Kestrel Connections
After configuring the application and reverse proxy, test each connection independently.
This makes it easier to identify the component responsible for a failure.
Test the Kestrel HTTP/2 endpoint
For an unsecured HTTP/2-only Kestrel endpoint, use:
curl --http2-prior-knowledge \
http://127.0.0.1:5000/
The --http2-prior-knowledge option tells curl to use HTTP/2 directly without attempting HTTP/1.1 negotiation.
This command is useful for checking whether Kestrel accepts HTTP/2.
A normal browser request is not an equivalent test because browsers do not use cleartext HTTP/2 in the same way.
Check HTTP/2 negotiation with Nginx
For the public HTTPS endpoint, inspect the negotiated protocol:
openssl s_client \
-alpn h2 \
-connect grpc.example.com:443
Look for:
ALPN protocol: h2
This confirms that the TLS connection negotiated HTTP/2.
If h2 is not negotiated, inspect the Nginx TLS listener and its HTTP/2 configuration.
Test the actual gRPC service using grpcurl
grpcurl is a command-line utility for communicating with gRPC services.
It is useful because it can test a service without requiring you to write a separate client application.
If server reflection is enabled, list available services:
grpcurl grpc.example.com:443 list
You can also invoke the service directly:
grpcurl \
-d '{"customerId":101}' \
grpc.example.com:443 \
customer.CustomerGrpc/GetCustomer
If reflection is disabled, provide the .proto file:
grpcurl \
-import-path ./Protos \
-proto customer.proto \
-d '{"customerId":101}' \
grpc.example.com:443 \
customer.CustomerGrpc/GetCustomer
Server reflection is useful for development and diagnostics, but exposing it publicly in production should be a deliberate decision.
The service definition is often better supplied directly to diagnostic tools in production environments.
Compare direct and proxied requests
Run the same test against Kestrel and Nginx.
Test | Destination | What it verifies |
|---|
Direct Kestrel test | 127.0.0.1:5000
| Upstream HTTP/2 endpoint |
Public TLS test | grpc.example.com:443
| Client-to-Nginx connection |
grpcurl service test | Public hostname | Complete gRPC request path |
If direct Kestrel communication works but the public endpoint fails, focus on Nginx, TLS, and the network path between the two components.
If both fail, investigate the application and Kestrel configuration first.
Handling gRPC Streaming Through Nginx
gRPC supports four communication patterns:
Unary RPC.
Server streaming.
Client streaming.
Bidirectional streaming.
For example, a server-streaming method might look like this:
service NotificationGrpc {
rpc Subscribe (SubscribeRequest)
returns (stream NotificationResponse);
}
The server can send multiple responses over the same RPC.
This is useful for applications that need continuous updates, event delivery, or real-time communication.
Nginx supports traditional gRPC forwarding through its gRPC module, including streaming requests.
However, streaming introduces additional operational considerations.
Configure appropriate timeouts
A stream may remain open for a long time.
For example:
location / {
grpc_pass grpc://127.0.0.1:5000;
grpc_read_timeout 600s;
grpc_send_timeout 600s;
}
These values control inactivity between successive operations.
If the server does not send data for longer than the configured read timeout, Nginx may close the connection.
Choose timeout values based on the application's actual streaming behavior.
Understand HTTP/2 connection reuse
A single HTTP/2 connection can carry multiple gRPC calls.
This means the number of TCP connections is not necessarily equal to the number of active RPC calls.
When scaling an application across multiple Kestrel instances, consider how Nginx distributes connections and requests.
A long-lived HTTP/2 connection can carry many streams through the same upstream connection.
If load distribution and backend balancing are important, evaluate the proxy's HTTP/2 stream handling and upstream balancing behavior under realistic workloads.
Plan for reconnects
Long-lived streams can be interrupted by:
Application deployments.
Proxy restarts.
Network failures.
Server restarts.
Load-balancer changes.
Connection timeouts.
Clients should implement reconnection behavior where appropriate.
For notification or event-streaming systems, consider sequence numbers, offsets, or another mechanism that allows clients to resume from the last successfully processed event.
Do not assume that an open gRPC stream guarantees permanent delivery.
Deploying Multiple gRPC Services Behind One Nginx Hostname
An application may expose multiple gRPC services.
For example:
CustomerGrpc.
OrderGrpc.
PaymentGrpc.
NotificationGrpc.
You can route all of them through one Nginx server block.
For example:
server {
listen 443 ssl;
http2 on;
server_name grpc.example.com;
ssl_certificate
/etc/letsencrypt/live/grpc.example.com/fullchain.pem;
ssl_certificate_key
/etc/letsencrypt/live/grpc.example.com/privkey.pem;
location / {
grpc_pass grpc://127.0.0.1:5000;
grpc_read_timeout 300s;
grpc_send_timeout 300s;
}
}
All gRPC method paths are forwarded to the same upstream application.
If the services run in separate applications, configure separate locations based on their service paths.
For example:
location /customer.CustomerGrpc/ {
grpc_pass grpc://127.0.0.1:5000;
}
location /order.OrderGrpc/ {
grpc_pass grpc://127.0.0.1:5001;
}
location /payment.PaymentGrpc/ {
grpc_pass grpc://127.0.0.1:5002;
}
The location paths must match the package and service names defined in the Protocol Buffers contracts.
Avoid broad path rewrites that change the generated gRPC method path.
Securing the gRPC Deployment
A working reverse proxy configuration is not enough for production.
The deployment should also follow appropriate security practices.
Keep the Kestrel upstream private
If Nginx and Kestrel run on the same machine, bind the upstream endpoint to loopback:
options.ListenLocalhost(5000, options =>
{
options.Protocols = HttpProtocols.Http2;
});
This prevents external clients from connecting directly to the unencrypted upstream endpoint.
If the application runs in a separate container or server, use an appropriate private network and firewall policy instead.
Use TLS for public communication
Public gRPC traffic should normally use TLS.
Nginx should present a valid certificate for the public hostname and negotiate HTTP/2 with clients.
Keep certificate renewal and deployment processes reliable.
Protect gRPC methods with authentication and authorization
A reverse proxy does not replace application-level authorization.
Use the appropriate ASP.NET Core authentication and authorization mechanisms for protected gRPC services.
For example:
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
builder.Services.AddGrpc();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGrpcService<CustomerGrpcServiceImpl>()
.RequireAuthorization();
Configure the actual authentication scheme and policies required by the application.
Configure forwarded headers carefully
When TLS terminates at Nginx, Kestrel receives the upstream connection rather than the original client connection.
If the application needs to understand the original request scheme or client address, configure forwarded headers appropriately.
For example:
using Microsoft.AspNetCore.HttpOverrides;
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto;
});
Then add the middleware early in the pipeline:
app.UseForwardedHeaders();
In production, configure trusted proxy addresses or networks.
Do not blindly trust forwarded headers from arbitrary clients. Otherwise, an external caller may be able to spoof the original IP address or scheme.
Production Deployment Checklist
Before deploying an ASP.NET Core gRPC service behind Nginx, review the following items.
Area | What to verify |
|---|
Kestrel | The upstream endpoint supports HTTP/2 |
Upstream transport | grpc:// matches an h2c endpoint, or grpcs:// matches a TLS endpoint
|
Nginx | Uses grpc_pass rather than ordinary proxy_pass for traditional gRPC |
Public protocol | HTTP/2 is enabled on the TLS listener |
TLS | The public certificate is valid |
Upstream security | Internal endpoints are not unnecessarily exposed |
Message size | gRPC message limits match application requirements |
Request limits | Proxy and server limits are compatible |
Timeouts | Read and send timeouts support expected traffic patterns |
Streaming | Long-lived RPC behavior has been tested |
Health checks | Monitoring uses an endpoint with a compatible HTTP protocol |
Authentication | Protected services enforce authorization |
Logging | Nginx and ASP.NET Core logs are available |
Testing | Direct Kestrel and public gRPC requests both work |
A deployment should also be tested during rolling restarts and application updates.
Long-running streams may disconnect during deployments, so clients should be able to reconnect safely.
Conclusion
Getting gRPC working behind Nginx requires more than forwarding traffic to an ASP.NET Core application.
Traditional gRPC depends on HTTP/2, and both connections in the reverse proxy architecture must support the required protocol.
The client should connect to Nginx over HTTPS with HTTP/2 enabled. Nginx should forward requests using grpc_pass. Kestrel must accept HTTP/2 on the upstream endpoint, including explicit HTTP/2-only configuration when using cleartext h2c.
For deployments that require encryption between Nginx and Kestrel, configure an HTTPS HTTP/2 endpoint and use grpcs:// with proper certificate verification.
Once the basic configuration works, pay attention to message-size limits, streaming timeouts, health checks, forwarded headers, and application security.
The most effective troubleshooting strategy is to test each connection independently. Verify Kestrel first, check HTTP/2 negotiation at Nginx, and then test the complete service using grpcurl.
With the correct protocol configuration and operational safeguards, Nginx can serve as a reliable reverse proxy for ASP.NET Core gRPC applications.
Join the conversation! Your thoughts help the community grow.