148 views
asked in Technology by
HAProxy Load Balancer Install, Configure, Self Sign SSL, Tuning and ASP.NET Code for Session Sticky Testing on Ubuntu 24.04 LTS for IIS Servers

1 Answer

answered by

Chirag's Technology Tutorial

*********************************************************************************

*HAProxy Install, Configure, Self Sign SSL, Tuning and ASP.NET Code for Session Sticky Testing on Ubuntu 24.04 LTS for IIS Servers*

*********************************************************************************

YouTube Video:

https://youtu.be/RoLfSzsEa38

Here's a step-by-step guide for HAProxy Install, Configure, Self Sign SSL, Tuning and ASP.NET Code for Session Sticky Testing on Ubuntu 24.04 LTS for IIS Servers.

HAProxy Server IP : 192.168.224.129
IIS Server1 IP : 192.168.224.133
IIS Server2 IP : 192.168.224.134

Part 1: Install HAProxy and Configure

Step 1: Install HAProxy

Update system packages:

sudo apt update && sudo apt upgrade -y

Install HAProxy:

sudo apt install haproxy -y

Verify installation:

haproxy -v

Step 2: Configure HAProxy for Load Balancing with Session Stickiness

Edit HAProxy configuration file:

sudo nano /etc/haproxy/haproxy.cfg

Configure Global Settings (ensure logs are enabled for debugging):

global
    log /dev/log local0
    log /dev/log local1 notice
    maxconn 2048
    daemon
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s

Configure Default Settings (for timeouts and logging):

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms
    retries 3

Set Up Frontend and Backend Configuration with Sticky Sessions:

Frontend Configuration: Define where requests from clients will be accepted.

Backend Configuration: Define the servers to which HAProxy will forward requests.

Add the following to haproxy.cfg:

frontend iis_frontend
    bind *:80
    mode http
    default_backend iis_backend

backend iis_backend
    mode http
    maxconn 60000
    balance roundrobin
    option httpclose
    option httpchk
    option prefer-last-server
    option http-keep-alive
    option forwardfor
    cookie SRVNAME insert
    cookie SERVERID insert indirect nocache
    server iis_server1 192.168.224.133:80 check cookie s1
    server iis_server2 192.168.224.134:80 check cookie s2

Explanation:

1. mode http

Purpose: Defines the mode in which HAProxy operates.

Usage: http mode is used for handling HTTP traffic (as opposed to tcp mode, which would handle raw TCP traffic). It enables features specific to HTTP, such as URL-based routing, headers manipulation, and more.

2. maxconn 60000

Purpose: Limits the maximum number of concurrent connections to the backend.

Usage: The value 60000 allows HAProxy to handle up to 60,000 concurrent connections to the backend servers. This value can be adjusted based on the expected server load and the capacity of the backend servers.

3.balance roundrobin

Purpose: Defines the load balancing algorithm.

Usage: roundrobin distributes incoming requests evenly across the backend servers in a cyclic manner. It’s a simple and fair method for load balancing when backend servers are similarly sized and capable.

4. option httpclose

Purpose: Closes the connection to the backend server after each HTTP request.

Usage: This option ensures that HAProxy will not keep the connection open between requests, which can help reduce the number of open connections to the backend and avoid potential resource exhaustion.

5. option httpchk

Purpose: Enables HTTP health checks for backend servers.

Usage: HAProxy will periodically send HTTP requests to the backend servers to check if they are healthy and able to handle traffic. By default, it sends a simple GET request to the root URL (/), but this can be customized.

6. option prefer-last-server

Purpose: Tries to reconnect the client to the last backend server they were assigned to, if that server is still available.

Usage: This is useful for improving session persistence. While it doesn't guarantee stickiness like cookies, it provides a "best-effort" approach to returning clients to the same server.

7. option http-keep-alive

Purpose: Allows HTTP keep-alive connections.

