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

By: Team Appsious | Saturday, September 28, 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 which 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.

Lists start:

.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 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...

Best Premium Stock Photography Websites to Buy/Sell Images in 2019

Best Premium Stock Photography Websites to Buy/Sell Images in 2019

These premium stock photography websites are useful for photographers to earn an extra bit of income. If you are a creative photographer, you might already have a collection of unused images stored in...

Best Pinterest Masonry style Premium Themes for Amazon affiliate WordPress site - 2019

Best Pinterest Masonry style Premium Themes for Amazon affiliate WordPress site - 2019

If you are creating an Amazon affiliate WordPress site new site in 2019, Here is a list of best Pinterest Masonry style premium themes. There are thousands of WordPress premium themes available in the...

Free Creative Commons Zero (CC0) license Images websites for commercial use in 2019

Free Creative Commons Zero (CC0) license Images websites for commercial use in 2019

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...

Top Coupons and Deals Websites in UK - 2019

Top Coupons and Deals Websites in UK - 2019

From gadgets to groceries, these websites make it easy to find the promos, coupons, deals, and discounts around you. There are many sites which provide deals and discounts coupons, here are the top si...

Top Coupons and Deals Websites in USA - 2019

Top Coupons and Deals Websites in USA - 2019

From gadgets to groceries, these websites make it easy to find the promos, coupons, deals, and discounts around you. There are many sites which provide deals and discounts coupons, here are the top si...

Best Online learning platform with video courses to upgrade your skill in 2019

Best Online learning platform with video courses to upgrade your skill in 2019

Today in the era of rapidly growing technology and ever-growing competition, it is becoming a mandate to upgrade your existing skills and also learn new and latest topics. People becoming expert in mu...

What is the cheapest and best Asp.Net MVC Hosting Providers

What is the cheapest and best Asp.Net MVC Hosting Providers

Team is working on Microsoft technology stack? and looking for cheapest and best Asp.Net MVC Hosting Providers. This is a list of cheapest and best Asp.Net MVC Hosting Providers....

Best Google Chrome New Tab App/Extension

Best Google Chrome New Tab App/Extension

Although the latest version of the chrome has given the support for editable speed dial, where the user can customize and keep their own list of website.  Still, there are many nice apps/extensio...

Best Hashtag Generator for Instagram, Twitter, Pinterest, and Other Social Media

Best Hashtag Generator for Instagram, Twitter, Pinterest, and Other Social Media

Whether it is on Instagram or Twitter or Pinterest or any other social platform it is proven that post with hashtag reaches more audience. There is no doubt that the correct usage of a hasht...

Best Free Python Online Code Editor (Cloud IDE / Compiler) - 2019

Best Free Python Online Code Editor (Cloud IDE / Compiler) - 2019

What is the best Free Online Code Editor or Compiler for Python? Online code editor will come handy if you want to test your python code quickly without installing IDE in your machine, ...

Best Process Mining Software

Best Process Mining Software

The process mining software helps to identify the inefficiency in the process and to improve gaps. Process mining software analyzes application event logs to identify the bottleneck in the p...