In modern microservices architectures, applications are rarely monolithic. Instead, they consist of distinct services—such as an authentication service, an inventory API, and a notification engine—that communicate over internal networks. Exposing all these endpoints directly to the public internet is a security risk and creates operational chaos. The industry standard solution is a reverse proxy, typically implemented using Nginx. This guide details how to configure a custom Nginx reverse proxy to route traffic between multiple internal microservices securely and efficiently.
This tutorial assumes a Linux environment (Ubuntu 22.04 LTS or similar) running systemd. We will cover the prerequisites, directory permissions, configuration syntax, SSL termination basics, monitoring considerations, and troubleshooting common errors. This content is intended for IT students, junior engineers, and practitioners looking to implement robust service mesh patterns without relying on heavy orchestration tools like Kubernetes initially.
Prerequisites and Environment Setup
Before modifying Nginx configurations, ensure your environment meets the following requirements:
* OS: A Linux distribution with systemd (e.g., Ubuntu, Debian, CentOS).
* Nginx: Version 1.24 or later is recommended for modern syntax support.
* Services: Two local applications running on http://localhost:3000 and http://localhost:3001. These represent your internal microservices.
* Security: SSH access configured with key-based authentication; root login disabled via /etc/ssh/sshd_config.
Directory Permissions: Ensure the Nginx worker process (usually running as www-data) has read permissions for configuration files but not write permissions to sensitive directories. Create a dedicated directory for service logs outside the default Nginx log path if desired:
sudo mkdir -p /var/log/my-microservices
sudo chown www-data:adm /var/log/my-microservices
sudo chmod 750 /var/log/my-microservices
Installing and Verifying Nginx
If Nginx is not installed, update your package lists and install the latest stable version. It is crucial to verify the installation immediately after setup.
sudo apt update
sudo apt install nginx -y
sudo systemctl status nginx
Expected output for a healthy status:
● nginx.service - A high performance reverse proxy and HTTP server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled)
Active: active (running) since ...
If the service is not active, start it with sudo systemctl start nginx. Always check the error log at /var/log/nginx/error.log if the service fails to start. Common causes include syntax errors in the main configuration file or missing dependencies.
Configuring Upstream Blocks and Location Routing
The core of a reverse proxy setup involves defining “upstreams”—groups of backend servers—and mapping incoming URLs to specific upstreams. Edit the default configuration file located at /etc/nginx/sites-available/default (or create a new file in sites-enabled).
Below is an example configuration that routes traffic for /auth-service to port 3000 and /inventory-service to port 3001:
server {
listen 80;
server_name localhost;
# Route Authentication Service
location /auth-service {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Timeout settings for long-running auth operations
proxy_connect_timeout 60s;
proxy_read_timeout 120s;
}
# Route Inventory Service
location /inventory-service {
proxy_pass http://127.0.0.1:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Different timeout for inventory lookups
proxy_connect_timeout 30s;
proxy_read_timeout 60s;
}
# Default catch-all
location / {
return 404 "No service found for this path";
}
}
Explanation of Directives:
* proxy_pass: Defines the backend address. Using 127.0.0.1 ensures the proxy talks to local services, not external hosts.
* proxy_set_header: Crucial for passing client information (like the original IP) to the backend service so they can log requests correctly or enforce rate limits.
* proxy_read_timeout: Prevents Nginx from timing out while waiting for a slow backend response.
Security Considerations and SSL Termination
Running services over plain HTTP in production is generally discouraged. While this guide focuses on routing, a complete setup requires SSL termination at the Nginx layer. You should obtain certificates via Let’s Encrypt using Certbot.
When handling SSL, ensure private keys are not world-readable. The www-data user must have read access to the certificate but no write access:
sudo chown root:www-data /etc/letsencrypt/live/your-domain.com/fullchain.pem
sudo chmod 644 /etc/letsencrypt/live/your-domain.com/fullchain.pem
sudo chown root:root /etc/letsencrypt/live/your-domain.com/privkey.pem
sudo chmod 600 /etc/letsencrypt/live/your-domain.com/privkey.pem
Security Warning: Never expose internal microservice ports (like 3000 or 3001) directly to the public internet. Always route traffic through Nginx. If a backend service crashes, Nginx can be configured to return a generic “Service Unavailable” page instead of exposing an error stack trace to the user.
Monitoring and Logging Strategy
Effective monitoring is essential for troubleshooting. Configure Nginx to send access logs in JSON format for easier parsing by tools like ELK Stack or Prometheus:
access_log /var/log/my-microservices/nginx-access.log json;
error_log /var/log/my-microservices/nginx-error.log warn;
To monitor the health of your upstream services, you can add a try_files directive or use Nginx Plus health check endpoints. For standard setups, ensure your backend applications respond to a /health endpoint. You can configure Nginx to fail over if the backend does not respond within a specific time:
location /auth-service {
proxy_pass http://127.0.0.1:3000;
# ... headers ...
# Return 503 if upstream is down
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
This ensures high availability by retrying the request on a different instance or returning an error gracefully if all instances are down.
Verification and Troubleshooting Common Errors
After making changes, always test the configuration before reloading to prevent downtime:
sudo nginx -t
If this returns syntax is ok and test is successful, you can reload Nginx without stopping connections:
sudo systemctl reload nginx
Common Errors and Fixes:
* Error 502 Bad Gateway: This usually means the backend service (port 3000/3001) is not listening or crashed. Check systemctl status <backend-service> and verify the port with sudo netstat -tlnp | grep 3000.
* Error 403 Forbidden: Often caused by incorrect file permissions on static assets or misconfigured root directives in Nginx.
* Connection Refused: Indicates the backend application is not running. Ensure your microservices are started and bound to 127.0.0.1, not localhost (which sometimes resolves differently depending on system configuration).
Student Practice Task
To solidify these concepts, students should attempt the following lab exercise:
1. Set up two Python Flask applications on ports 5000 and 5001.
2. Configure Nginx to route /api/user to port 5000 and /api/product to port 5001.
3. Simulate a failure by stopping the service on port 5000.
4. Observe how Nginx handles the request (does it timeout immediately or return a configured error page?).
5. Restart the service and verify traffic resumes normally.
This hands-on approach reinforces the importance of resilience in microservice architectures and ensures that junior engineers understand not just how to configure, but how to maintain and troubleshoot these systems under pressure.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