Usage: This option instructs HAProxy to maintain connections to backend servers for reuse across multiple HTTP requests, improving performance by reducing the overhead of establishing new connections.

8. option forwardfor

Purpose: Adds the client's original IP address to the X-Forwarded-For HTTP header.

Usage: Since HAProxy acts as a reverse proxy, it’s useful for backend servers to know the actual client IP. This is commonly used for logging, security checks, or rate limiting.

9. cookie SRVNAME insert

Purpose: Enables session persistence via cookies.

Usage: This creates a cookie named SRVNAME on the client’s browser, allowing HAProxy to direct requests from the same client to the same backend server. This ensures "sticky sessions" where the client is consistently sent to the same backend server.

10. cookie SERVERID insert indirect nocache

Purpose: Configures an additional cookie for session persistence.

Usage:

SERVERID is the name of the cookie that HAProxy will insert into the client’s browser.

insert: HAProxy will insert this cookie into the response.

indirect: This ensures that the cookie is only set for responses from HAProxy and not from backend servers.

nocache: Instructs clients to not cache the cookie, ensuring it’s always freshly set by HAProxy.

11. server iis_server1 192.168.224.133:80 check cookie s1

Purpose: Defines the backend server.

Usage:

iis_server1: The name used to identify the backend server within HAProxy.

192.168.224.133:80: The IP address and port of the backend server.

check: Enables health checks for this backend server.

cookie s1: Specifies the value of the cookie (s1) that HAProxy will insert for this server. Clients with this cookie will be directed to iis_server1 for future requests, maintaining session stickiness.

Step 3: Test and Enable HAProxy

Check HAProxy configuration for errors:

sudo haproxy -f /etc/haproxy/haproxy.cfg -c

Restart HAProxy to apply changes:

sudo systemctl restart haproxy

Enable HAProxy to start at boot:

sudo systemctl enable haproxy

Step 4: Verify the Configuration

Open a web browser or use curl to test:

Navigate to 

http://192.168.224.129

and HAProxy should distribute the requests to IIS servers with session persistence.

Check Logs for Issues (Optional):

sudo tail -f /var/log/haproxy.log

Step 5: Tuning HAProxy (Optional)

Adjust Maximum Connections (in global section):

maxconn 4096

Optimize Timeouts in defaults to suit application requirements:

timeout connect 5000
timeout client  60000
timeout server  60000

Monitor HAProxy Statistics: Configure the statistics page for real-time monitoring by adding this to the end of haproxy.cfg:

listen stats
    bind *:8080
    mode http
    stats enable
    stats uri /haproxy?stats
    stats refresh 10s
    stats auth admin:admin@123

Then, access the stats page at 

http://192.168.224.129:8080/haproxy?stats

Part 2 : Add a Machine Key to the IIS servers

Adding a machine key to the IIS servers is a method to ensure consistent session persistence across multiple IIS servers. Here’s how to add a machine key to achieve consistent sticky sessions.

Step 1: Configure Machine Key on IIS Servers

Log in to each IIS server (192.168.224.133 and 192.168.224.134).

Open IIS Manager:

Press Windows + R, type inetmgr, and press Enter.

Navigate to the Application Level:

In the left panel, expand the server node, then expand Sites and select your application.

Open the Machine Key Settings:

In the middle panel, double-click Machine Key.

Set Consistent Validation and Decryption Keys:

Under Validation Key and Decryption Key, set both to use a consistent custom key across all IIS servers (Generate the keys from right panel).

Example:

Validation Key: C5C76403C2033957A103B713C5500ACCB0B92B77D2F0A94A12F5D6D0AA94DC911C707421B8B6E581B76FCC819D9407FDB0B1C9796331509963267E324BCB548A

Decryption Key: 1C3B97FE9EB4EEA7157E042832784B79F2CB35346623FED3

Note: Use a secure, unique key string for production environments. These should match exactly on each IIS server for sticky sessions.

Choose Encryption and Validation Methods:

Set Validation to SHA1 or another preferred encryption method.

Set Decryption to AES.

Apply the Configuration:

Click Apply in the Actions pane to save the changes.

Step 2: Verify Session Stickiness

Restart the IIS Services on both servers:

iisreset

Test Sticky Sessions:

Open a browser and access 

http://192.168.224.129

Login or interact with your application to generate a session, then refresh or navigate across pages to verify session persistence on the same server.

Step 3: Adjust HAProxy Configuration (If Needed)

If further tuning for stickiness is required, consider adjusting HAProxy session timeout settings as follows in the backend configuration:

backend iis_backend
    cookie SERVERID insert indirect nocache
    option http-server-close
    timeout client 1h
    timeout server 1h

With this setup, both HAProxy and IIS machine keys work together to ensure sessions remain sticky across multiple servers.

Part 3: Sample Code for Session Sticky test

To test session stickiness, you can use a simple PHP or ASP.NET script that displays the server's IP address and the session ID. This will help confirm that the client is consistently routed to the same server for the duration of the session.

Option 1: PHP Code for Session Sticky Testing

Create a PHP file (session_test.php) on each IIS server in the web root directory (e.g., C:\inetpub\wwwroot).

Add the following code:

<?php
session_start();
if (!isset($_SESSION['session_id'])) {
    $_SESSION['session_id'] = session_id();
}
echo "Server IP: " . $_SERVER['SERVER_ADDR'] . "<br>";
echo "Session ID: " . $_SESSION['session_id'] . "<br>";
?>

Access the PHP page via HAProxy, e.g., 

http://192.168.224.129/session_test.php

and refresh the page multiple times.

Expected Result: The Server IP should remain consistent across requests, and the Session ID should stay the same, indicating sticky sessions are working.

Option 2: ASP.NET Code for Session Sticky Testing

Create an ASP.NET page (SessionTest.aspx) on each IIS server in the application folder.

Add the following code:

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["SessionID"] == null)
        {
            Session["SessionID"] = Session.SessionID;
        }
        Response.Write("Server IP: " + Request.ServerVariables["LOCAL_ADDR"] + "<br>");
        Response.Write("Session ID: " + Session["SessionID"] + "<br>");
    }
</script>
<!DOCTYPE html>
<html>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Literal ID="Literal1" runat="server"></asp:Literal>
        </div>
    </form>
</body>
</html>

Access the ASP.NET page via HAProxy, e.g., 

http://192.168.224.129/SessionTest.aspx

Expected Result: Similar to the PHP example, the Server IP should stay the same across requests, with a consistent Session ID, confirming that sticky sessions are active.

This simple script helps verify if session stickiness is working by checking that the requests go to the same backend server.

KB Article:

"option httpchk vs option http-server-close"

In HAProxy, option httpchk and option http-server-close serve different purposes:

1. option httpchk

Purpose: Health check option to verify if backend servers are available and responsive.

Usage: HAProxy sends HTTP requests to the backend servers at regular intervals to confirm they’re up and can handle traffic.

Configuration: Typically used in the backend section to set up health checks for each server.

Example:

backend iis_backend

    option httpchk GET /healthcheck

    server iis_server1 192.168.224.133:80 check

    server iis_server2 192.168.224.134:80 check

Here, option httpchk GET /healthcheck tells HAProxy to request the /healthcheck endpoint on each server to determine if it’s healthy.

2. option http-server-close

Purpose: Manages connection handling between clients and backend servers to improve performance and prevent connection exhaustion.

Usage: This option closes the server connection after the response is sent to the client, but keeps the client-side connection open. This can reduce server load by ensuring connections are not held open unnecessarily.

Configuration: Commonly set in the defaults or backend sections to control connection behavior.

Example:

backend iis_backend
    option http-server-close
    balance roundrobin
    server iis_server1 192.168.224.133:80 check
    server iis_server2 192.168.224.134:80 check

When to Use Each

Use option httpchk: When you need to monitor server health and ensure that traffic only goes to healthy servers.

Use option http-server-close: When you want to manage connections efficiently, especially useful for web applications to reduce server load and improve response times by closing server connections promptly after the response.

In many configurations, both can be used together to ensure both health monitoring (httpchk) and efficient connection management (http-server-close).

Part 4 : Self-Signed SSL Certificate

1. Use a Self-Signed SSL Certificate

A self-signed certificate allows encryption, although browsers will display a warning because it's not from a trusted certificate authority (CA).

2. Use an Internal Certificate Authority (CA)

If you have multiple internal users, you could set up an internal CA and install its root certificate on each device accessing the server. This way, the certificate will appear trusted without warnings.

Here’s how to generate and configure a self-signed certificate for HAProxy on Ubuntu 24.04:

Step-by-Step Guide for Self-Signed SSL Certificate

Generate a Self-Signed SSL Certificate

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/selfsigned.key -out /etc/ssl/certs/selfsigned.crt

You will be prompted to fill out details for the certificate. For Common Name (CN), use the server's IP (e.g., 192.168.224.129).

Combine the Certificate and Key

Combine the certificate and private key into a single file for HAProxy:

sudo cat /etc/ssl/certs/selfsigned.crt /etc/ssl/private/selfsigned.key | sudo tee /etc/ssl/private/haproxy-selfsigned.pem

Configure HAProxy to Use the Self-Signed Certificate

Open the HAProxy configuration file:

sudo nano /etc/haproxy/haproxy.cfg

Modify the frontend section to use SSL with the self-signed certificate:

frontend iis_frontend
    bind *:80
    bind *:443 ssl crt /etc/ssl/private/haproxy-selfsigned.pem
    mode http
    redirect scheme https code 301 if !{ ssl_fc }
    default_backend iis_backend

Restart HAProxy

Check the configuration and restart HAProxy:

sudo haproxy -f /etc/haproxy/haproxy.cfg -c
sudo systemctl restart haproxy

Access the Server

Now, you can access 

https://192.168.224.129

but browsers will show a warning due to the self-signed nature of the certificate. You can bypass the warning manually or install the certificate in trusted root stores on client devices if this is an internal network.

This setup provides SSL encryption without needing a domain name, suitable for private or development environments.

Final Note: 

This configuration enables load balancing with session stickiness for the IIS servers. You may adjust the timeout and maximum connection values based on traffic load and system capacity.

For any doubts and query, please write on YouTube video comments section.

Note : Flow the Process shown in video.

Please, Subscribe and like for more videos:

https://www.youtube.com/@chiragstutorial

Don't forget to, Follow, Like, Share &, Comment

Thanks & Regards,

Chitt Ranjan Mahto "Chirag"

_____________________________________________________________________

Note: All scripts used in this demo will be available in our website.

Link will be available in description.

#chirags 

#chiragstutorial 

#chiragsTechnologytutorial

#chiragsTechnologytutorials

#Technologytutorial 

#Technology 

#Technologycourse 

chirags, chirags tutorial, chirags Technology tutorial, chirags Technology tutorial, HAProxy Install, Configure, Self Sign SSL, Tuning and ASP.NET Code for Session Sticky Testing on Ubuntu 24.04 LTS for IIS Servers

commented by Purab
Testing Your comment on this answer:

Most popular tags

postgresql laravel replication laravel-10 ha postgresql mongodb ubuntu 24.04 lts mongodb database mongodb tutorial streaming-replication laravel-11 mysql database laravel postgresql backup laravel login register logout database mysql php technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 - login with otp valid for 10 minutes. laravel 11 gaurds user and admin registration user and admin login multiauth postgresql 16 to postgresql 17 postgresql migration zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase ubuntu 24.04 koha 24.05 letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...