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.

    maxconn 4096

    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.


version: '2'


        image: ali/redis
            - "6379:6379"

        image: ali/webapi
            - ASPNETCORE_ENVIRONMENT=Staging
        image: haproxy:1.7.1
            - "./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg"
            - "9911:8080"


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

public string GetCacheData()
        var time = Encoding.UTF8.GetString(_memoryCache.Get("serverTime")); = 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.


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:

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