Use Nginx to host. Net Core applications in the Centos7 environment.

Source: Internet
Author: User
Tags openssl x509

Use Nginx to host. Net Core applications in the Centos7 environment.

1. Install. Net Core

Reference official documents: https://www.microsoft.com/net/core#linuxcentos

1. Add dotnet product Feed

Before installing. NET Core, you must register a Microsoft Product Feed. You only need to do this once. First, register the Microsoft signature key, and then add the Microsoft Product Feed

sudo rpm --import https://packages.microsoft.com/keys/microsoft.ascsudo sh -c 'echo -e "[packages-microsoft-com-prod]\nname=packages-microsoft-com-prod \nbaseurl=https://packages.microsoft.com/yumrepos/microsoft-rhel7.3-prod\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/dotnetdev.repo'

2. Install. NET Core SDK

sudo yum updatesudo yum install libunwind libicusudo yum install dotnet-sdk-2.0.0

Then run the command

dotnet --info

You can check whether the installation is successful. So far, the installation of. Net Core is complete.

Of course, you can also decompress the package for installation. Download the corresponding sdk package for centos7 to the https://www.microsoft.com/net/download/linux and decompress it to the custom installation path.

Sudo mkdir-p/opt/dotnet & sudo tar zxf dotnet.tar.gz-C/opt/dotnet
# You can set the environment variables or use the following method to create soft links, because/usr/local/bin is included in $ PATH by default.
Sudo ln-s/opt/dotnet/usr/local/bin
# Run later to view the installation result
Dotnet -- info

2. Compile and run the project

1. Create an mvc Project

dotnet new mvc -o ntmvc

As shown in:

 

View the ntmvc folder and you can find that the template of an mvc project has been created, as shown below:

2. Modify the Startup. cs file.

You can use vscode to directly modify files on a remote computer or virtual machine, see http://www.cnblogs.com/learn21cn/p/6189023.html

As nginx is used to build a reverse proxy later, modify the code in the Startup. cs file and add references here.Using Microsoft. AspNetCore. HttpOverrides;

And then in the Startup. cs FileConfigureMethod to add a piece of code (for details, see the complete Startup. cs file below ):

Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using Microsoft. aspNetCore. builder; using Microsoft. aspNetCore. hosting; using Microsoft. extensions. configuration; using Microsoft. extensions. dependencyInjection;// Add the reference using Microsoft. AspNetCore. HttpOverrides;Namespace ntmvc {public class Startup {public Startup (IConfiguration configuration) {Configuration = configuration;} public IConfiguration Configuration {get;} // This method gets called by the runtime. use this method to add services to the container. public void ConfigureServices (IServiceCollection services) {services. addMvc ();} // This method gets called by the runtime. use this method Configure the HTTP request pipeline. public void Configure (IApplicationBuilder app, IHostingEnvironment env) {if (env. isDevelopment () {app. useDeveloperExceptionPage ();} else {app. useExceptionHandler ("/Home/Error");} app. useStaticFiles (); app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller = Home}/{action = Index}/{id ?} ");});// Add the following code app. UseForwardedHeaders (new ForwardedHeadersOptions {ForwardedHeaders = ForwardedHeaders. XForwardedFor |ForwardedHeaders. XForwardedProto}); app. UseAuthentication ();}}}

3. Generate a project

Switch to the project directory ntmvc, and then run the following command

dotnet publish -c Release

As follows:

After running the command, the project directory will contain one moreBinFolder

The "bin" folder contains the "Release" folder. The "netcoreapp2.0" folder in the "Release" folder contains the releable content, that isPublishFolder.

Note: The content outside the publish folder is the same as the file generated when we run the dotnet run Command, except that the Debug folder is replaced with the Release folder named by ourselves. In other words, running dotnet publish-c Release has an additional publish folder than running dotnet run, which is exactly the content to be published.

 

4. Run the project

Switch to the publish folder and run the command

dotnet nmvc.dll

As shown in:

5. Automatic project startup

Next, set the project to automatically start upon startup./Etc/systemd/system/Create a new service file

vim /etc/systemd/system/kestrel-ntmvc.service 

