Nginx hosted. Net Core Applications

Source: Internet
Author: User
Tags dotnet openssl x509

Nginx hosted. Net Core Applications

First, install. Net Core

Reference Official Document: Https://www.microsoft.com/net/core#linuxcentos

1. Add Dotnet Product Feed

Before you install. NET Core, you need to register for a Microsoft product feed. This only needs to be done once. first, sign up for the Microsoft signing 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 the. NET Core SDK

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

Run command after

Dotnet--info

To see if the installation was successful. At this point, the. Net core installation is complete.

Of course, you can also use the decompression installation. Download the SDK package for Centos7 to Https://www.microsoft.com/net/download/linux, then unzip to the custom installation path.

sudo mkdir-p/opt/dotnet && sudo tar zxf dotnet.tar.gz-c/opt/dotnet
# You can set the environment variable, or you can create a soft link in the following way, because/usr/local/bin is included in the $path by default
sudo ln-s/opt/dotnet/dotnet/usr/local/bin
# Run to view installation results later
Dotnet--info

Second, compile and run the project

1. Create a new MVC project

dotnet New Mvc-o Ntmvc

As shown in the following:

Looking at the Ntmvc folder, you can see that a template for an MVC project has been built, as follows:

2. Modify the Startup.cs file

You can use Vscode to directly modify files in a remote computer or a virtual machine, for reference http://www.cnblogs.com/learn21cn/p/6189023.html

Since the back of the use of nginx to build a reverse proxy, here to modify the code in the Startup.cs file, add Reference using the Microsoft.AspNetCore.HttpOverrides;

Then add a piece of code in the Configure method of the Startup.cs file (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 reference using Microsoft.AspNetCore.HttpOverrides;Namespace ntmvc{public class startup {public Startup (IConfiguration configuration) {Conf        iguration = 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 to 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.xforwarded for |Forwardedheaders.xforwardedproto}); App. Useauthentication ();}    }}

3. Build the Project

First switch to the project directory Ntmvc, and then run the following command

dotnet Publish-c Release

As shown below:

After you run the command, a bin folder is found in the project directory

The Bin folder contains the Release folder, which in the netcoreapp2.0 folder in the Release folder contains content that can be published, that is, the publish folder.

Note: The content outside of the publish folder is the same as the file that we generated when we ran the dotnet Run command, except that the Debug folder was replaced by its own named Release folder. In other words, running dotnet publish-c release is a more publish folder than running Dotnet run, and this folder is exactly what you want to publish

4. Running the project

Switch to the Publish folder, run the command

Dotnet Nmvc.dll

As shown in the following:

5. Automatic operation of the project start-up

Next, set up the project to start automatically, create a new service file in /etc/systemd/system/

The contents are 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 seconds if dotnet service crashessyslogidentifier=dotnet-exampleuser=rootenvironment=aspnetcore_ environment=production [Install]wantedby=multi-user.target

After saving, run the following command:

Note: If you check for errors, you need to modify the Kestrel-ntmvc.service file, and after you modify it correctly, you need to run the following command to restart:

The following are the results after normal operation

At this end, a simple project can be accessed normally. Next, the project is reformed, and the use of Nginx is introduced.

Third, compile and install Nginx

1. Installation 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 get the latest.

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

3. Decompression

mkdir NGINXFILESTAR-ZXVF nginx-1.13.5.tar.gz-c Nginxfiles

4. Switch directories

CD NGINXFILES/CD nginx-1.13.5/

Such as:

5. Compile and install

Execute 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
# compilation
Make
# installation
Make install

The following are the results of the installation

6. Create a soft link

As described above, you can no longer set environment variables.

Iv. Certificate-related

To enhance the security of your project, you sometimes need to switch HTTP access to HTTPS access. This can be achieved by setting the SSL module in Nginx.

Typically, this requires requesting a security certificate from the CA (Common Free Certificate: https://letsencrypt.org/).

Since this is for testing purposes only, use the certificate that you generated.

1, the certificate generation

In the root directory, create the Certs folder, switch to the folder, and run the following command:

# Establish the Server private key (the procedure needs to enter a password, please remember this password) generate RSA key OpenSSL genrsa-des3-out Testcert.key 1024  
# to generate a certificate request you need to enter the country, region, organization, Email,common name, etc., common name can write your name or domain name. If you are applying for HTTPS, you must match the domain name, otherwise the browser alert will be raised. OpenSSL Req-new-key testcert.key-out TESTCERT.CSR
# Generate Keyopenssl rsa-in testcert.key-out testcert_nopwd.key that do not require a password
# Generating CRT files OpenSSL x509-req-days 365-in testcert.csr-signkey testcert_nopwd.key-out testcert.crt

As shown in the following two graphs:

2, the location of the certificate

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

CP TESTCERT.CRT/ETC/SSL/CERTS/CP Testcert_nopwd.key/etc/ssl/certs/testcert.key

Such as:

3. Deffee-Herman Key Exchange

In general, you can then modify the nginx.conf configuration file. To further enhance security, Deffee-Herman key Exchange can be performed in the/etc/ssl/certs/directory

OpenSSL dhparam-out Dhparam.pem 4096

The following is the generated file

Five, nginx configuration file related

1. Custom proxy.conf Files

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

Proxy_redirect             off;proxy_set_header         Host             $host;p roxy_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            4k;

2. Modify the nginx.conf file

Modify the nginx.conf file in the/usr/local/nginx/cong/directory, emphasizing that the points have been annotated with different colors.

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;Client_body_timeout 10;     Client_header_timeout 10;       Send_timeout 10; Upstream ntmvc{server localhost: the;} 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 capableAdd_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=10Nodelay;Limit_req_status 503; }    }}

six, Nginx boot automatically start

# set Nginx self-boot, create a service file under the/lib/systemd/system/directory Vim/lib/systemd/system/nginx.service

Note that the path here is/lib/systemd/system/, not the/etc/systemd/system/of the above NTMVC project since the start of the service file is worth noting.

The contents are 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 editing is complete, run the following command to start the service:

Systemctl enable nginx.service# to start the Nginx service systemctl start nginx.service# view state systemctl status Nginx.service

The results are as follows:

There is a caveat here because the certificate we use is generated by ourselves, not by a formal certificate.

Typically, you need to restart the service after modifying the configuration file to execute the following command:

# If the file is modified, this is a must systemctl daemon-reload
# Restart Service Systemctl Restart Nginx.service

Vii. Firewall-related

The following three ports are required to be open, depending on the situation.

#端口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# start port must be reloaded firewall-cmd--reload# View all open ports: Firewall-cmd  --list-ports

The specific operation:

Reload and display port

Viii. access to relevant

When the above configuration is complete, if the environment is using a real physical machine, or a bridged virtual machine, direct access to the IP address is possible.

If it is a NAT-connected virtual machine, port mapping is required. This experiment uses the VirtualBox to build the virtual machine, take this as an example, according to set up can.

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

If you are accessing from a host, you can enter https://192.168.56.1:1518 in the host's browser to map to port 443 of the virtual machine, so that the NTMVC project in the virtual machine can be accessed over HTTPS.

Because Add_header strict-transport-security max-age=15768000 is configured in nginx.conf ; that is, HTTPS access is allowed only, so entering http://192.168.56.1:1518 will prompt an error.

As shown in the normal access results (Google Chrome), the reason for this is that the certificate used is generated by itself.

Continue to access the pages in Ntmvc, such as:

Official Reference documents:

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

Category:. Net Core,nginx,linux,centos

Nginx hosted. Net Core Applications

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.