Achraf Ben Alaya
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
SUBSCRIBE
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
No Result
View All Result
Achraf Ben Alaya
No Result
View All Result
ADVERTISEMENT
Home Blog Cloud Azure

How to setup nginx reverse proxy for aspnet core apps with and without Docker compose

Part 1

achraf by achraf
November 23, 2022
in Azure, c#, Cloud, docker
5 min read
6
How to setup nginx reverse proxy for aspnet core apps with and without  Docker compose
0
SHARES
1.9k
VIEWS
Share on FacebookShare on Twitter

Introduction

First of all and before we go straight to deployment and demo let’s understand what is a reverse proxy .

A reverse proxy intercepts all incoming requests and direct them to the appropriate server ,it can play the role of Load Balancer ” a Traffic Cop ” that will distribute the clients requests across group of servers in order to maximizes speed and capacity and making sure that no server is overloaded (in case a server is down the load balancer will redirect the traffic to the other servers ) ,more than that a reverse proxy will protect the identity of the other servers and act as a defense againsts security attacks .In this sense the reverse proxy will make sure that multiple servers can be accessed only from a single URL .

Prerequisites

  • Visual studio or visual studio code
  • A command mine /Terminal
  • Docker installed on your system

Part 1- Without Docker Compose

in this first part we will create our dotnet application that we will use now and later too , also nginx .
and we will go straight to our Index.cshtml  , and edit it to be like this :

@page
@model IndexModel

@{
    ViewData["Title"] = "Home page";
    var hostname = ViewData["host"];
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <p>
        <strong>Hostname :</strong> <h3> <code>@hostname</code></h3>
    </p>
</div>

Also we will edit the Index.cshtml.cs 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Net;

namespace hostnameapp.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        [BindProperty]
        public string? hostname { get; set; }
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            String hostName = Dns.GetHostName();
            Console.WriteLine(hostName);
            ViewData["host"] = hostName;
            

        }
    }
}

now if we run the application using IIS express we will have this view  :
As you can see the goal here is to show the hostname , nothing special .

now we will dockeriz application by creating a dockerfile  with this content (full source code of the solution will be shared )

FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS base

WORKDIR /app
ENV ASPNETCORE_URLS http://+:5000
# EXPOSE 80
EXPOSE 5000

FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build
WORKDIR /src
COPY ["hostnameapp/hostnameapp.csproj", "hostnameapp/"]
RUN dotnet restore "hostnameapp/hostnameapp.csproj"
COPY . .
WORKDIR "/src/hostnameapp"
RUN dotnet build "hostnameapp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "hostnameapp.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "hostnameapp.dll"]

now we will create the nginx application but we have some config for the app :
we will create  a file : nginx.conf

worker_processes 4;
 
events { worker_connections 1024; }
 
