Hosting .Net Core on Linux(Ubuntu) Amazon AWS Lightsail with MySQL - A Complete Guide

By: Team Appsious | Saturday, 07 December 2019
Hosting .Net Core on Linux(Ubuntu) Amazon AWS Lightsail with MySQL - A Complete Guide

As .Net Core is an open-source, cross-platform framework we don't need to rely on windows (IIS) hosting platform. Now we have the option to host it on Linux using either Nginx or Apache as a webserver. This post is a complete guide to hosting .net core web application on Amazon AWS Lightsail Linux (Ubuntu) instance with managed MYSQL as a backend database.

There are many popular cloud hosting platforms that provide Linux(Ubuntu) hosting from as cheap as $5. I'm going to use Amazon AWS Lightsail ubuntu with managed MYSQL as a backend for this guide.

.Net Core + Linux(Ubuntu) + Nginx + Amazon AWS Lightsail + MySQL


1) Create Linux(Ubuntu) Instance in Amazon AWS Lightsail

Create Linux(Ubuntu) Instance in Amazon AWS Lightsail
  • Signup/Login to Lightsail then click on Create Instance. 
  • You can set up a free trial instance for 30 days. or select an instance of your choice. Give a name to your instance. The screen also has an option to upload your own SSH key. I'm going to leave for default one which is generated by AWS.
  • Click on Create Instance. Your Lightsail ubuntu instance will be ready in a minute or two.
  • Create Static IP: Lightsail instance comes with free static/public IP address. Attaching the server with static IP helps in DNS configuration. Also, using that IP  adress the website can be directly accessed from anywhere.
    • Go to the Network tab and click on Create Static IP
    • Select the location same as Linux box
    • Attach the instance created above
    • Give a name to the static IP
    • Click Create

2) Create MySQL Managed Instance

Create MySQL Managed Instance
  • Navigate to the Database tab then click on Create Database
  • Select the AWS region same as one selected while creating the Ubuntu box.
  • Select the My SQL Version
  • Provide username and password for DB instance or leave it to the default username dbmaster and lightsail auto generates a strong password for you.
  • Give a name to MySqlL instance then click Create Database.

3) Setup .Net Core Project with MySql

As our AWS instance is ready, lets setup .net core project to use MySQL database

  • First, open MySql workbench in your local system.
    If you don't have MySql, download and install it from here
  • In MySql, workbench window click on create a new connection (+ icon), then give lightsail MySql database instance credentials
  • Once the connection is created, open your database instance and create a new schema (database)
  • Open .net core project either in Visual Studio or VS Code and install MySql NuGet package.
    From visual studio package manager console, run
    Install-Package MySql.Data.EntityFrameworkCore
    Install-Package MySql.Data.EntityFrameworkCore.Design
    If you are using vs code run below command from the .Net CLI
    dotnet add package MySql.Data.EntityFrameworkCore
    dotnet add package MySql.Data.EntityFrameworkCore.Design
  • Open appsettings.json file and enter the connection string
     "ConnectionStrings": {
    	"dbconnection": "server=<aws_server_name>;port=3306;database=<database>;User=<db_user>;Password=<my_sql_password>"
      }
  • Open Startup.cs, in the configure section, enter below code
     public void ConfigureServices(IServiceCollection services)
     { 
       services.AddDbContext<ApplicationDbContext>(options =>
               options.UseMySQL(Configuration.GetConnectionString("dbconnection")));
     } 
  • With the above setup in place, the project is now connected to MySQL. Let's run the migration commands to migrate user tables.
  • At the time of writing this article, there are some issues with the MySQL NuGet package. I've mentioned the issues at the end of this article, if necessary check it out
  • Run the migration command to update the database.
    (Note: I've not created a new migration as .net core default project template comes with migration files for user tables. Below command is only for updating the existing migration)
    Update-Database //from visual studio
    dotnet ef database update //from .net cli
  • Create a publishing profile with the following options and publish code to the local directory
    • Target Machine: Linux-x64
    • Deployment Mode: Self-Contained

Setup .net core project with MY SQL

4) Hosting .Net Core in Nginx

