How to set up Nginx as a load balancer with session persistence for sticky sessions?

To set up Nginx as a load balancer with session persistence for sticky sessions, follow these steps:

  1. Install Nginx:

    • For Ubuntu/Debian: sudo apt-get install nginx
    • For CentOS/RHEL: sudo yum install nginx
  2. Open the Nginx configuration file:

    • For Ubuntu/Debian: sudo nano /etc/nginx/nginx.conf
    • For CentOS/RHEL: sudo vi /etc/nginx/nginx.conf
  3. 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 }
  4. 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; } }
  5. Save the configuration file and exit the text editor.

  6. Test the Nginx configuration for syntax errors:

    • For Ubuntu/Debian: sudo nginx -t
    • For CentOS/RHEL: sudo nginx -t -c /etc/nginx/nginx.conf
  7. If the configuration test is successful, restart Nginx to apply the changes:

    • For Ubuntu/Debian: sudo systemctl restart nginx
    • For CentOS/RHEL: 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.