Tencent Cloud - ASP.NET Core + MySQL + Jexus + CDN Cloud Practice

2019年12月15日 104点热度 0人点赞 0条评论
内容目录

腾讯云-ASP.NET Core+Mysql+Jexus+CDN上云实践.md

Opening a Tencent Cloud Server and MySQL

Key Points:

  • Usage of ASP.NET Core and Entity Framework Core
  • Installation and configuration of MySQL database on Linux
  • Generating the database using entities
  • Basic Linux commands and Shell tools
  • Reverse proxy
  • Usage of Tencent Cloud CDN and configuration of server SSL certificates

I. Create a CVM Server

Introduction to Cloud Virtual Machine (CVM)

Cloud Virtual Machine (CVM) provides secure and reliable elastic computing services. You can acquire and activate CVM in the cloud in just a few minutes to meet your computing needs. As business needs change, you can scale computing resources up or down in real-time. CVM supports billing based on the actual resources used, allowing you to save on computing costs. Using CVM significantly reduces your software and hardware procurement costs while simplifying IT operations.

Introduction to Cloud Database MySQL

Tencent Cloud Database MySQL (TencentDB for MySQL) allows users to easily deploy and use MySQL databases in the cloud. MySQL is the world's most popular open-source relational database, and with Cloud Database MySQL, you can deploy scalable MySQL database instances in minutes. It is not only cost-effective but also allows for elastic adjustments of hardware capacity without downtime. Cloud Database MySQL provides a complete set of database operation solutions including backup rollback, monitoring, rapid scaling, and data transmission, simplifying your IT operations and allowing you to focus more on business development.

Before starting the tutorial, you need to create a Tencent Cloud CVM server and open all ports in the security group (or at least add port 3306 for development).

Please choose Ubuntu 18.04 or CentOS 7.5.

Ubuntu is more suitable for beginners; it is recommended to install Ubuntu on the server.

Shell Tool:

Free licensed XShell download address:

https://www.netsarang.com/zh/free-for-home-school/

Connecting to Linux:

Note that the default username for Ubuntu is ubuntu.

In the XShell interface, you can connect to Linux using the Shell command directly:

ssh ubuntu:7t@DfP3Ym3FwDoLM@129.204.104.20

The format is ssh [username]:[password]@[host IP].

After logging in, you will need to manually add a root user:

sudo passwd root

Then, enter the password twice as prompted.

You can switch users using the su command, for example su root.

II. Install MySQL on the Server

Since cloud databases can only be accessed on the intranet, if you need to access it from the public network, you need to purchase an Elastic Public IP. For learning purposes, here we will manually set up a MySQL database instead of using the cloud database.

1. Install, Configure, and Use MySQL Database

The following operations require root privileges; please switch to the root user first.

Install MySQL

apt install mysql-server

or

apt-get install mysql-server

The difference between apt-get and apt is that apt-get provides detailed output.

If you are using CentOS, use yum install mysql-server.

Allow Remote Login to MySQL

vim /etc/mysql/mysql.conf.d/mysqld.cnf

Find bind-address and press i to modify the content. Please change it to:

bind-address            = 0.0.0.0

0.0.0.0 means allowing any IP to log in to this server's MySQL.

After modification, press Esc, type :wq!, and press Enter to save and exit.

Restart MySQL

service mysql restart

Configure Remote Login Permissions

mysql -u root -p

This will log you into MySQL.

In the MySQL database, create a root user and set the password to 123456:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY "123456" WITH GRANT OPTION; 

Create the Database

create database testmvc;

Then Exit MySQL

exit;

Then restart again

service mysql restart

Manage MySQL

Navicat for MySQL is a commercial software used for managing MySQL databases.

Download link: https://navicatformysql.en.softonic.com.

There are many online tools for managing MySQL; please search for them on your own.

III. Create an ASP.NET Core Application for Testing

Please create an ASP.NET Core application in Visual Studio 2017/2019 and select MVC (Model-View-Controller).

1. Add NuGet Packages

Search and install the following NuGet packages in order:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Tools

MySql.Data.EntityFrameworkCore

MySql.Data.EntityFrameworkCore.Design

In the Models directory of the web application, create a class Users.cs, which is referred to as a model class, as it is used for generating database tables through EF Core and mapping data models; hence it is also called an entity class.

Code for the Users class:

This will generate a table for user information (you can freely add properties).

    public class Users
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public int YearsOld { get; set; }
        [Phone]
        public string PhoneNumber { get; set; }
        [EmailAddress]
        public string Email { get; set; }
    }

2. Create Database Access Context

In the Models directory, create a DatabaseContext.cs.

    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
        {

        }
        public DbSet<Users> Users { get; set; }
    }

The database context is used to access the database and for dependency injection.

3. Configure Services

In the Startup.cs file, find the ConfigureServices method and add

            services.AddDbContext<DatabaseContext>(options => options.UseMySQL("server=129.204.104.20;user id=root;password=123456;database=test;charset=utf8;sslMode=None"));

Please modify the above connection string to your own.

4. Add a Controller for Modifying Database Tables

Use the built-in code generator to generate pages and database operation code.

Right-click the Controllers folder in the project.

1565250372(1)

1565250455(1)

Configure Website Port

Since this is for testing, only HTTP access will be used.

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5001")
                .UseStartup<Startup>();

In the Startup.cs file, delete app.UseHttpsRedirection();.

