阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

CentOS 7环境下使用Nginx托管.Net Core应用程序

168次阅读
没有评论

共计 8060 个字符,预计需要花费 21 分钟才能阅读完成。

一、安装.Net Core

参考官方文档:https://www.microsoft.com/net/core#linuxcentos

1、添加 dotnet 产品 Feed

在安装.NET Core 之前,您需要注册 Microsoft 产品 Feed。这只需要做一次。首先,注册 Microsoft 签名密钥,然后添加 Microsoft 产品 Feed

sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
sudo 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、安装.NET Core SDK

sudo yum update
sudo yum install libunwind libicu
sudo yum install dotnet-sdk-2.0.0

之后运行命令

dotnet --info

可以查看安装是否成功。至此,.Net Core 的安装就完成了。

当然,也可以使用解压安装。到 https://www.microsoft.com/net/download/linux 下载 CentOS7 对应的 sdk 压缩包,之后解压到自定义的安装路径。

sudo mkdir -p /opt/dotnet && sudo tar zxf dotnet.tar.gz -C /opt/dotnet
# 可以设置一下环境变量,也可以采用下面的方式建立软链接,因为
/usr/local/bin 默认包含于 $PATH 中
sudo ln -s /opt/dotnet/dotnet /usr/local/bin
# 之后运行查看安装结果
dotnet --info

二、编译运行项目

1、新建一个 mvc 项目

dotnet new mvc -o ntmvc

如下图所示:

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 查看 ntmvc 文件夹,可以发现,一个 mvc 项目的模板已经建好了,如下:

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

2、修改   Startup.cs 文件

可以使用 vscode 直接修改远程计算机或者是虚拟机中的文件,具体参考  http://www.linuxidc.com/Linux/2017-10/147241.htm

由于后面要用到 nginx 搭建反向代理,在此处修改一下 Startup.cs 文件中的代码,添加引用 using Microsoft.AspNetCore.HttpOverrides;

之后再在 Startup.cs 文件的 Configure 方法中添加一段代码(具体参见下面完整的 Startup.cs 文件):

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;
// 添加引用
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 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?}");
            });
            
            // 添加下面的代码
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseAuthentication();
        }
    }
}

 3、生成项目

首先切换到项目目录 ntmvc,之后运行下面的命令

dotnet publish -c Release

如下所示:

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 运行命令之后,项目目录中会多出一个 bin 文件夹

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 在 bin 文件夹中会包含 Release 文件夹,在 Release 文件夹中的 netcoreapp2.0 文件夹中,会包含可以发布的内容,即 publish 文件夹。

注:publish 文件夹之外的内容,同我们运行 dotnet run 命令时所生成的文件是相同的,只不过 Debug 文件夹换成了自己命名的 Release 文件夹而已。换句话说,运行dotnet publish -c Release 比运行 dotnet run 多了一个 publish 文件夹,而这个文件夹正是所要发布的内容

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

4、运行项目 

切换到 publish 文件夹,运行命令

dotnet nmvc.dll

如下图所示:

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 5、项目的开机自动运行

接下来设置项目的开机自动启动,在 /etc/systemd/system/ 中新建一个服务文件

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

内容如下:

[Unit]
Description=Example .NET Web MVC Application running on Centos7

[Service]
WorkingDirectory=/root/ntmvc
ExecStart=/usr/bin/dotnet /root/ntmvc/bin/Release/netcoreapp2.0/publish/ntmvc.dll
Restart=always
RestartSec=10  # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=dotnet-example
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production 

[Install]
WantedBy=multi-user.target

之后保存,运行以下命令:

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

注意:如果检查到错误,需要修改 kestrel-ntmvc.service 文件,修改正确之后,需要运行以下命令重新启动:

systemctl daemon-reload
systemctl restart kestrel-ntmvc.service

 下面是正常运行后的结果

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 到此为止,一个简单的项目就可以正常访问了。接下来,对项目进行改造,引入 nginx 的使用。

三、编译安装 nginx

1、安装依赖项

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

2、下载安装包

最新的下载地址请到官网获取。

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

3、解压

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

4、切换目录

cd nginxfiles/
cd nginx-1.13.5/

 如下图:

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 5、编译安装

执行以下命令

# 配置:这里需要安装额外的模块
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-stream --with-mail=dynamic
# 编译
make
# 安装
make install

 以下是安装的结果

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 6、创建软链接

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

 如上所述,这样可以不用再设置环境变量。

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

四、证书相关 