The content is as follows:

[Unit]Description=Example .NET Web MVC Application running on Centos7[Service]WorkingDirectory=/root/ntmvcExecStart=/usr/bin/dotnet /root/ntmvc/bin/Release/netcoreapp2.0/publish/ntmvc.dllRestart=alwaysRestartSec=10  # Restart service after 10 seconds if dotnet service crashesSyslogIdentifier=dotnet-exampleUser=rootEnvironment=ASPNETCORE_ENVIRONMENT=Production [Install]WantedBy=multi-user.target

Save and run the following command:

systemctl enable kestrel-ntmvc.service systemctl start kestrel-ntmvc.service systemctl status kestrel-ntmvc.service 

Note: if an error is detected, You need to modify the kestrel-ntmvc.service file. After the modification is correct, you need to run the following command to restart:

systemctl daemon-reloadsystemctl restart kestrel-ntmvc.service 

The following is the result after normal operation

So far, a simple project can be accessed normally. Next, we will transform the project and introduce the use of nginx.

3. Compile and install nginx

1. Install Dependencies

yum -y install gcc gcc-c++ pcre pcre-devel openssl openssl-devel zlib zlib-devel

2. Download the installation package

Please go to the official website to obtain the latest one.

wget http://nginx.org/download/nginx-1.13.5.tar.gz

3. Decompress

mkdir nginxfilestar -zxvf nginx-1.13.5.tar.gz -C nginxfiles

4. Switch Directories

cd nginxfiles/cd nginx-1.13.5/

For example:

5. Compile and install

Run the following command:

# Configuration: additional modules need to be installed here
./Configure -- prefix =/usr/local/nginx -- with-http_ssl_module -- with-stream -- with-mail = dynamic
# Compile
Make
# Installation
Make install

The installation result is as follows:

6. Create a soft link

ln -s /usr/local/nginx/sbin/nginx /usr/local/bin 

As mentioned above, you do not need to set environment variables.

 

Iv. Certificate-related

To enhance project security, you sometimes need to convert http access to https access. This can be achieved by setting the ssl module in nginx.

