In this article, I will show how to create a web farm on docker with using redis and haproxy, step by step. In this sample, there will be a web api project as a web server apps (.net core framework) and a load balancer (haproxy). I will reproduce the web api to test load balancer. These web api projects will use the same cache server(redis) to sharing data. Finally, I will simulate this web farm on docker.

I won’t go into the details of how to install/configure docker on windows. There are documents about this in here. And there is a Getting Started document as well.

Creating Web API Project

First I create basic web api project from template.

6.jpg

7.jpg

And I change the valuescontroller to set/get/remove memory cache keys.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
 
namespace WebFarmExample.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly IDistributedCache _memoryCache;
 
        public ValuesController(IDistributedCache memoryCache)
        {
            _memoryCache = memoryCache;
        }
 
        [HttpGet("SetCacheData")]
        public IActionResult SetCacheData()
        {
            try
            {
                var time = DateTime.Now.ToLocalTime().ToString(CultureInfo.InvariantCulture);
                var cacheOptions = new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.Now.AddYears(1)
                };
                _memoryCache.Set("serverTime", Encoding.UTF8.GetBytes(time), cacheOptions);