As we have published the code to the local folder in the previous section. Next step is to set up the Nginx and then transfer the code to Ubuntu Nginx hosting directory.

  • Login to the Lightsail website from browser and open Ubuntu terminal
  • Install .Net Core runtime using this link. Step to install for deferent Linux distros are also given the same link.
  • Install Nginx -
    sudo apt update
    sudo apt install nginx
  • Start webserver
    sudo service nginx start
  • Verify that Nginx running by browsing the public IP address created earlier from your local system.
    You should see the default Nginx screen saying "Welcome to Nginx" 
  • Create folder for project in Nginx directory /var/www/html/ directory
    -sudo mkdir /var/www/html/<project_name>
  • Give write permission to non-root user - Ubuntu
    This is needed to access your file using FTP clients
    cd /var/www/html/<project_name>
    sudo chown ubuntu <project_name>
  • Copy the published project file to Nginx folder using any FTP client like WinSCP
  • Nginx Configuration: Nginx works as a reverse proxy server with Kestrel.
    Edit the Nginx config file
  • sudo nano /etc/nginx/sites-available/default

  • Below is the config file example. 
    server
    {   
        listen 80 default_server; 
        return 444;   
    }
    server { 
        listen       80;
        #Once site starts working with IP, replace it with your domain name.
    server_name <Static_IP>; 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; } }
  • Verify the syntax of the configuration files.
  • sudo nginx -t

  • Our Nginx is ready, Configure Kestrel server to run as service.
    Create a service definition file using below command
    sudo nano /etc/systemd/system/<kestrel_project_name>.service
  • Put below code in the service definition file. Change project_name and assembly_name.
    [Unit] 
    
    Description=Example .NET Core Web App running on Ubuntu 
    
    [Service] 
    
    WorkingDirectory=/var/www/ 
    
    ExecStart=/usr/bin/dotnet /var/www/<project_name>/<app_assembly>.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 

  • Save the file and Enable the service
    sudo systemctl enable <kestrel_project_name>.service 
    
  • Restart the service
    sudo systemctl restart <kestrel_project_name>.service
With this configuration, the .net core website should be up and running. You should be able to access it using the Lightsail Public IP address. 

Next step is to -

  • Remove IP address from Nginx config file and replace with your domain name.
  • Configure DSN recording using the public IP
  • Generate and Add SSL certificate
Related Articles
Latest Articles
Best websites for Royalty Free CC0 Images (Free Commercial Use & Creative Commons Zero)

Best websites for Royalty Free CC0 Images (Free Commercial Use & Creative Commons Zero)

Websites with royalty-free creative commons zero (CC0) license Images for your blog, presentations or any commercial useThe pictures are free for personal and even for commercial use.You can modi...

What are the Best Cross-Platform Mobile Development Tools (Android + IOS)?

What are the Best Cross-Platform Mobile Development Tools (Android + IOS)?

Code once and run on any platform. This is the promise of cross-platform development tools. You can build your codebase once, and then run the app on any platform. The native apps are created specific...

Best websites to follow for AI & Machine Learning news

Best websites to follow for AI & Machine Learning news

If you are an AI enthusiast, looking for the latest Artificial Intelligence and machine learning news and blogs know what is happening around the world in the AI field, here is the list of Best Artifi...

Hosting .Net Core on Linux(Ubuntu) Amazon AWS Lightsail with MySQL - A Complete Guide

Hosting .Net Core on Linux(Ubuntu) Amazon AWS Lightsail with MySQL - A Complete Guide

As .Net Core is an open-source, cross-platform framework we don't need to rely on windows (IIS) hosting platform. Now we have the option to host it on Linux using either Nginx or Apache as a webserver...

Selenium + Chrome WebDriver With .Net Core on Ubuntu

Selenium + Chrome WebDriver With .Net Core on Ubuntu

Selenium is the most used web application testing framework. It is also a widely used framework for web data scrapping. Selenium has support for all the major web browsers. This article explains how t...

Best Free Icon Font library for Commercial Use

Best Free Icon Font library for Commercial Use

Icon Fonts has become a goto standard for modern web design. They are easy to use and manage. Instead of keeping many png icons, these icons fonts can be rendered using one single CSS file. Advan...

Best Image Recognition APIs

Best Image Recognition APIs

The term image recognition refers to computer technology which uses machine learning and deep learning technics to identify people, animals, and other objects. There are many companies that ...

Collection of Best Free Image API (CC0 Royalty Free Stock Images API)

Collection of Best Free Image API (CC0 Royalty Free Stock Images API)

First, take look at how some of the world's best websites and applications use free stock image API in their platform. Medium one of the largest blogging platform allows image search using Unspla...

Blog Post Title Generators

Blog Post Title Generators

Fresh content is a king when it comes to search engine and SEO, A good looking title with a relevant keyword is a must. If you need in creating a title for your blog post, here is the list of Blog Pos...

Best Dictionary APIs (freemium - Free + Paid)

Best Dictionary APIs (freemium - Free + Paid)

Are you a developer building an AI BOT or a game? Do you want dictionary data for learning and academic research purpose? Dictionary APIs allows the developer to build deferent types of applications. ...

Best Password Managers 2019 - Generate and Securely Store All Your Passwords

Best Password Managers 2019 - Generate and Securely Store All Your Passwords

We do sign up for many web sites and it is very difficult to remember the usernames and passwords of all of them unless you decide to keep is the same. Keeping the same usernames and passwords for mul...

Best windows shared hosting provider

Best windows shared hosting provider

If you need a web server powered by Microsoft windows server and SQL database obvious choice is to go for windows web hosting. But if you have doubt like which one to choose, that depends on factors l...