为了增强项目的安全性,有时需要将 http 访问转为 https 访问。通过对 nginx 中 ssl 模块进行设置,可以实现这一点。

通常,这需要向 CA 申请安全证书(常用免费证书:https://letsencrypt.org/)。

由于这里仅作测试用,因此使用自己生成的证书。

1、证书的生成

在 root 目录下建立 certs 文件夹,切换到该文件夹,依次运行以下命令:

# 建立服务器私钥(过程需要输入密码,请记住这个密码)生成 RSA 密钥
openssl genrsa -des3 -out testcert.key 1024  
# 生成一个证书请求 需要依次输入国家,地区,组织,email,common name 等,common name 可以写你的名字或者域名。如果为了 https 申请,必须和域名吻合,否则会引发浏览器警报。openssl req
-new -key testcert.key -out testcert.csr
# 生成不需要密码的 key openssl rsa
-in testcert.key -out testcert_nopwd.key
# 生成 crt 文件 openssl x509
-req -days 365 -in testcert.csr -signkey testcert_nopwd.key -out testcert.crt

 如以下两图:

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

2、证书的位置

将证书复制到 /etc/ssl/certs/ 目录

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

 如下图:

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 3、迪菲-赫尔曼密钥交换 

一般来说,之后修改 nginx.conf 配置文件就可以了。为了进一步增强安全性,可以进行迪菲-赫尔曼密钥交换,在 /etc/ssl/certs/ 目录中

openssl dhparam -out dhparam.pem 4096

 以下是生成的文件 

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

五、nginx 配置文件相关 

1、自定义 proxy.conf 文件 

在 /usr/local/nginx/cong/ 目录下新建 proxy.conf 文件,后面会在 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、修改 nginx.conf 文件

修改 /usr/local/nginx/cong/ 目录下的 nginx.conf 文件,着重点已经使用了不同的颜色进行标注。


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;
        }
    }


} 

 六、nginx 开机自动启动

# 设置 nginx 自启动,在 /lib/systemd/system/ 目录下创建一个服务文件
vim /lib/systemd/system/nginx.service

 注意,这里的路径是 /lib/systemd/system/,而非上面 ntmvc 项目自启动服务文件所在的 /etc/systemd/system/ 这一点值得注意。

 内容如下:

[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop

[Install]
WantedBy=multi-user.target

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 文件编辑完成之后,运行以下命令启动服务:

systemctl enable nginx.service
# 启动 nginx 服务
systemctl start nginx.service
# 查看状态
systemctl status nginx.service

 结果如下:CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 这里之所以有一个警告,是因为我们使用的证书是自己生成的,而不是正式的证书。

通常,对配置文件修改后需要重启服务,执行以下命令:

# 如果修改了文件,这个是必须的
systemctl daemon-reload
# 重新启动服务 systemctl restart nginx.service

 七、防火墙相关

 以下的三个端口是必须要开的,其他的视情况而定。

# 端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=5000/tcp --permanent
firewall-cmd --zone=public --add-port=443/tcp --permanent
#开端口后必须重新加载
firewall-cmd --reload
# 查看所有打开的端口:firewall-cmd  --list-ports

 具体的操作如图所示:

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 重新加载并显示端口

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 

八、访问相关

以上的配置完成之后,如果环境使用的是真实的物理机,或者是桥接的虚拟机,直接访问 ip 地址就可以了。

如果是 NAT 连接的虚拟机,需要进行端口映射。本实验使用的 VirtualBox 搭建的虚拟机,以此为例,按下图进行设置即可。

CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

如果是直接在虚拟机中进行浏览,浏览 127.0.0.1 或者 localhost 即可。

如果是从主机进行访问,可在主机的浏览器中输入 https://192.168.56.1:1518,即可映射到虚拟机的 443 端口,这样就可以通过 https 进行访问虚拟机中的 ntmvc 项目。

由于在 nginx.conf 中配置了 add_header Strict-Transport-Security max-age=15768000;  即只能允许 https 访问,因此输入 http://192.168.56.1:1518 会提示错误。

正常的访问结果如下图所示(谷歌浏览器),之所以会出现这样的提示,是因为所用的证书是自己生成的。

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 继续访问即可访问 ntmvc 中的页面,如下图:

 CentOS 7 环境下使用 Nginx 托管.Net Core 应用程序

 官方参考文档:

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

http://www.linuxidc.com/Linux/2017-10/147241.htm

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-21发表,共计8060字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中