.Net Core部署在Linux服务器:Nginx反向代理+Supervisor进程守护
Posted bruke
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.Net Core部署在Linux服务器:Nginx反向代理+Supervisor进程守护相关的知识,希望对你有一定的参考价值。
前言:.Net Core 程序(网站)可以部署在windows IIS ,也可以部署在Linux系统(更加推荐)
本文部署,基于.net core 2.1,服务器CentOS 7, 需要安装的服务有2个:nginx,SuperVisor(进程守护)
命令预览:
Linux: 重启:reboot Nginx: 强杀: killall -9 nginx 测试配置是否正确: nginx -t 启动: nginx SuperVisor:停止:supervisorctl shutdown 启动: supervisord
描述:(以下,我以开发一个在线记事本 BookkeepingWeb 为例 )
一。在本地做好项目
开发好Web,并配置好程序监听的端口(不配置,默认5000端口,如果服务器部署多个web的话,这里应该更改端口),VS里面,或者cmd进入到项目进行发布,发布项目下的\\bin\\Debug\\netcoreapp2.1\\publish 后,
在cmd 进入到该项目运行 :dotnet 程序名称.dll ,浏览器打cmd提示的访问地址,保证正常访问。
找到程序的路径:D:\\study\\consoleTest\\Bruke.Bookkeeping\\Bruke.Bookkeeping.Core.Web\\bin\\Debug\\netcoreapp2.1\\publish
程序的启动入口:Bruke.Bookkeeping.Core.Web.dll
运行起来:打开cmd 进入程序路径 执行: dotnet 程序入口名称
执行:dotnet Bruke.Bookkeeping.Core.Web.dll
浏览器查看是否可以访问:http://localhost:5000 ,如图正常。
当cmd关闭或 程序shut down(Ctrl+C) 时, 网站就是访问不了,说明,由cmd单线程监听端口,并执行和返回的。比如浏览器访问了本地5000端口,就会给这个单线程的cmd捕获到,并执行你的代码后返回到浏览器。
至此,本地程序是没问题的,那么就可以把publish拷贝到Linux服务器上了,下面是服务器如何设置监听端口,并转发请求的。
附(设置端口)的博文,可以先忽略该文:https://www.cnblogs.com/1175429393wljblog/p/8267772.html
二.服务器操作
1.接下来就是把publish 拷贝到Linux服务器上去即可,推荐使用 SecureCRSecureFXPortable,可以上传文件,命令运行。
链接: https://pan.baidu.com/s/15kDCQn3xSg4PyZO5R4gPLw 提取码: punw
在服务器 /root 添加文件夹 BookkeepingWeb,把publish的东西拷贝上来。
2.服务上安装.Net Core SDK (基于你的项目版本去安装,我的服务器,安装了.net core 3.0.1,和.net core 2.1,以下为core 2.1为例)
微软官网:https://dotnet.microsoft.com/download/linux-package-manager/rhel/sdk-current
(这个是官网的推荐的sdk 默认3.0版本)
寻找对应2.1的版本:https://dotnet.microsoft.com/download/dotnet-core
https://dotnet.microsoft.com/download/dotnet-core/2.1
执行:sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm
执行:sudo yum install dotnet-sdk-2.1
安装.net core运行环境完毕。
3.服务上安装Nginx:
(可以参考:https://www.jianshu.com/p/e1b5ee442a70)
命令:
curl -o nginx.rpm http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
rpm -ivh nginx.rpm
yum install nginx
至此,安装完毕,外网访问服务器,访问80端口,如图说明,Ngnix部署成功,并完成了监听端口(80)。
打开服务器的目录 /etc/nginx
把配置文件拷贝下来到本地编辑后上传,或者直接在服务器上编辑(不推荐),在本地编辑时,注意使用编码是:utf-8 无bom的格式。
a. nginx.conf
如果nginx.conf和图上没什么区别,就不用管,如果是不同,参考或复制下面的
worker_processes 1; 这个表示nginx运行处理的线程数,推荐使用cpu核数的2倍(https://www.cnblogs.com/aaron-agu/p/8003831.html)
#user nginx; worker_processes 1; #error_log /var/log/nginx/error.log warn; #pid /var/run/nginx.pid; events worker_connections 1024; http include /etc/nginx/mime.types; default_type application/octet-stream; log_format main ‘$remote_addr - $remote_user [$time_local] "$request" ‘ ‘$status $body_bytes_sent "$http_referer" ‘ ‘"$http_user_agent" "$http_x_forwarded_for"‘; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf;
b. default.conf
多个Web,可以使用多个server来设置转发
listen 80;Nginx对外表示监听了80端口,有人访问,IP:80就会使用该配置。
server_name jz.test.com www.test.com;绑定域名(多个域名绑定到同一个web时 ,使用空格隔开即可)
proxy_pass 这个是设置该请求转发的到服务器本地的端口(比如我们的这个项目是5000端口,那么转发过去给它处理就好)
server listen 80; location / proxy_pass http://localhost:5000;
至此,配置完成,把本地的这2个配置,替换到服务器上对于的位置即可。
接下来让Nginx重新加载配置即可(nginx不会自动加载配置的)
使用命令:nginx -t 查看nginx 配置是否配置的对。不正常的话,检查一下配置。
推荐使用:killall -9 nginx 杀死所以nginx 进程。
然后启动命令:nginx
至此,nginx在外网的访问下(80端口),会进行转发到端口5000。
Nginx配置完毕。
4.服务上运行咱们的应用程序:
方法和我们本地上很像啦。
无非就是CD到我们发布的那个目录,执行 dotnet 程序名称.dll
无报错就是启动完成了。这时候,可以用外网浏览器服务IP:80。即可访问到我们的网站了
(原理是,启动网站后,该网站会一直监听我们的端口5000,外网访问的80端口会给Nginx转发到5000,那么我们的网站就可以捕获到并处理返回)。
至此,web部署完毕。
不好意思,还有后续,什么?你忘了我们本地的CMD窗口了吗?只要关闭,或者shut down 就GG。
所以你web虽然部署好了,但是你这个是单线程窗口,只能在里面,退不出来,断开服务器命名窗口,也一样,对不起,GG。
哦,是的,web启动了,和我们的本地的那个cmd太像了,那么我们就需要把我们的网站搞成另一个进程程来执行它,并不退出(俗称进程守护)。
5.安装supervisor进程守护:
【安装Supervisor】
yum install python-setuptools
easy_install supervisor
【配置Supervisor】
mkdir /etc/supervisor
新增一个文件:(这一句不是命令) /etc/supervisor/supervisord.conf
【修改supervisord.conf文件,将文件尾部的配置】
;[include]
;files = relative/directory/*.ini
改成
[include]
files = conf.d/*.conf
注意:conf.d是没有自动创建的,自己手动创建一个,还有就是参考下面的图片,如果没有的,都要自己创建文件夹或文件,配置也贴下面了
supervisord.conf 的代码:
; Sample supervisor config file. ; ; For more information on the config file, please see: ; http://supervisord.org/configuration.html ; ; Notes: ; - Shell expansion ("~" or "$HOME") is not supported. Environment ; variables can be expanded using this syntax: "%(ENV_HOME)s". ; - Quotes around values are not supported, except in the case of ; the environment= options as shown below. ; - Comments must have a leading space: "a=b ;comment" not "a=b;comment". ; - Command will be truncated if it looks like a config file comment, e.g. ; "command=bash -c ‘foo ; bar‘" will truncate to "command=bash -c ‘foo ". ; ; Warning: ; Paths throughout this example file use /tmp because it is available on most ; systems. You will likely need to change these to locations more appropriate ; for your system. Some systems periodically delete older files in /tmp. ; Notably, if the socket file defined in the [unix_http_server] section below ; is deleted, supervisorctl will be unable to connect to supervisord. [unix_http_server] file=/tmp/supervisor.sock ; the path to the socket file ;chmod=0700 ; socket file mode (default 0700) ;chown=nobody:nogroup ; socket file uid:gid owner ;username=user ; default is no username (open server) ;password=123 ; default is no password (open server) ; Security Warning: ; The inet HTTP server is not enabled by default. The inet HTTP server is ; enabled by uncommenting the [inet_http_server] section below. The inet ; HTTP server is intended for use within a trusted environment only. It ; should only be bound to localhost or only accessible from within an ; isolated, trusted network. The inet HTTP server does not support any ; form of encryption. The inet HTTP server does not use authentication ; by default (see the username= and password= options to add authentication). ; Never expose the inet HTTP server to the public internet. ;[inet_http_server] ; inet (TCP) server disabled by default ;port=127.0.0.1:9001 ; ip_address:port specifier, *:port for all iface ;username=user ; default is no username (open server) ;password=123 ; default is no password (open server) [supervisord] logfile=/tmp/supervisord.log ; main log file; default $CWD/supervisord.log logfile_maxbytes=50MB ; max main logfile bytes b4 rotation; default 50MB logfile_backups=10 ; # of main logfile backups; 0 means none, default 10 loglevel=info ; log level; default info; others: debug,warn,trace pidfile=/tmp/supervisord.pid ; supervisord pidfile; default supervisord.pid nodaemon=false ; start in foreground if true; default false minfds=1024 ; min. avail startup file descriptors; default 1024 minprocs=200 ; min. avail process descriptors;default 200 ;umask=022 ; process file creation umask; default 022 ;user=supervisord ; setuid to this UNIX account at startup; recommended if root ;identifier=supervisor ; supervisord identifier, default is ‘supervisor‘ ;directory=/tmp ; default is not to cd during start ;nocleanup=true ; don‘t clean up tempfiles at start; default false ;childlogdir=/tmp ; ‘AUTO‘ child log dir, default $TEMP ;environment=KEY="value" ; key value pairs to add to environment ;strip_ansi=false ; strip ansi escape codes in logs; def. false ; The rpcinterface:supervisor section must remain in the config file for ; RPC (supervisorctl/web interface) to work. Additional interfaces may be ; added by defining them in separate [rpcinterface:x] sections. [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface ; The supervisorctl section configures how supervisorctl will connect to ; supervisord. configure it match the settings in either the unix_http_server ; or inet_http_server section. [supervisorctl] serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket ;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket ;username=chris ; should be same as in [*_http_server] if set ;password=123 ; should be same as in [*_http_server] if set ;prompt=mysupervisor ; cmd line prompt (default "supervisor") ;history_file=~/.sc_history ; use readline history if available ; The sample program section below shows all possible program subsection values. ; Create one or more ‘real‘ program: sections to be able to control them under ; supervisor. ;[program:theprogramname] ;command=/bin/cat ; the program (relative uses PATH, can take args) ;process_name=%(program_name)s ; process_name expr (default %(program_name)s) ;numprocs=1 ; number of processes copies to start (def 1) ;directory=/tmp ; directory to cwd to before exec (def no cwd) ;umask=022 ; umask for process (default None) ;priority=999 ; the relative start priority (default 999) ;autostart=true ; start at supervisord start (default: true) ;startsecs=1 ; # of secs prog must stay up to be running (def. 1) ;startretries=3 ; max # of serial start failures when starting (default 3) ;autorestart=unexpected ; when to restart if exited after running (def: unexpected) ;exitcodes=0 ; ‘expected‘ exit codes used with autorestart (default 0) ;stopsignal=QUIT ; signal used to kill process (default TERM) ;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10) ;stopasgroup=false ; send stop signal to the UNIX process group (default false) ;killasgroup=false ; SIGKILL the UNIX process group (def false) ;user=chrism ; setuid to this UNIX account to run the program ;redirect_stderr=true ; redirect proc stderr to stdout (default false) ;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO ;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;stdout_logfile_backups=10 ; # of stdout logfile backups (0 means none, default 10) ;stdout_capture_maxbytes=1MB ; number of bytes in ‘capturemode‘ (default 0) ;stdout_events_enabled=false ; emit events on stdout writes (default false) ;stdout_syslog=false ; send stdout to syslog with process name (default false) ;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO ;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;stderr_logfile_backups=10 ; # of stderr logfile backups (0 means none, default 10) ;stderr_capture_maxbytes=1MB ; number of bytes in ‘capturemode‘ (default 0) ;stderr_events_enabled=false ; emit events on stderr writes (default false) ;stderr_syslog=false ; send stderr to syslog with process name (default false) ;environment=A="1",B="2" ; process environment additions (def no adds) ;serverurl=AUTO ; override serverurl computation (childutils) ; The sample eventlistener section below shows all possible eventlistener ; subsection values. Create one or more ‘real‘ eventlistener: sections to be ; able to handle event notifications sent by supervisord. ;[eventlistener:theeventlistenername] ;command=/bin/eventlistener ; the program (relative uses PATH, can take args) ;process_name=%(program_name)s ; process_name expr (default %(program_name)s) ;numprocs=1 ; number of processes copies to start (def 1) ;events=EVENT ; event notif. types to subscribe to (req‘d) ;buffer_size=10 ; event buffer queue size (default 10) ;directory=/tmp ; directory to cwd to before exec (def no cwd) ;umask=022 ; umask for process (default None) ;priority=-1 ; the relative start priority (default -1) ;autostart=true ; start at supervisord start (default: true) ;startsecs=1 ; # of secs prog must stay up to be running (def. 1) ;startretries=3 ; max # of serial start failures when starting (default 3) ;autorestart=unexpected ; autorestart if exited after running (def: unexpected) ;exitcodes=0 ; ‘expected‘ exit codes used with autorestart (default 0) ;stopsignal=QUIT ; signal used to kill process (default TERM) ;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10) ;stopasgroup=false ; send stop signal to the UNIX process group (default false) ;killasgroup=false ; SIGKILL the UNIX process group (def false) ;user=chrism ; setuid to this UNIX account to run the program ;redirect_stderr=false ; redirect_stderr=true is not allowed for eventlisteners ;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO ;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;stdout_logfile_backups=10 ; # of stdout logfile backups (0 means none, default 10) ;stdout_events_enabled=false ; emit events on stdout writes (default false) ;stdout_syslog=false ; send stdout to syslog with process name (default false) ;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO ;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;stderr_logfile_backups=10 ; # of stderr logfile backups (0 means none, default 10) ;stderr_events_enabled=false ; emit events on stderr writes (default false) ;stderr_syslog=false ; send stderr to syslog with process name (default false) ;environment=A="1",B="2" ; process environment additions ;serverurl=AUTO ; override serverurl computation (childutils) ; The sample group section below shows all possible group values. Create one ; or more ‘real‘ group: sections to create "heterogeneous" process groups. ;[group:thegroupname] ;programs=progname1,progname2 ; each refers to ‘x‘ in [program:x] definitions ;priority=999 ; the relative start priority (default 999) ; The [include] section can just contain the "files" setting. This ; setting can list multiple files (separated by whitespace or ; newlines). It can also contain wildcards. The filenames are ; interpreted as relative to this file. Included files *cannot* ; include files themselves. [include] files = conf.d/*.conf
这些便是要执行的配置。
如图,该好对应的配置,比如守护名称,命令,命令执行的目录,执行人权限啊。
相当于这配置,就是把我们的手动启动web的工作,交个这个文件,由守护进程去执行即可
DotNetCoreWeb.conf的代码:
[program:DotNetCoreWeb] command=dotnet Bruke.VideoOnline.Web.dll ; directory=/root/Bruke.VideoOnline.Web/ ; autorestart=true ; stderr_logfile=/var/log/DotNetCoreWeb.err.log ; stdout_logfile=/var/log/DotNetCoreWeb.out.log ; environment=ASPNETCORE_ENVIRONMENT=Production ; user=root ; stopsignal=INT
参考图中的备注:
最后启动 运行,查看是否生效
命令:supervisord
下面是执行配置,并守护到后台去。
supervisord -c /etc/supervisor/supervisord.conf
ps -ef | grep DotNetCoreWeb
至此。如果没报错,使用外网即可访问。
以上是关于.Net Core部署在Linux服务器:Nginx反向代理+Supervisor进程守护的主要内容,如果未能解决你的问题,请参考以下文章
Linux中以单容器部署Nginx+ASP.NET Core
So Easy - 在Linux服务器上部署 .NET Core App
在Linux环境下使用Apache部署ASP.NET Core