How to Host ASP.NET Core App on Ubuntu with Apache Webserver

In this article, we are going to learn how to host ASP.NET Core on Linux Azure Ubuntu VM with Apache Web server in simple steps.

The version of the Linux operating system: – Ubuntu 18.04
Web Server: – Apache
ASP.NET Core Version: – 3.1
Hosting: – on Azure Linux VM with Ubuntu Operating System

Table of Contents

  • Getting Started with Hosting ASP.NET Core on Linux
  • Project structure
  • Configure a reverse proxy server in the application
  • Configure Method in Startup Class
  • Supported distributions
  • Creating Azure VM
  • Connecting to Linux VM Using PuTTY
  • Step 1 Register the Microsoft Product key as trusted
  • Step 2 Install .Net Core runtime
  • Step 3 Publishing Application
  • Step 4 Copying Application to Linux VM
  • Step 5 Install Apache
  • Step 6 Check Apache Server Status
  • Step 7 Enable the required apache modules
  • Step 8 Restart Apache
  • Step 9 Creating Folder in www folder and copy all application files
  • Step 10 Create a Virtual Host Configuration File
  • Step 11 Add below content to Webnixfile.conf file
  • Step 12 Disable the default site defined in 000-default.conf
  • Step 13 Activate the Webnixfile.conf
  • Step 14 Check Syntax of the Default Configuration file
  • Step 15 Restart Apache2 to make to take new changes
  • Step 16 Creating service
  • Step 17 Enable the service
  • Step 18 Start the service
  • Step 19 Output

Getting Started with Hosting ASP.NET Core on Linux

Getting Started with Hosting ASP.NET Core on Linux

We are going to create a new application with Name Webnix for demo as shown below.

Next, we are going to set Project Name Webnix and location. In last part, we are going to choose .Net Core framework and ASP.NET Core Version 3.1 as the framework for application and few advance settings for such as configuring https and enabling docker we are not going to enable docker settings for this project.

Now finally click on create button to create a project.

Project structure
The project structure generated according to the configuration.

Configure a reverse proxy server in the application
After creating project next, we are going to make changes in Configure method in Startup class we are going to add UseForwardedHeaders middleware.

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
      ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

Configure Method in Startup Class

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Supported distributions
Distributions which are supported for hosting .Net Core 3.1. https://docs.microsoft.com/en-us/dotnet/core/install/linux-ubuntu

Creating Azure VM

In this part, we are going to create Linux Virtual Machine on Azure with Image of Ubuntu Server 18.04 LTS.
You can choose your subscription which you have next in Resource group if you have existing resource group then you can select that or create a new resource for this demo, I have made new resources group Ubuntu-Host-VM-Apache-RG

Then in Instance details, we are going to name Virtual machine as VMLinuxUbuntu-Apache You can choose the name of VM as you want. Next, to select a region to depend upon your choice, I am going to choose (US) East US. Operation System for VM (image) we are going to choose Ubuntu Server 18.04 LTS – Gen1 which is supported for hosting .Net Core 3.1.

Next to choosing Size of Virtual Machine according to you need for the demo we don’t require a large machine that why I have chosen Standard_B2s instance which has 2 vCPU(s) and 4GB RAM.


In authentication type we are going to choose is Password for using it we need to provide Username, Password and Confirm Password.
Inbound port rules section Public inbound ports we are going to choose Allow selected ports and in Select inbound ports we are going to select port 80 (HTTP), port 22 (SSH) and port 443 (HTTPS).

With this configuration just click on Review + Create button to create you VM will take some time for deployment.

Connecting to Linux VM Using PuTTY

For connecting to Linux Virtual Machine, we are going to use the PuTTY URL for downloading putty https://www.putty.org/.

To get Public IP address to connect to you VM just click on Home Menu from sidebar then you can Recent resources from that choose recently Create Virtual Machine you will see a similar screen as shown below.

Let’s start PuTTY for connecting to Virtual Machine.

Enter your public IP address in Host Name and Port will be 22 as shown in the above screenshot and click on Open button to connect.

Enter your username and password which you have set while creating Virtual Machine.

After connecting terminal, we are going to run some installation in it.

Step 1 Register the Microsoft Product key as trusted

We are going to run this command in terminal.

wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb

Step 2 Install .Net Core runtime

In this step we are going to install .NET Core Runtime allows you to run apps that were made with .NET Core.

sudo apt-get update; \
sudo apt-get install -y apt-transport-https && \
sudo apt-get update && \
sudo apt-get install -y aspnetcore-runtime-3.1 

Step 3 Publishing Application

In this step, we are going to publish an application to the folder and copy that folder to VM.

For publishing application just right click on the web application (Webnix) and select publish from Menu. We are going publish the application to the local folder we are going to choose Folder option.

Published files

After publishing, we need to copy files to Linux Virtual Machine for doing that we are going to use WinSCP tool.

Step 4 Copying Application to Linux VM

In this step, we are going to copy that folder to Linux Virtual Machine for doing that we are going to use WinSCP.

URL to Download WinSCP: –  https://winscp.net/eng/index.php

Step 5 Install Apache

In this step, we are going to install Apache web server.

sudo apt install apache2

Next, we have installed Apache now we can check Apache web server status is it running.

Step 6 Check Apache Server Status

sudo systemctl status apache2

To test in the browser, just access from Public IP. It will show you default Ubuntu 18.04 Apache web page as shown below.

Step 7 Enable the required apache modules

Here we are going to run following command to enable proxy and SSL Modules of Apache server.

  • sudo a2enmod rewrite
  • sudo a2enmod proxy
  • sudo a2enmod proxy_http
  • sudo a2enmod headers
  • sudo a2enmod ssl

Run each command one by one in similar ways, as shown above.
After Enabling modules, Apache server needs to restart.

Step 8 Restart Apache

Here we are going to restart Apache server after Enabling Modules in the last step.

sudo service apache2 restart

Step 9 Creating Folder in the www folder and copy all application files

In step 3 we have copied files to /home/azureuser/publish/ folder now we are going copy those files to /var/www/publishapplication/ folder. Before copying, we are going to create a folder.

sudo mkdir -p /var/www/publishapplication/publish/

mkdir -p command
With the help of mkdir -p command, you can create subdirectories of a directory. It will create a parent directory first if it doesn’t exist.
But if it already exists, then it will not print an error message and will move further to create sub-directories.
https://www.javatpoint.com/linux-mkdir-p

Copy files to newly created folder /var/www/publishapplication/Publish folder.

sudo cp -r /home/azureuser/publish/ /var/www/publishapplication/

cp -r command

Option ‘r’ with the copy command can be used to copy a directory including all its content from a source directory to the destination directory. https://www.javatpoint.com/linux-cp-r

View after copying files to a new folder.

Step 10 Create a Virtual Host Configuration File

Apache Virtual Host configuration are located in /etc/apache2/sites-available

I am going to name Virtual Host Configuration file as webnixfile.conf many people give the domain name to the Configuration file for easy to recognize.

sudo nano /etc/apache2/sites-available/webnixfile.conf

Step 11 Add below content to Webnixfile.conf file

<VirtualHost *:80>  
   ServerName www.example.com  
   ProxyPreserveHost On  
   ProxyPass / http://localhost:5000/ 
   ProxyPassReverse / http://localhost:5000/  
   RewriteEngine on  
   RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]  
   RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]  
   RewriteRule /(.*) ws://127.0.0.1:5000/$1 [P]  
   ErrorLog ${APACHE_LOG_DIR}/error-webnix.com.log  
   CustomLog ${APACHE_LOG_DIR}/access-webnix.com.log combined  
</VirtualHost>

After adding this content just save the file.

Step 12 Disable the default site defined in 000-default.conf

sudo a2dissite 000-default.conf

After disabling site next defined in 000-default.conf file next, we are going activate current configured virtual host configuration file.

Step 13 Activate the Webnixfile.conf

Here we are going to enable webnixfile.conf file.

sudo a2ensite webnixfile.conf

Step 14 Check Syntax of the Default Configuration file

sudo apachectl configtest

If the message of the terminal is Syntax OK then your configuration file is proper.

Step 15 Restart Apache2 to make to take new changes

sudo systemctl restart apache2

Step 16 Creating service

Creating a systemd Service file with name webnixservicefile.service

sudo nano /etc/systemd/system/webnixservicefile.service

Paste the following contents into the service file.

WorkingDirectory= defines on which directory the service will be launched.

This my application publish folder /var/www/publishapplication/publish

ExecStart= allows you to specify any command that you’d like to run when this service is started.

/usr/bin/dotnet /var/www/publishapplication/publish/Webnix.dll

[Unit]
Description=Running ASP.NET Core on Ubuntu 18.04 Webserver APACHE

[Service]
WorkingDirectory=/var/www/publishapplication/publish
ExecStart=/usr/bin/dotnet /var/www/publishapplication/publish/Webnix.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target

Step 17 Enable the service

sudo systemctl enable webnixservicefile.service

Step 18 Start the service

sudo systemctl start webnixservicefile.service

Step 19 Output

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.