harbor run -t LiteCoder/nginx-consul-service-discoveryharbor download LiteCoder/nginx-consul-service-discoverySet up an Nginx reverse proxy that dynamically discovers and routes traffic to backend services using Consul for DNS-based service discovery.
Consul Agent
127.0.0.1.8600, HTTP API on port 8500.Backend Services
{"service": "<name>", "port": <port>} on any HTTP GET request.
web-api on port 8001web-api on port 8002web-api on port 8003web-apiweb-api-1, web-api-2, web-api-3)Nginx Configuration
80.127.0.0.1:8600) as the resolver with valid=5s./api/ that proxies requests to the backend services discovered via Consul DNS. The upstream host should be resolved using the Consul DNS name for the web-api service (i.e., web-api.service.consul).X-Real-IP, X-Forwarded-For, X-Forwarded-Proto, Host./app/
├── nginx/
│ └── nginx.conf # Full Nginx configuration
├── consul/
│ └── web-api.json # Consul service definition file for all three instances
├── services/
│ ├── backend.py # Python HTTP backend service (accepts --port argument)
│ └── start_services.sh # Script to start all three backend instances in background
├── test.sh # Test script (described below)
└── output.json # Test results output
The file /app/consul/web-api.json must be a valid JSON file that defines the three service instances for Consul registration. Each service entry must include Name, ID, Port, and a Check with an HTTP health check.
/app/test.sh)Create an executable bash script at /app/test.sh that:
http://127.0.0.1:8500/v1/status/leader returns a non-empty response).http://127.0.0.1:8500/v1/catalog/service/web-api) and confirms 3 instances are registered.http://localhost/api/ via Nginx and collects the responses.Write results to /app/output.json in this exact format:
{
"consul_running": true,
"backends_healthy": true,
"registered_services_count": 3,
"nginx_proxy_success": true,
"total_requests": 6,
"successful_responses": 6
}
consul_running: true if Consul's leader endpoint returns a valid response.backends_healthy: true if all three ports (8001, 8002, 8003) respond to HTTP GET.registered_services_count: integer count of web-api services in Consul catalog.nginx_proxy_success: true if all 6 requests through Nginx returned valid JSON with a service key.total_requests: always 6.successful_responses: count of requests that returned HTTP 200 with valid JSON.chmod +x /app/test.sh) and produce /app/output.json when run.