Load Balancing an ASP.NET Core Web App using Nginx and Docker

Host an ASP.NET Core Web API app with Nginx and Docker: Load Balancing

Changhui Xu
codeburst
Published in
6 min readJun 27, 2020

--

Following the two articles (Configure ASP.NET Core to work with proxy servers and load balancers and Host ASP.NET Core on Linux with Nginx) in Microsoft Docs, I created a demo application using Docker Compose, which orchestrates an Nginx reverse proxy server and an ASP.NET Core Web API app. The following screen recording shows the demo app.

In the demo, the web API app is replicated to four instances ( -- scale api=4), and Nginx is served as a reverse proxy for the four api services. When the client visits the https://localhost site, the four api services handle the HTTP requests in a round-robin manner, as can be seen from the console logs and the Host Name in the web page.

The complete solution is located in my GitHub repository. In this article, we will go over some implementation details.

Create an ASP.NET Core Web API Project

We first create an ASP.NET Core Web API project MyWebApi from the dotnet template. Since we will use Nginx for SSL termination (more in next section), we don’t need to enable HTTPS support in our ASP.NET Core project.

The MyWebApi app will be hosted by Kestrel which is sitting behind Nginx. HTTPS requests are proxied over HTTP, so the original scheme (HTTPS) and originating client IP address are lost. To remediate that, we can forward the original scheme and client IP using forwarded headers by enabling the Forwarded Headers Middleware. Note that the Forwarded Headers Middleware should run before other middlewares. The following code snippet shows an example implementation.

In the code above, lines 4 to 7 configure the Forwarded Headers options. In the options, we can also…

--

--

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.