http {
    sendfile on;
    limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
    # upstream app_servers {
    #     #server app:127.0.0.1:5000;
    #   # server  http://backend:5000;
    # }
 
    server {
        listen 80;
 
        location / {
            proxy_pass          http://backend:5000;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}

Also we are going to docke the nginx proxy app

FROM nginx:alpine
RUN rm -r  /etc/nginx/nginx.conf
COPY nginx.conf /etc/nginx/nginx.conf

now we can build both apps and run them to see what will happen .

let’s start with our dotnet application we need to build and run our solution :

docker build -t backend  .
docker run -it --rm -p 5000:5000   --name backend backend

Now if you go to your browser and visit :  http://localhost:5000/ you will have this result :

And now as you can see our hostname have the id of the container .

now it’s time to run the nginx proxy that will be the entry to our application or let’s say the way we will expose our application .

docker build -t frontend  .
docker run -it --rm -p 8082:80   --name frontend frontend

if we run those commandes the project will build but will not run and we will finish by having an error saying that host not found , the host is the backend that we defined in the config file with port 5000 , and that’s because the two containers are not in the same network !
now let’s make some changes :
Let’s create a network :

docker network create demonetwork-001;
#to inspect that network 
docker network inspect demonetwork-001;

now we need to attach our containers to the network that we have created  :

docker network connect demonetwork-001 backend;
#this will fail because the container did exit beceause of error
docker network connect demonetwork-001 frontend;

--------------instead we will use this -------------------------
docker run -it --rm -p 5000:5000 --network=demonetwork-001  --name backend backend
docker run -it --rm -p 8082:80  --network=demonetwork-001  --name frontend frontend

and like that we will have our result  while visiting our entry point on port 8082 :

Part 2- With Docker Compose

now all we need is to create a docker compose file without editing our solutions : docker-compose.yml

version: "3.9"
services:
  app:
    build: ./hostnameapp
    expose: 
      - "5000"    
  proxy:
    #image: nginx:alpine
    build: ./nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    depends_on:
      - app
    links:
      - app  
    ports:
      - "8082:80"

now in our file we define the two apps and we say that the proxy app depends on the first app let see the result :
and this is our goal , we want the backend not to be exposed to public and we want our frontend exposed as you can see on port 8082 and we can not acces the backend , now if we modify the config file and add different backends with different port the load balancer will play it’s role to manage the traffic between the apps .

Now if we have the same app on different port and we edit the config file like this ofr example :

worker_processes 4;
 
events { worker_connections 1024; }
 
http {
    sendfile on;
 
    upstream app_servers {
        server app:5000 weight=4;
        server app2:5010 weight=2;
    }
 
    server {
        listen 80;
 
        location / {
            proxy_pass         http://app_servers;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}

the result will show that we balance between the two apps

that’s it for this demo , in next post we will discuss how we will do this on Azure Kubernetes Service (AKS) .

 

source code : https://bit.ly/3EDJVus

ShareTweet
Previous Post

Win free certifications at the Microsoft Build Cloud Skills Challenge | May 2022 🎁

Next Post

How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

Related Posts

AI

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025
106
Azure

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
227
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet
Azure

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025
135
Understanding Generative AI and RAG Benefits
AI

Understanding Generative AI and RAG Benefits

January 12, 2025
96
Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring
Azure

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

December 8, 2024
1.5k
PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis
Azure

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

November 2, 2024
500
Next Post
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

Comments 6

  1. Pingback: How to configure an ingress controller using TLS/SSL for the Azure Kubernetes Service (AKS) – achraf ben alaya
  2. Pingback: Switch from Docker Hub to Azure Container Registry – achraf ben alaya
  3. Pingback: From Docker Hub, switch to Azure Container Registry & AKS – achraf ben alaya
  4. Pingback: Part 5-A : Using Azure DevOps, Automate Your CI/CD Pipeline and Your Deployments – achraf ben alaya
  5. Pingback: Part 5-B : Using Azure DevOps, Automate Your CI/CD Pipeline and Your Deployments – achraf ben alaya
  6. Pingback: Part 5-C : Using Azure DevOps, Automate Your CI/CD Pipeline and Your Deployments – achraf ben alaya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Terraform

Certifications

Microsoft certified trainer (MCT)

Recommended

Goodbye my lover Xamarin, Hello MAUI!

Goodbye my lover Xamarin, Hello MAUI!

September 25, 2020
588
Streamlining Website Editing on My Local Machine with Docker Compose and WordPress

Streamlining Website Editing on My Local Machine with Docker Compose and WordPress

July 1, 2023
142
Migrate and modernize your applications on Azure

Migrate and modernize your applications on Azure – Part 2.0 (Azure Functions)

April 3, 2021
543
Learn… and get rewarded

Learn… and get rewarded

September 28, 2020
537
Sql tips and tricks

Sql tips and tricks

April 26, 2020
218
Reflecting on My Journey as a Microsoft MVP in 2024

Reflecting on My Journey as a Microsoft MVP in 2024

March 24, 2024
356
Facebook Twitter LinkedIn Youtube

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025

Categories

  • AI (2)
  • Apps (1)
  • Azure (63)
  • blazor (2)
  • Blog (91)
  • c# (7)
  • Cloud (65)
  • Courses (3)
  • Dapr (4)
  • docker (4)
  • Games (1)
  • General Tips & Fix (1)
  • Home (1)
  • Kubernetes Service (AKS) (1)
  • motivation (2)
  • Motivation (3)
  • News (9)
  • Resume (1)
  • sql (4)
  • Terrafrom (1)
  • Tricks, Tips and Fixes (4)
  • xamarin (5)
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy

ADVERTISEMENT