nginx 概述:
nginx 服务由一个 master 进程和多个 worker 进程组成,master 进程主要负责读取和应用配置,以及维护 worker 进程,worker 进程负责实际处理请求。Nginx 基于事件处理机制来高效地将请求分配给 worker 进程,worker 进程的数量可以在配置文件中预先定义好或者基于可用CPU数量自动调整匹配。
nginx 配置文件:
- 配置文件默认路径为 /usr/local/nginx/conf/nginx.conf,或者 /etc/nginx/nginx.conf,或者 /usr/local/etc/nginx/nginx.conf
- 配置文件由指令和指令块(block)组成,单个指令有指令名和参数组成,英文分号(;)结尾。指令块由大括号({和})将多个指令包括起来,如果一个指令块中可以包含其他指令块,则称这个指令块为一个上下文(context),例如 events,http,server,location 等。
如果指令没有被包括任何上下文中,则认为其在上下文 main 中。events 和 http 的指令被放在上下文 main 中,server 的指令在上下文 http 中,location 的指令在 server 中。
配置文件中通过 # 来定义注释。
当 nginx 进程启动后,可以通过nginx -s <signal> 参数向 master 进程发送信号,信号有下面几种:
- stop:快速停止 nginx 进程。
- quit:同样是停止进程,但是会等待全部 worker 进程处理完成当前已经收到的请求。
- reload:当 master 进程收到 reload 信号后,会首先检查新的配置文件的语法,如果检查通过,master 进程会启动新的 worker 进程,并发消息给旧的 worker 进程通知其关闭,当 worker 进程收到关闭通知后,会停止接收新的请求,处理完成当前处理中的请求,然后退出。如果配置文件检查没有通过,master 进程会回滚配置并仍然使用原有配置工作。
- reopen:重新打开(新的)日志文件,该操作可以用于日志的分割,例如当日志积累到一定大小后,先使用 mv 命令将原日志移动到新的目录下,然后使用 reopen 信号告知 nginx 重新打开新的日志文件用于日志记录。
nginx 反向代理和负载均衡的基础配置实验:
nginx服务器我们安装在一台CentOS 7.3上面,后端两台server一台是CentOS 6.9搭建的Apache,一台用Windows Server 2012搭建的IIS。
CentOS6.9搭建Apache:
安装:yum installhttpd
启动服务:servicehttpd start
配置开机启动:chkconfighttpd on
找一个测试用的http模板网站上传到httpd默认目录/var/www/html下(在/etc/httpd/conf/httpd.conf中配置),如果需要的话,调整一下iptables。测试站点是否可以访问:
Windows Server 2012搭建IIS站点:
安装:在添加删除角色和功能(Rolesand Features)中添加Web Server (IIS)
默认安装后,找一个测试用的http模板网站上传到http默认目录C:\inetpub\wwwroot下,如果需要的话,调整一下防火墙规则。测试站点是否可以访问:
安全起见我们可以把后端这两台server的http侦听端口修改为一个高位端口,例如:61234:
CentOS 6.5上面修改/etc/httpd/conf/httpd.conf中的Listen端口,Windows IIS上面修改bind中的绑定端口。
配置好之后,开始搭建nginx:
首先添加nginx的repo,添加/etc/yum.repos.d/nginx.repo文件,写入下面的内容:
[nginx]
name=nginxrepo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
保存退出,使用yuminstall nginx安装。
安装完成后启动服务:systemctlstart nginx
设置开机启动:systemctlenable nginx
测试nginx安装是否成功:
接下来就是配置nginx配置文件了,由于nginx模块非常多,所以可以变查变学习nginx各个模块对应的配置,可以参考官网上面的说明:
举个例子,要配置http的配置,就可以在上面链接中找到ngx_http_core_module模块,打开对应的链接,里面会有http配置的详细指令和参数说明,如果要了解http下面的upstream模块,可以找到ngx_http_upstream_module的链接查看。
接着我们配置一个简单的负载均衡,修改/etc/nginx/nginx.conf文件内容如下:
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;
upstream backend{ server 172.16.0.11:61234; server 172.16.0.6:61234; }
server{ listen 80; server_name localhost; location / { proxy_pass http://backend; } } } |
上面配置里面172.16.0.11和172.16.0.6分别是前面我们做的IIS和Apache的机器的内网地址,配置完成后使用nginx -s reload。
尝试访问一下nginx,发现提示502 Bad Gateway:
首先使用paping测试一下nginx到两台后端web服务器是否可达:
再测试一下web页面是否能够返回内容:
测试发现都没问题并且nginx的配置也正常,再查看一下nginx的errorlog:
可以看到在连接后端两台web服务器的时候报Permission denied,于是使用setenforce0将selinux关闭,再次访问发现正常了:
多测试几次看一下负载均衡是否运行正常:
测试没问题,最后把selinux配置文件修改下,大功告成:
当然,nginx能够实现的功能以及后续的优化还有很多,具体就需要各位看官实践出真知了~~