Generate Entity Mapping

Entity Framework Core is an ORM framework that allows us to manipulate databases directly through code, without writing complex SQL statements.

Open the Package Manager Console.

Generate mapping:

Add-Migration Migrations

Generate database tables:

Update-Database

Then you will find that the database has an additional Users table.

Prepare for Migration to the Cloud Server for Running

Modify the database IP in services.AddDbContext to change it to 127.0.0.1. Once we migrate to the server, accessing the database will become local access, and there’s no need to enter a public IP.

Publish the web project, package the published content directly into a publish.zip.

IV. Set Up the Server Environment

1. Install .NET Core SDK

Download the full version of the .NET Core SDK

https://dotnet.microsoft.com/download

Directly download the Ubuntu version:

https://dotnet.microsoft.com/download/linux-package-manager/ubuntu18-04/sdk-current

Copy commands to the server as prompted on the page.

2. Install lrzsz

To facilitate file uploads, install lrzsz

apt install lrzsz

Then you can directly drag and upload files to Linux.

Here we store the website in a temporary directory.

mkdir /tmp/www
cd /tmp/www

Then upload the website compressed package to this directory.

Unzip the files

unzip publish.zip
cd publish

3. Install Jexus

Here we use Jexus as the web server to host applications and perform reverse proxying.

The reason for using Jexus is that it is lightweight and simple. Of course, you can also use Nginx, etc.

Installation:

curl https://jexus.org/release/x64/install.sh | sudo sh

Configure Jexus

We configure Jexus to make the website accessible from the outside world.

/usr/jexus/siteconf
touch testmvc
vim testmvc

Copy and paste the following content:

######################
# Web Site: Default 
########################################

port=80
root=/tmp/www/publish
hosts=129.204.104.20    #OR your.com,*.your.com
reproxy=/ http://127.0.0.1:5001
# User=www-data

# AspNet.Workers=2  # Set the number of asp.net worker processes. Default is 1.

# addr=0.0.0.0
# CheckQuery=false
NoLog=true

AppHost={cmd=dotnet /tmp/www/publish/WebApplication2.dll; root=/tmp/www/publish; port=5001}

80 is the port for the external access to the website,

129.204.104.20 is the public IP,

reproxy=/ http://127.0.0.1:5001 is the reverse proxy,

AppHost={cmd=dotnet /tmp/www/publish/WebApplication2.dll; root=/tmp/www/publish; port=5001} indicates the command to run, the root directory, and the website port.

Configuration notes:

Hosting ASP.NET Core through Jexus, using the web server to launch the application.

Configuring reverse proxy so that the public can access the ASP.NET Core application.

4. Restart Jexus and Start the Website

cd /usr/jexus/
./jws restart

5. Open the Website and Experience Database Operations

1

If you need to configure the reverse proxy with Nginx, please refer to another article by the author.

https://www.cnblogs.com/whuanle/p/10228893.html

V. Tencent Cloud CDN and Website SSL Configuration

Here we will not perform actual coding operations but demonstrate the general idea.

You can apply for a free SSL certificate for your website at https://console.cloud.tencent.com/ssl.

At https://console.cloud.tencent.com/cdn, configure acceleration for your website.

1565268177(1)

You must use CNAME to resolve your domain name to the Tencent Cloud CDN acceleration domain, allowing you to configure acceleration and caching functions.

1565268272(1)

SSL Website Configuration Concepts and Solutions

When configuring website SSL, there is an issue of forcing the redirect to HTTPS.

How to force a redirect to HTTPS when users access HTTP?

It is not feasible to configure this on the website or server; firstly, free configurations with substantial traffic can impact performance, and secondly, it may reduce access speed.

We can configure the Forced HTTPS feature in Tencent Cloud CDN.

This way, after domain resolution, it will directly force redirect to HTTPS without any modifications to the web server or website.

1565268546(1)

However, this also leads to issues.

Since using CDN acceleration and caching features requires CNAME, most domains may set the main domain for corporate email, making it impossible to use CNAME resolution but allowing for A records.

Therefore, if you have a domain like qq.com configured with an email system xxx@qq.com, you will not be able to use qq.com to configure CDN records.

General Solution:

qq.com is no longer used; it is set for email.

www.qq.com and other prefixes will be used as website domain access. Accessing www.qq.com will force redirect to HTTPS.

However, we cannot waste qq.com; we can redirect any client accessing qq.com to www.qq.com.

That is, qq.com will not be accessed as the website domain; accessing qq.com will redirect to www.qq.com.

Verification:

Enter qq.com in the browser and visit. You will find that it redirects to https://www.qq.com.

Now entering www.qq.com will redirect to https://www.qq.com.

Testing with commands:

root@VM-14-73-ubuntu:/tmp# curl qq.com
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.6.0</center>
</body>
</html>
root@VM-14-73-ubuntu:/tmp# curl www.qq.com
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

Explanation:

Accessing qq.com and www.qq.com will both trigger a 302 redirect.

Issue

There’s an issue:

Try accessing: https://qq.com.

You will find that it cannot be accessed. Don't believe it? Try it.

The domain qq.com cannot actually be accessed via HTTPS...

Of course, it is unclear how qq.com’s resolution is set up.

I’m just providing an example. Many websites that access xx.com also redirect to www.xx.com.

痴者工良

高级程序员劝退师

文章评论