API Hosting and Routing using NGNIX
Using Nginx for Hosting and Routing APIs
1. Hosting APIs with Nginx
When used to host APIs, Nginx serves as a reverse proxy that receives incoming HTTP(S) requests and forwards them to backend services (often written in Node.js, Python, Go, etc.).
Example
Let’s say you have a REST API running on localhost:3000
. You can configure Nginx to expose it on https://api.example.com/
like so:
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
This configuration:
- Routes all requests from
api.example.com
to the backend app on port 3000. - Preserves the client IP and host info for the backend.
2. API Routing with Nginx
In microservices, you may have multiple services (e.g., /users
, /orders
, /payments
). Nginx routes incoming requests to the correct service.
Example
server {
listen 80;
location /users/ {
proxy_pass http://user-service:4000/;
}
location /orders/ {
proxy_pass http://order-service:5000/;
}
location /payments/ {
proxy_pass http://payment-service:6000/;
}
}
This configuration lets you route:
/users/...
→ user service/orders/...
→ order service/payments/...
→ payment service
3. Service Discovery with Nginx
Nginx itself does not do dynamic service discovery out of the box. But there are three common ways to integrate it:
A. Static Configuration
You define backend IPs or hostnames directly in the config.
upstream user_service {
server 10.0.0.21:4000;
server 10.0.0.22:4000;
}
B. DNS-based Service Discovery
If you’re in a dynamic environment (e.g., Docker Swarm, Kubernetes), services can be registered via DNS:
upstream user_service {
server user-service.default.svc.cluster.local:4000;
}
C. Dynamic Reconfiguration
You can use tools to auto-update the Nginx config when services change:
- Consul Template: Watches for changes and rewrites
nginx.conf
. - Lua + Nginx (via OpenResty): Allows dynamic routing logic within Nginx itself.
Bonus: Nginx as an API Gateway
If you use Nginx Plus, you get features like:
- Active health checks
- JWT validation
- Rate limiting
- Advanced load balancing
- Native service discovery
With OpenResty (Nginx + Lua), you can build custom logic. Example:
-- Lua-based routing
if uri:match("^/v2/users") then
proxy_pass("http://new-user-service")
end
Summary Table
Role | What Nginx Does |
---|---|
API Hosting | Acts as reverse proxy to backend services |
API Routing | Directs requests to correct microservice |
API Discovery | Via DNS, templates, or Lua scripting |
Load Balancing | Distributes traffic across instances |
SSL Termination | Handles HTTPS so backend doesn’t have to |
Leave a Reply