To set up Nginx as a load balancer with session persistence for sticky sessions, follow these steps:
Install Nginx:
sudo apt-get install nginx
sudo yum install nginx
Open the Nginx configuration file:
sudo nano /etc/nginx/nginx.conf
sudo vi /etc/nginx/nginx.conf
Add the following configuration inside the http
block:
upstream backend {
server backend1.example.com;
server backend2.example.com;
# Add more backend servers here if needed
}
Add the following configuration inside the server
block:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
# Enables session persistence using cookies
proxy_cookie_path / "/; secure; HttpOnly";
proxy_cookie_domain example.com;
# Enables session persistence using IP hash
# ip_hash;
}
}
Save the configuration file and exit the text editor.
Test the Nginx configuration for syntax errors:
sudo nginx -t
sudo nginx -t -c /etc/nginx/nginx.conf
If the configuration test is successful, restart Nginx to apply the changes:
sudo systemctl restart nginx
sudo service nginx restart
Nginx is now configured as a load balancer with session persistence for sticky sessions. Client requests will be distributed among the backend servers using the configured algorithm (default is round-robin) while maintaining session persistence based on cookies or IP hash.