【.Net Core】 使用 Nginx 发布 .Net Core 3.1 项目至LInux(Centos7)。

前置博客(博客中使用的项目来自于此):

【Docker】 .Net Core 3.1 webapi 集成EF Code First,使用MySql进行业务操作 、配置swagger (三)

 

环境:.Net Core 3.1 , Centos7.6

工具:连接工具MobaXterm,阿里云服务器一台

 

1.安装微软签名,不安装不能使用net。

rpm --import https://packages.microsoft.com/keys/microsoft.asc

 

2.安装.net环境,也可以单独安装 dotnet-runtime ,但是缺少很多方便的工具包,不推荐。

yum install dotnet-sdk-3.1

 

3.先修改要发布的端口号,再右键项目发布,然后修改信息,发布。

 

 

 发布完,到目标文件夹把文件拖到  /home/xxx(随意取名)   目录下

      

dotnet Test.dll 

使用donet XXX运行项目,Test.dll是项目名。 运行后此项目只能本机访问,没有任何作用

 

 

 PS.

下面使用nginx进行代理转发请求,使外网也能访问。

如果启动的端口是5000,Nginx 可把5000端口映射到其他端口。

 

4.添加 Nginx 存储库

在某些Centos版本要添加 CentOS 7 EPEL 仓库,实测Centos7.8不需要 :

yum install epel-release

 

5.安装 Nginx

yum install nginx

 

6.启动 Nginx

 systemctl enable nginx  #设置nginx为开机启动

 systemctl start nginx  #启动nginx服务

 // 其他

 systemctl stop nginx     #停止 nginx 服务

 systemctl restart nginx  #重启 nginx 服务

 systemctl nginx reload   #重新加载配置文件。

 systemctl status nginx   #查看服务器状态

 ps -ef | grep nginx      #查看Nginx是否启动

 

 

7.修改 Nginx 配置文件

两种方法,第一种是把 /etc/nginx/nginx.conf 文件中直接改 server 配置信息

第二种是把 /etc/nginx/nginx.conf 文件中server注释掉,然后在 /etc/nginx/conf.d/ 添加一个 xxx.conf 配置文件,如下所示

 

 

  红色画圈部分的意思是加载这个文件夹下面的所有 .conf 配置文件

 新建一个xxx.conf配置文件

 

 

 

 

 

 netcore.conf 配置如下

server {
    listen 80;
    location / {
        proxy_pass http://localhost:8001;
        
        proxy_http_version 1.1;

        proxy_set_header Upgrade $http_upgrade;

        proxy_set_header Connection keep-alive;

        proxy_set_header Host $http_host;
 
        proxy_cache_bypass $http_upgrade;
    }
}

保存后重启nginx

 systemctl restart nginx  #重启 nginx 服务

或者刷新配置

sudo nginx -t    #检查配置文件
sudo nginx -s reload    #重新加载配置文件

访问站点80端口(80端口是默认端口自动隐藏),此端口会被nginx转发至 8001端口

 

8.配置守护进程Supervisor

项目启动只能前台运行,不能进行其他操作,所以要建一个守护进程,使得项目后台运行

安装 supervisor

yum install supervisor

 检查 /etc/supervisord.conf 配置文件,如果不为圈中代码,请修改为圈中代码。

意思是 supervisord.d 文件夹下的所有 ini 类型的文件都是配置文件

 

 

 

到/etc/supervisord.d 目录下 新建 xxx.ini文件,文件配置内容如下 自己定义,记得一定要改运行命令和程序路径。

[program:TestNetCore]
command=dotnet Test.dll                        #运行命令
directory=/home/dotnet/Test                    #程序路径
environment=ASPNETCORE__ENVIRONMENT=Production #环境变量
user=root        #设置启动进程的用户,默认是root
stopsignal=INT   #请求停止时用来杀死程序的信号
autostart=true   #自动启动
autorestart=true #3秒自动重启
startsecs=3      #自动重启间隔
stderr_logfile=/var/log/ossoffical.err.log  #标准错误日志 路径可以自定义
stdout_logfile=/var/log/ossoffical.out.log  #标准输出日志  路径可以自定义

保存配置文件,启动守护进程,然后设置开机启动

supervisord -c /etc/supervisord.conf  #启动服务
supervisorctl reload #重新加载配置
systemctl enable supervisord #开机启动

其他相关操作

supervisorctl shutdown #关闭
systemctl is-enabled supervisord #验证是否开机启动
systemctl status supervisord.service #执行命令,查看服务器启动失败的原因

 

Tags: