You are on page 1of 7

Tutorial: Hosting ASP.

NET Core on Linux


Updated March 9, 2023, by Nathaniel Stickman
ASP.NET Core is Microsoft’s cross-platform and open-source redesign of its original ASP.NET framework.
With ASP.NET Core, you can build and run .NET applications not only on Windows but also macOS and
Linux.

This guide shows you how to install ASP.NET Core on your Linux server and how to use it to create a web
application. Then, it walks you through the steps for deploying your application using NGINX.

Before You Begin


1. If you have not already done so, create a Linode account and Compute Instance. See our Getting
Started with Linode and Creating a Compute Instance guides.
2. Follow our Setting Up and Securing a Compute Instance guide to update your system. You may
also wish to set the timezone, configure your hostname, create a limited user account, and
harden SSH access.
3. This guide uses example-app as the name of the ASP.NET Core application and example.com as
your server’s domain name. Replace these with your preferred application name and actual
server name, respectively.
Note
The steps in this guide are written for a non-root user. Commands that require elevated privileges are
prefixed with sudo. If you are not familiar with the sudo command, see the Linux Users and Groups guide.

Install ASP.NET Core


These installation steps work for Debian 10 and Ubuntu 20.04. If you are using another Linux
distribution, refer to the Microsoft’s Install .NET on Linux guide.

1. Add Microsoft’s package keys and its package repository.

 On Debian:

 wget https://packages.microsoft.com/config/debian/10/packages-microsoft-
prod.deb -O packages-microsoft-prod.deb
 sudo dpkg -i packages-microsoft-prod.deb

 On Ubuntu:

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

2. Update the package indices.

3. sudo apt update

4. Install the APT package allowing you to use repositories over HTTPS and update APT’s indices
again.
5. sudo apt install apt-transport-https
6. sudo apt update

7. Install the .NET Core SDK.

8. sudo apt install dotnet-sdk-5.0

Replace 5.0 with the latest version of the .NET Core SDK available, which you can find by running
the following command:

sudo apt search dotnet-sdk

Alternatively, you can install .NET SDK using snap.

sudo snap install dotnet-sdk

9. Verify the .NET Core version installed

10. dotnet --version

Create a Web Application with .NET Core


1. Initialize a base .NET web application project.

2. dotnet new webapp -o example-app

3. Change into the application’s directory.

4. cd example-app

Unless noted otherwise, all subsequent commands in this guide assume you are still in the
application’s directory.
5. Run the application.

6. dotnet watch run

.NET Core serves the application on localhost port 5001. To visit the application remotely, you
can use an SSH tunnel:
 On Windows, you can use the PuTTY tool to set up your SSH tunnel. Follow the
appropriate section of the Using SSH on Windows guide, replacing the example port
number there with 5001.
 On OS X or Linux, use the following command to set up the SSH tunnel. Replace example-
user with your username on the application server and 192.0.2.0 with the server’s IP
address.

 ssh -L5001:localhost:5001 example-user@192.0.2.0

7. Now you can visit the application in your browser by navigating to https://localhost:5001.
Note
.NET Core serves your application over HTTPS. When visiting the application, you browser may
warn you that the SSL certificate is self-signed. Choose to proceed anyway.

.NET Core uses Razor as its template engine for web application interfaces. You can learn more about
using Razor in your web application from Microsoft’s Get started with Razor Pages in ASP.NET
Core guide. .NET Core also has extensive support for developing applications using the Model–View–
Controller (MVC) architecture. If you want to learn more about MVC, checkout the Microsoft’s Get started
with ASP.NET Core MVC guide.

Deploy Your Application with NGINX


.NET Core’s default server, Kestrel, works well for serving dynamic web applications. However, Microsoft
recommends pairing it with a reverse proxy server when deploying your application to production. Doing
so allows you to offload tasks like request handling and serving static content.

The steps in this section show you how to set up NGINX as the reverse proxy server for your .NET Core
application.

Install and Configure NGINX


1. Install NGINX:

2. sudo apt install nginx

3. Create a /etc/nginx/proxy.conf file, and add the contents of the example file:
File: /etc/nginx/proxy.conf

1 proxy_redirect off;
2 proxy_set_header Host $host;
3 proxy_set_header X-Real-IP $remote_addr;
4 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
5 proxy_set_header X-Forwarded-Proto $scheme;
6 client_max_body_size 10m;
7 client_body_buffer_size 128k;
8 proxy_connect_timeout 90;
9 proxy_send_timeout 90;
10 proxy_read_timeout 90;
11 proxy_buffers 32 4k;
12

4. Open the NGINX configuration file — /etc/nginx/nginx.conf — and replace its contents with the
following:
File: /etc/nginx/nginx.conf

1 user www-data;
2 worker_processes auto;
3 pid /run/nginx.pid;
4 include /etc/nginx/modules-enabled/*.conf;
5
6 events {
7 worker_connections 768;
8 # multi_accept on;
9 }
10
11 http {
12 include /etc/nginx/proxy.conf;
13 limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
14 server_tokens off;
15
16 sendfile on;
17 keepalive_timeout 29;
18 client_body_timeout 10; client_header_timeout 10; send_timeout 10;
19
20 upstream example-app{
21 server localhost:5000;
22 }
23
24 server {
25 listen 443 ssl http2;
26 listen [::]:443 ssl http2;
27 server_name example.com;
28
29 add_header X-Frame-Options DENY;
30 add_header X-Content-Type-Options nosniff;
31
32 location / {
33 proxy_pass http://example-app;
34 limit_req zone=one burst=10 nodelay;
35 }
36 }
37 }
38

5. Open access to the HTTPS port ( 443) on your server’s firewall.

6. sudo ufw allow https


7. sudo ufw reload

Get an SSL Certificate


The steps below show you how to use Certbot to request and download a free certificate from Let’s
Encrypt and how to add that certificate to your NGINX server.

1. Install the Snap Store. Snap provides application bundles that work across major Linux
distributions. If you are using Ubuntu, Snap should already be installed (since version 16.04):

2. sudo apt install snapd

3. Update and refresh Snap.

4. sudo snap install core && sudo snap refresh core

5. Ensure that any existing Certbot installation is removed.

6. sudo apt remove certbot

7. Install Certbot, and create a symbolic link for executing it.

8. sudo snap install --classic certbot


9. sudo ln -s /snap/bin/certbot /usr/bin/certbot

10. Download a certificate for your site.

11. sudo certbot certonly --nginx

Certbot prompts you to select from the NGINX sites configured on your machine. Select the one
with your domain name.
12. Certbot includes a cron job that automatically renews your certificate before it expires. You can
test the automatic renewal with the following command:

13. sudo certbot renew --dry-run

Add the SSL Certificate to NGINX


1. Add the SSL certificate and its key to your NGINX configuration, via
the ssl_certificate and ssl_certificate_key properties as shown below:
File: /etc/nginx/nginx.conf

1 # [...]
2
3 server {
4 listen 443 ssl http2;
5 listen [::]:443 ssl http2;
6 server_name example.com *.example.com;
7 ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
8 ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
9
10 add_header X-Frame-Options DENY;
11 add_header X-Content-Type-Options nosniff;
12
13 # [...]
14

2. Verify the NGINX configuration. Then, assuming the test passes, restart NGINX.

3. sudo nginx -t
4. sudo systemctl restart nginx

5. You can test NGINX’s routing to the application by running the application directly.

6. dotnet watch run

Prepare the Application


The steps below ensure that your .NET Core application works properly with the NGINX reverse proxy.
These steps also have you make a “published” executable of your application, which makes it easier to
use in production scenarios.
1. Open the Startup.cs file, and add the Forwarded Headers middleware. Ensure that
the app.UseForwarededHeaders method is invoked before any other middleware.
File: ~/example-app/Startup.cs

1 // [...]
2
3 using Microsoft.AspNetCore.HttpOverrides;
4
5 // [...]
6
7 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
8 {
9 app.UseForwardedHeaders(new ForwardedHeadersOptions
10 {
11 ForwardedHeaders = ForwardedHeaders.XForwardedFor |
12 ForwardedHeaders.XForwardedProto
13 });
14
15 app.UseAuthentication();
16
17 // [...]
18 }
19
20 // [...]

2. Publish your application.

3. dotnet publish --configuration Release

The output should indicate the location of an example-app.dll file. Take note of that location, as
it is used in the example-app.service file created below. It should be similar
to /bin/Release/net5.0/example-app.dll.
4. Copy your project to the /var/www directory. This is a conventional place to store your production
application, but it also allows you to separate your production and working versions of the
application.

5. sudo cp -r ~/example-dotnet-app /var/www/example-dotnet-app

6. Create a service file for systemd to run the application.


File: /etc/systemd/system/example-app.service

1 [Unit]
2 Description=Example .NET Core Web Application
3
4 [Service]
5 WorkingDirectory=/var/www/example-app
6 ExecStart=/usr/bin/dotnet /var/www/example-app/bin/Release/net5.0/example-app.dll
7 Restart=always
8 RestartSec=10
9 KillSignal=SIGINT
10 SyslogIdentifier=dotnet-example-app
11 User=www-data
12 Environment=ASPNETCORE_ENVIRONMENT=Production
13 Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
14
15 [Install]
16 WantedBy=multi-user.target
17
Run the Application
1. Enable the systemd service for the published application, and then start it up.

2. sudo systemctl enable example-app


3. sudo systemctl start example-app

4. Verify that the application is running by visiting its URL, http://example.com.

Conclusion
You have now successfully created and deployed a .NET Core application. You can continue your journey
and learn more about using .NET for web-application development by following
Microsoft’s Recommended learning path.

You might also like