Typically, this requires a security certificate (commonly used free certificate: https://letsencrypt.org/) from the CA /).

Because this is only used for testing, use the self-generated certificate.

1. Certificate generation

Create a certs folder in the root directory, switch to the folder, and run the following commands in sequence:

# Create a server private key (the password is required during the process, please remember this password) to generate the RSA key openssl genrsa-des3-out testcert. key 1024
# To generate a certificate request, enter the country, region, organization, email, and common name in sequence. The common name can be your name or domain name. If you apply for https, it must match the domain name; otherwise, a browser alarm is triggered. Openssl req-new-key testcert. key-out testcert. csr
# Generate keyopenssl rsa-in testcert. key-out testcert_nopwd.key without a password
# Generate the crt file openssl x509-req-days 365-in testcert. csr-signkey testcert_nopwd.key-out testcert. crt

See the following two figures:

 

2. Certificate location

Copy the certificate to the/etc/ssl/certs/directory

 cp testcert.crt /etc/ssl/certs/ cp testcert_nopwd.key /etc/ssl/certs/testcert.key

For example:

3. difi-Herman Key Exchange

Generally, you can modify the nginx. conf configuration file. To further enhance the security, you can perform key exchange between difi-Herman in the/etc/ssl/certs/directory.

openssl dhparam -out dhparam.pem 4096

The following are generated files:

 

 

5. nginx configuration files

1. Customize the proxy. conf file

Create a new proxy. conf file in the/usr/local/nginx/cong/directory, which will be referenced later in nginx. conf.

proxy_redirect             off;proxy_set_header         Host             $host;proxy_set_header        X-Real-IP         $remote_addr;proxy_set_header        X-Forwarded-For    $proxy_add_x_forwarded_for;proxy_set_header    X-Forwarded-Proto $scheme;client_max_body_size     10m;client_body_buffer_size 128k;proxy_connect_timeout     90;proxy_send_timeout         90;proxy_read_timeout         90;proxy_buffers            32 4k;

2. Modify the nginx. conf file

Modify the nginx. conf file in the/usr/local/nginx/cong/directory, and use different colors to mark the file.

worker_processes  1;events {    worker_connections  1024;}http {    include       proxy.conf;    include       mime.types;    default_type  application/octet-stream;      limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;    server_tokens off;    sendfile        on;    #tcp_nopush     on;        keepalive_timeout  29;    client_body_timeout 10;     client_header_timeout 10;     send_timeout 10;       upstream ntmvc{        server localhost:5000;    }    server {               listen       80;        add_header Strict-Transport-Security max-age=15768000;        return 301 https://$host$request_uri;    }      # HTTPS server    #    server {        listen *:443    ssl;        server_name     localhost;        ssl_certificate /etc/ssl/certs/testcert.crt;        ssl_certificate_key /etc/ssl/certs/testcert.key;        ssl_protocols TLSv1.1 TLSv1.2;        ssl_prefer_server_ciphers on;        ssl_dhparam /etc/ssl/certs/dhparam.pem;        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";        ssl_ecdh_curve secp384r1;        ssl_session_cache shared:SSL:10m;        ssl_session_tickets off;        ssl_stapling on; #ensure your cert is capable        ssl_stapling_verify on; #ensure your cert is capable        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";        add_header X-Frame-Options SAMEORIGIN;        add_header X-Content-Type-Options nosniff;        #Redirects all traffic        location / {            proxy_pass  http://ntmvc;            limit_req   zone=one burst=10 nodelay;            limit_req_status 503;        }    }}

 

 Vi. nginx Automatic startup

# Set nginx to start automatically. Create a service file vim/lib/systemd/system/in the/lib/systemd/system/nginx. service directory.

 Note that the path here is/lib/systemd/system/, rather than the/etc/systemd/system/file of the self-starting service file of the ntmvc project above.

The content is as follows:

[Unit]Description=nginx - high performance web serverAfter=network.target remote-fs.target nss-lookup.target[Service]Type=forkingExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.confExecReload=/usr/local/nginx/sbin/nginx -s reloadExecStop=/usr/local/nginx/sbin/nginx -s stop[Install]WantedBy=multi-user.target

After the file is edited, run the following command to start the service:

Systemctl enable nginx. service # start nginx service systemctl start nginx. service # view the status systemctl status nginx. service

The result is as follows:

Here is a warning because the certificate we use is generated by ourselves, rather than the formal certificate.

After modifying the configuration file, restart the service by running the following command:

# If the file is modified, this is a required systemctl daemon-reload.
# Restart the service systemctl restart nginx. service

 

 VII. Firewall Problems

The following three ports must be enabled. The other ports are based on the actual situation.

# Port firewall-cmd -- zone = public -- add-port = 80/tcp -- permanentfirewall-cmd -- zone = public -- add-port = 5000/tcp -- permanentfirewall-cmd -- zone = public -- add-port = 443/tcp -- permanent # after opening the port, you must reload firewall-cmd -- reload # view all opened ports: firewall-cmd -- list-ports

Specific operations:

 

Reload and display the port

 

 

8. Access related

After the above configuration is complete, if the environment uses a real physical machine or a bridge virtual machine, you can directly access the IP address.

Port ing is required for virtual machines connected by NAT. This experiment uses the virtual machine built by VirtualBox as an example.

If you are directly browsing in a virtual machine, you can browse 127.0.0.1 or localhost.

For access from the host, you can enter https: // 192.168.56.1: 1518 in the browser of the host to map to port 443 of the VM, in this way, you can access the ntmvc project in the virtual machine through https.

Because nginx. conf is configuredAdd_header Strict-Transport-Security max-age = 15768000;That is, only https access is allowed. Therefore, an error occurs when you enter http: // 192.168.56.1: 1518.

The normal access result is shown in (Google Chrome). The reason for this prompt is that the certificate used is self-generated.

 

You can access the page in ntmvc by visiting the website, for example:

 

Official Reference documents:

Https://docs.microsoft.com/zh-cn/aspnet/core/publishing/linuxproduction? Tabs = aspnetcore2x

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.