Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。由Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的。官网是nginx.org。
Nginx是本次HA方案中使用频率最高的,非常好用。感谢战斗民族!
CentOS7的默认yum源中没有Nginx,所以要新增一个nginx源。在/etc/yum.repos.d下添加文件nginx.repo:
[nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=0 enabled=1 yum安装nginx $ yum install nginx -y 关闭selinux $ setenforce 0 启动nginx $ systemctl enable nginx $ systemctl start nginx用浏览器打开 http://192.168.30.1/出现如下欢迎界面,安装完成!
在/var/lib/tomcat/webapps/下创建目录helloproject:
$ mkdir helloproject $ cd helloproject $ touch index.htmlindex.html:
<html> <head></head> <body> <h2>Hello nginx !</h2> <h2>I'm host1.</h2> </body> </html>重启tomcat
$ systemctl restart tomcat用浏览器打开http://192.168.30.1:8080/hellonginx出现如下界面
增加nginx配置文件在/etc/nginx/conf.d/中增加配置文件http_proxy.conf:
server { listen 80; server_name localhost; location /hellonginx{ proxy_pass http://localhost:8080/hellonginx; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; } } $ nginx -s reload用浏览器打开http://192.168.30.1/hellonginx,出现如下界面,http反向代理成功。
从nginx-v1.9.0开始,nginx增加了ngx_stream_core_module模块,开始提供对tcp/udp的反向代理功能。But, 编译时需要带--with-stream参数,yum安装的nginx默认是没有这个功能。So, 我们只能重新通过源码安装了。
开始安装:
# 关闭yum安装的nginx $ systemctl stop nginx # 卸载yum安装的nginx $ yum remove nginx # 下载nginx最新稳定版源码包 $ wget http://nginx.org/download/nginx-1.10.2.tar.gz # 解压缩 $ tar xvf nginx-1.10.2.tar.gz $ cd nginx-1.10.2 $ ./configure --with-stream $ make $ make install安装完后nginx的主目录在/usr/local/nginx,我们需要改一下环境变量来使nginx命令生效,这里就不叙述怎么改环境变量。
修改nginx.conf在上文中可以看到,yum安装的nginx有一个配置文件目录/etc/nginx/conf.d,当我们增加一个代理的时候只要在这个目录中增加一个配置文件即可,而不必修改nginx.conf文件。显然,源码安装的nginx没有,那么只要稍改一下nginx.conf就可以达到这个效果。修改/usr/local/nginx/conf/nginx.conf如下:
…… http { …… include /etc/nginx/conf.d/*.conf; …… }另外,再增加tcp的配置目录:
$ mkdir /etc/nginx/conf_stream.d//usr/local/nginx/conf/nginx.conf增加配置如下:
…… stream { include /etc/nginx/conf_stream.d/*.conf; } 配置tcp反向代理在/etc/nginx/conf_stream.d/中增加配置文件tcp_proxy.conf:
server { listen 0.0.0.0:22222; proxy_pass 192.168.30.1:22; } $ nginx -s reload在host2下测试ssh通过22222端口连接:
$ ssh -p 22222 root@192.168.30.1ssh连接成功,tcp反向代理完成。
