此次主要为了练习和熟悉Nginx这个反向代理服务器的反向代理功能和它的负载均衡功能。反向代理,主要用于服务器集群分布式部署的情况下,反向代理隐藏了服务器的信息。以前没有自己安装和配置使用过,这次练习,总结一下安装和使用心得。
Nginx安装总结:
Nginx安装非常容易,类似于Tomcat安装(下面的所有安装都在centOS 7系统中安装),
本人安装nginx-1.12.2.tar.gz版本。
安装Nginx时,必须先安装相应的编译工具,
#yum -yinstall gcc gcc-c++ autoconf automake
此外,Nginx还需要依赖以下工具:
zlib:Nginx提供gzip模块,需要zlib库支持
openssl:Nginx提供ssl功能
pcre:支持地址重写rewrite功能
yum -yinstall zlib zlib-devel openssl openssl--devel pcre pcre-devel
将已下载好的nginx-1.12.2.tar.gz解压: tar –vxzf nginx-1.12.2.tar.gz
配置configure:./configure --prefix=/usr/local/nginx --user=nobody
prefix是设定安装目录,而user是设置nginx的worker用户
执行编译和安装命令 make make install
将Nginx设置Linux系统开机启动:
创建设置启动脚本文件nginx,然后拷贝到/etc/init.d/下
执行设置文件的执行权限chmod a+x /etc/init.d/nginx将脚本文件设置成可执行文件
使用chkconfig进行管理,将nginx服务加入chkconfig管理列表chkconfig --add /etc/init.d/nginx
加完这个之后,就可以使用service对nginx进行启动,重启等操作了
servicenginx start
servicenginx stop
然后通过chkconfig将nginx启动
Chkconfignginx on
Tomcat安装类似:
解压apache-tomcat-8.5.23.tar.gz到指定位置
tomcat服务器运行时是需要JDK支持的,所以必须配置好JDK用到的那些环境变量
编辑/etc下的profile文件,添加如下信息(jdk信息):
# jdkinfoMessage
exportJAVA_HOME=/usr/local/java/jdk1.8.0_161
exportJRE_HOME=/usr/local/java/jdk1.8.0_161/jre
exportPATH=$PATH:/usr/local/java/jdk1.8.0_161/bin
exportCLASSPATH=./:/usr/local/java/jdk1.8.0_161/lib:/usr/local/java/jdk1.8.0_161/jre/lib
本人使用Nginx作为接收请求的服务器,以下是我的个人Nginx配置文件:
worker_processes 2;
#工作模式及连接数上限
events {
#epoll是多路复用IO(I/OMultiplexing)中的一种方式,
#仅用于linux2.6以上内核,可以大大提高nginx的性能
use epoll;
#单个后台worker process进程的最大并发链接数
worker_connections 2048;
}
# http设置
http {
#设定mime类型,类型由mime.type文件定义
include 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 logs/access.log main;
#sendfile 指令指定nginx 是否调用 sendfile 函数(zerocopy 方式)来输出文件
#对于普通应用,必须设为 on,
#如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
#以平衡磁盘与网络I/O处理速度,降低系统的uptime.
sendfile on;
#tcp_nopush on;
#连接超时时间
#keepalive_timeout 0;
keepalive_timeout 65;
#开启gzip压缩
gzip on;
# 负载均衡配置 反向代理服务器的服务器池 服务器的集群
upstream tomcatDemo {
#ip_hash;
#服务器1
server 192.168.226.129:8129 weight=2;
#服务器2
server 192.168.226.130:8130 weight=1;
}
#设定虚拟主机配置 服务器主机配置
server {
#侦听 8199 端口
listen 8199;
#定义使用 localhost 访问
server_name ngdemo.com.cn;
charset utf-8;
#设定本虚拟主机的访问日志
access_log logs/host.access.log main;
location / {
add_headerAccess-Control-Allow-Origin *;
root /home/webapp/static/app;
#定义首页索引文件的名称
index index.html index.htm;
}
#路由配置
location /tomcatDemo {
#用于指定反向代理服务器的服务器池
proxy_pass http://tomcatDemo;
#作用web服务器上有多个站点时,用该参数header来区分反向代理哪个域名
proxy_set_header Host $host;
#作用是后端服务器上的程序获取访客真实IP,从该header头获取。部分程序需要该功能
proxy_set_header X-Forwarded-For $remote_addr;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
下面是我的nginx运行的项目:
下面是利用了负载均衡的效果:
请求分发到不同的服务器上了