Part 3 – Web Farm Example (Docker, Redis Cache, Haproxy, .Net Core Web API)

In this last article, I will add haproxy to project to load balancing. To add haproxy to project, first I will add a file that named haproxy.cfg to configure the haproxy.

global
    maxconn 4096

defaults
    mode http
    timeout connect 5s
    timeout client 50s
    timeout server 50s

listen http-in
    bind *:8080

    server web-1 dockerconfig_ali_webapi_1:80
    server web-2 dockerconfig_ali_webapi_2:80
	server web-3 dockerconfig_ali_webapi_3:80

    stats enable
    stats uri /haproxy
    stats refresh 1s

And I am modifiying docker-compose.yml and up.ps1 like following.

docker-compose.yml

version: '2'

services:

    ali_redis:  
        image: ali/redis
        ports:
            - "6379:6379"

    ali_webapi:
        image: ali/webapi
        environment:
            - ASPNETCORE_ENVIRONMENT=Staging
            
    load_balancer:
        image: haproxy:1.7.1
        volumes:
            - "./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg"
        ports:
            - "9911:8080"

up.ps1

docker rm $(docker ps -aq)
docker-compose up -d ali_redis
sleep 3
docker-compose up -d ali_webapi
sleep 2
docker-compose scale ali_webapi=3
sleep 2
docker-compose up -d load_balancer

And the result:

docker build and up

docker ps

How can we know if it works?

I am modifiying the GetCacheData action that is in ValuesController.cs

[HttpGet("GetCacheData")]
public string GetCacheData()
{
    try
    {
        var time = Encoding.UTF8.GetString(_memoryCache.Get("serverTime"));
        ViewBag.data = time;
 
        return "Server time: " + time + " - Machine name: " + Environment.MachineName;
    }
    catch (Exception ex)
    {
        return ex.GetBaseException().Message;
    }
}

I added machine name to returning data to understand which web api application is calling.

Set cache data

After set cache data, I will try to get the same cache value for different machines.

Capture19Capture20Capture21

As you can see, when I refresh the GetCacheData page, I can get the same value for different machines. And also it is possible to see haproxy is working with using haproxy web interface, too.

Haproxy web interface

When you refresh the GetCacheData page, you can see that the haproxy is routing the requests to different machines. You can track which machine is running under Sessions > Cur tab.

Source code of the project finished version: https://github.com/alirizaadiyahsi/WebFarmExample

Part 1 – Web Farm Example (Docker, Redis Cache, Haproxy, .Net Core Web API)

Part 2 – Web Farm Example (Docker, Redis Cache, Haproxy, .Net Core Web API)

#net-core, #docker, #haproxy, #redis-cache, #web-api, #web-farm