Skip to content

Instantly share code, notes, and snippets.

@lcrilly
Last active April 6, 2021 09:37
Show Gist options
  • Save lcrilly/e49501131137fe103419d553b6e1409b to your computer and use it in GitHub Desktop.
Save lcrilly/e49501131137fe103419d553b6e1409b to your computer and use it in GitHub Desktop.
Active health checks for gRPC endpoints with NGINX Plus
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log debug;
pid nginx.pid;
events { worker_connections 1024; }
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
upstream grpc_endpoints {
server 10.0.0.1;
server 10.0.0.2;
server 10.0.0.3;
}
server {
listen 50051 http2; # This is unencrypted, plaintext gRPC. Use 'ssl' parameter to enable TLS.
location / {
# The 'grpc://' prefix is optional; unencrypted gRPC is the default
# Use 'grpcs://' for TLS-encrypted gRPC services
grpc_pass grpc://grpc_endpoints;
error_page 502 = @grpc_unavailable; # If no healthy servers then send the appropriate gRPC response
}
# Simple gRPC health check
# Sends a dummy gRPC request, expecting a grpc-status=14 response to indicate
# service unavailable, which tells us there is a live gRPC service listening.
location @grpc_health {
health_check mandatory uri=/nginx.health/check match=grpc_response; # Other parameters as required
grpc_set_header Content-Type application/grpc;
grpc_set_header TE trailers;
grpc_pass grpc://grpc_endpoints;
}
# Generates a gRPC-compliant error response
location @grpc_unavailable {
default_type application/grpc;
add_header grpc-status 14;
add_header grpc-message unavailable;
return 204;
}
}
# This is the expected response from a gRPC health check
match grpc_response {
header Content-Type = application/grpc;
header grpc-status = 12; # unimplemented / unknown method
}
}
@vladimirkokshenev
Copy link

Probably, @grpc_health location requires one more directive:
grpc_set_header content-type "application/grpc".

@lcrilly
Copy link
Author

lcrilly commented Oct 1, 2020

Thanks! Done (L42).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment