Host your .NET Core project on Linux with Nginx
2021-08-03 LinuxHave you been looking for hosting alternatives for your .NET Projects? Why not host them yourself? .NET Core is built to run on Linux as well as on Windows. This guide will take you trough all necessary steps to get your project running on a Linux server.
Get yourself a good server
The first step is to get yourself a server. Here bellow you’ll find a list with good server options. This guide will work for most Debian based operating systems.
- Time4VPS
- Azure
- AWS
- Google Cloud
Install the latest version of .NET Core
If you wish to install other versions of .NET Core or simply need the instructions for another operative system then visit: https://dotnet.microsoft.com/download/dotnet-core
Before we can install .NET Core we have to make sure that the package-installer knows where to find them. Run the following commands:
sudo wget https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
Run these commands in the following order to install the runtime for .NET Core 5.0. If you wish to install another version then visit the link above for further instructions
sudo apt-get update
sudo apt-get install -y apt-transport-https
sudo apt-get update
sudo apt-get install -y aspnetcore-runtime-5.0
Install Nginx
Since .NET Core has it's own built in webbserver which is somewhat limited, we'll use Nginx as a reverse proxy.
sudo apt-get install nginx
sudo systemctl status nginx
sudo service nginx start
sudo service nginx stop
sudo service nginx restart
sudo vim /etc/nginx/sites-available/default
server {
listen 80;
server_name example.com;
root /websites/mywebsite;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Configure your service
sudo vim /etc/systemd/system/MY-SERVICE-NAME.service
[Unit]
Description=This is a sample application for my tutorial
[Service]
WorkingDirectory=/websites/mywebsite/ #CHANGE this to your application location
ExecStart=/usr/bin/dotnet /websites/mywebsite/MyWeb.dll #CHANGE this to your application location
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-myapp
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
sudo systemctl enable MY-SERVICE-NAME.service
sudo systemctl start MY-SERVICE-NAME.service
Install a SSL certificate with Letsencrypt
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get install python-certbot-nginx
sudo certbot --nginx -d example.com