basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    Proxying gRPC in nginx: grpc_pass, HTTP/2, long streams, and error statuses

    Line-by-line nginx configs for gRPC: TLS termination with http2 on;, forwarding to local h2c backends or TLS-encrypted grpcs://, per-service routing, long-lived streams without 60-second drops, and mapping 502/504 to grpc-status headers.

    How gRPC differs from a standard reverse proxy

    gRPC runs over HTTP/2: each RPC is a POST to /package.Service/Method with Content-Type: application/grpc, a binary Protobuf body, and mandatory HTTP/2 trailers (grpc-status and grpc-message) at the end of the stream. A regular proxy_pass from Reverse proxy talks HTTP/1.1 to the backend and breaks that flow: a cleartext HTTP/2 (h2c) backend immediately resets the connection, and trailers never reach the client.

    Official nginx 1.30 packages compile ngx_http_grpc_module alongside --with-http_v2_module, so no extra package is required. The main differences from proxy_pass:

    Setting proxy_pass (HTTP) grpc_pass (gRPC)
    Backend protocol HTTP/1.0 by default (1.1 set manually) Strictly HTTP/2 (grpc:// for h2c, grpcs:// for TLS)
    Trailing slash / URI path Rewrites the URI (Trailing slash in proxy_pass) Forbidden: nginx -t fails with invalid host in upstream
    Connection header Cleared (Connection "") for keepalive Omit: HTTP/2 forbids the Connection header
    Response header buffer Three directives (proxy_buffer_size, proxy_buffers, proxy_busy_buffers_size) Single directive grpc_buffer_size (default 4k)
    Error when node is down HTML or JSON with 502/504 Same 502/504 unless mapped to grpc-status

    On a dedicated gRPC hostname, keep port 443 on TLS plus http2 on; — skip listen 443 quic; and Alt-Svc: h3 (HTTPS & HTTP/3): standard gRPC clients expect HTTP/2 (h2).

    Scenario 1: basic gRPC with TLS, per-service routing, and error codes

    The most common setup: nginx terminates external TLS with http2 on;, applies access rules per gRPC service name, and forwards traffic to a local h2c backend (unencrypted on 127.0.0.1 or an internal network). A regular REST API via proxy_pass can share the same hostname and port 443 right next to grpc_pass.

    /etc/nginx/conf.d/grpc.example.org.conf
    upstream grpc_orders {
        server 127.0.0.1:50051;
        server 127.0.0.1:50052;
        keepalive 32;
    }

    Backend pool with persistent HTTP/2 connections. One HTTP/2 TCP socket already multiplexes up to a hundred concurrent calls, while keepalive 32 keeps connections open between traffic bursts without repeat TCP handshakes (Load balancing). Neither proxy_http_version nor Connection "" is needed here.

    default:keepalive off

    server {
        listen 443 ssl;
        http2 on;
        server_name grpc.example.org;
    
        # ssl_certificate / ssl_certificate_key / snippets/tls.conf
    
        client_max_body_size 4m;
        grpc_buffer_size     16k;
    Key part

    Without http2 on;, a gRPC client gets HTTP/1.1 and drops on the first frame. Standard gRPC libraries (Go, Python, Java) default to a 4 MiB message limit, so raise client_max_body_size from 1m to 4m (or more if your API accepts larger payloads). grpc_buffer_size 16k leaves headroom for large response metadata (upstream sent too big header).

    default:client_max_body_size 1mgrpc_buffer_size 4k/8k

        location /orders.OrderService/ {
            grpc_set_header X-Real-IP       $remote_addr;
            grpc_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            grpc_pass grpc://grpc_orders;
    
            error_page 502 503 = /error_grpc_unavailable;
            error_page 504     = /error_grpc_timeout;
        }
    Key part

    Route by the full .proto package and service name (/package.Service/). Never append a trailing slash to grpc_pass or nginx -t will fail. Pass client IP via grpc_set_header; nginx forwards Content-Type and TE: trailers automatically. Intercept 502/503 and 504 so clients get valid gRPC statuses instead of HTML.

        location /orders.AdminService/ {
            allow 10.0.0.0/24;
            deny all;
            grpc_pass grpc://grpc_orders;
    
            error_page 502 503 = /error_grpc_unavailable;
            error_page 504     = /error_grpc_timeout;
        }

    Restrict an admin service on the same port 443 by IP (Limits & access), while a normal REST route /api/ using proxy_pass can sit alongside it — HTTP/2 separates them cleanly by path.

        location = /error_grpc_unavailable {
            internal;
            default_type application/grpc;
            add_header grpc-status 14;
            add_header grpc-message "unavailable";
            return 200 "";
        }
    
        location = /error_grpc_timeout {
            internal;
            default_type application/grpc;
            add_header grpc-status 4;
            add_header grpc-message "deadline exceeded";
            return 200 "";
        }
    }
    Key part

    Internal handlers translate nginx gateway errors into valid Trailers-Only gRPC responses: HTTP/2 200, content-type: application/grpc, and status 14 (UNAVAILABLE) or 4 (DEADLINE_EXCEEDED). Use return 200 "";, not return 204;: on 204, nginx strips Content-Type and strict gRPC clients reject the response.

    Scenario 2: long-lived streams (server, client, and bidirectional)

    Unary RPCs finish in seconds, whereas server event subscriptions and bidirectional streams stay open for hours with long idle gaps between messages. With default settings, four limits cut them short:

    • grpc_read_timeout 60s — gap between two consecutive reads from the backend. After one silent minute, nginx sends HTTP/2 RST_STREAM (INTERNAL_ERROR) to the client and logs upstream timed out (110: Connection timed out) while reading upstream in error.log.
    • grpc_send_timeout 60s and client_body_timeout 60s — the same 60-second cutoff in the opposite direction when the client stays silent in a client or bidirectional stream.
    • keepalive_time 1h and keepalive_requests 1000 — max lifetime and max HTTP/2 streams on one client TCP connection. Once hit, nginx sends GOAWAY so the client reconnects on a fresh socket; raise keepalive_time when single streams must outlive one hour.
    • Intermediate NATs and firewalls drop idle TCP sockets silently unless grpc_socket_keepalive on; or application-level HTTP/2 PING keepalives are enabled in the gRPC client/server.
    /etc/nginx/conf.d/stream.grpc.example.org.conf
    server {
        listen 443 ssl;
        http2 on;
        server_name stream.grpc.example.org;
    
        # ssl_certificate / ssl_certificate_key / snippets/tls.conf
    
        http2_max_concurrent_streams 256;
        keepalive_requests           10000;
        keepalive_time               4h;
        keepalive_timeout            1h;
    Key part

    Raise HTTP/2 connection limits for busy streaming channels: http2_max_concurrent_streams 256 widens parallel streams per connection, keepalive_requests 10000 delays GOAWAY, and keepalive_time 4h prevents a 1-hour cutoff on long sessions.

    default:http2_max_concurrent_streams 128keepalive_requests 1000keepalive_time 1hkeepalive_timeout 75s

        location /events.StreamService/ {
            client_max_body_size  0;
            client_body_timeout   1h;
            grpc_read_timeout     1h;
            grpc_send_timeout     1h;
            grpc_socket_keepalive on;
    
            grpc_set_header X-Real-IP       $remote_addr;
            grpc_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            grpc_pass grpc://grpc_orders;
    
            error_page 502 503 = /error_grpc_unavailable;
            error_page 504     = /error_grpc_timeout;
        }
    
        # location = /error_grpc_unavailable and /error_grpc_timeout — same as Scenario 1
    }
    Key part

    Raise timeouts in both directions on the streaming location and turn on TCP keepalive toward the backend. client_max_body_size 0 lifts the total size cap on client streams (otherwise a long stream hits the cumulative body limit). Avoid setting huge timeouts like 24h without application-level gRPC PING keepalives, or half-open dead streams will hold memory.

    default:grpc_read_timeout 60sgrpc_send_timeout 60sclient_body_timeout 60sgrpc_socket_keepalive off

    Scenario 3: TLS to the backend (grpcs://) and mTLS

    When the gRPC service runs on another host or requires end-to-end TLS, switch the scheme to grpcs:// and enable backend certificate verification. grpc_ssl_verify defaults to off — without it, nginx accepts any forged certificate between itself and the backend.

    /etc/nginx/conf.d/grpcs-upstream.conf
    upstream grpc_remote {
        server 10.0.0.21:50051;
        server 10.0.0.22:50051;
        keepalive 32;
    }
    
    server {
        listen 443 ssl;
        http2 on;
        server_name secure.grpc.example.org;
    
        # ssl_certificate / ssl_certificate_key / snippets/tls.conf
    
        location /billing.BillingService/ {
            grpc_pass grpcs://grpc_remote;
    
            grpc_ssl_server_name         on;
            grpc_ssl_name                billing.internal.example.org;
            grpc_ssl_verify              on;
            grpc_ssl_trusted_certificate /etc/nginx/certs/internal-ca.crt;
    Key part

    grpcs:// encrypts the nginx-to-backend leg over TLS + HTTP/2. grpc_ssl_server_name on sends SNI during the handshake, grpc_ssl_name sets the expected certificate hostname (needed when upstream lists raw IP addresses), and grpc_ssl_verify on validates the chain against your internal CA.

    default:grpc_ssl_server_name offgrpc_ssl_verify off

            # For mTLS between nginx and the backend:
            # grpc_ssl_certificate     /etc/nginx/certs/nginx-client.crt;
            # grpc_ssl_certificate_key /etc/nginx/certs/nginx-client.key;
    
            grpc_next_upstream error timeout invalid_header http_502 http_503 http_504;
            grpc_next_upstream_tries 2;
        }
    }

    If the backend requires a client certificate from nginx (mTLS), uncomment grpc_ssl_certificate and grpc_ssl_certificate_key. grpc_next_upstream retries are safe only for idempotent reads — for write RPCs (creating orders, charging cards) keep grpc_next_upstream error; or off (Load balancing).

    How to check

    1. Validate syntax (catches trailing slashes on grpc_pass and certificate path typos) and apply with a zero-downtime reload so open streams stay up (reload instead of restart):
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify HTTP/2 negotiation, call delivery, and the grpc-status trailer using plain curl (no extra tools required):
      curl -sS -v --http2 -X POST \
        -H "Content-Type: application/grpc" \
        -H "TE: trailers" \
        https://grpc.example.org/orders.OrderService/Ping \
        -o /dev/null
      # * using HTTP/2
      # < HTTP/2 200
      # < content-type: application/grpc
      # < grpc-status: 0
      If the server enables gRPC Reflection and you have grpcurl, list services and methods with grpcurl grpc.example.org:443 list.
    3. Stop the backend and test error mapping: the response should return HTTP/2 200, content-type: application/grpc, grpc-status: 14, and grpc-message: unavailable with no HTML body.

    If it doesn’t work

    A gRPC client disconnects right away with an HTTP/2 error (unexpected data while we expected SETTINGS frame or ALPN h2 rejected)

    Cause
    http2 on; is missing from the server block, so nginx speaks HTTP/1.1 while gRPC requires HTTP/2.
    Fix
    Add http2 on; inside server (nginx 1.25.1+ syntax, HTTPS & HTTP/3) and apply with sudo nginx -t && sudo systemctl reload nginx.

    Through nginx, clients get an HTML 502 Bad Gateway page instead of a gRPC response, and error.log shows recv() failed (104: Connection reset by peer)

    Cause
    The location block uses proxy_pass instead of grpc_pass: nginx sent an HTTP/1.1 request to an HTTP/2 backend, which reset the connection (or stripped HTTP/2 grpc-status trailers).
    Fix
    Switch proxy_pass http://... to grpc_pass grpc://... (or grpcs://... for backend TLS) and drop proxy_set_header Connection.

    nginx -t fails with invalid host in upstream "127.0.0.1:50051/"

    Cause
    A trailing slash was left on grpc_pass out of habit from proxy_pass. grpc_pass accepts only a scheme, host, and port (or an upstream name) with no URI path.
    Fix
    Remove the trailing slash: grpc_pass grpc://127.0.0.1:50051;.

    A server-streaming or bidirectional stream breaks at exactly 60 seconds with INTERNAL_ERROR (RST_STREAM), and error.log logs upstream timed out (110: Connection timed out) while reading upstream

    Cause
    One minute of silence passed between stream messages, hitting the default grpc_read_timeout 60s (or grpc_send_timeout / client_body_timeout on client streams).
    Fix
    Raise grpc_read_timeout, grpc_send_timeout, and client_body_timeout to fit real idle gaps (e.g., 1h), turn on grpc_socket_keepalive on;, and raise keepalive_time if a stream runs longer than an hour.

    When a backend goes down, the gRPC client fails trying to parse an HTML 502 Bad Gateway page instead of receiving UNAVAILABLE

    Cause
    By default nginx serves its standard text/html 502 error page, which gRPC clients can’t decode as a valid gRPC response.
    Fix
    Intercept 502/503 via error_page 502 503 = /error_grpc_unavailable; and return an empty HTTP/2 200 with default_type application/grpc;, add_header grpc-status 14;, and return 200 "";.

    Sending a Protobuf message larger than 1 MB fails with 413, or a response with large metadata fails with 502 upstream sent too big header

    Cause
    nginx defaults client_max_body_size to 1m (while gRPC libraries default to 4 MiB) and grpc_buffer_size to 4k.
    Fix
    Set client_max_body_size 4m; (or higher to match your payload limit, client_max_body_size limit) and grpc_buffer_size 16k; (upstream sent too big header).