高可用笔记(1) nginx

高可用笔记(1) nginx

felenwe  2017-01-11 15:15:24  浏览95  评论0

nginx HA

摘要: Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。由Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的。官网是[nginx.org](http://nginx.org)。 Nginx是本次HA方案

Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。由Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的。官网是nginx.org

Nginx是本次HA方案中使用频率最高的,非常好用。感谢战斗民族!

测试环境

  1. host1 192.168.3.21 (本文都在host1下进行)
  2. host2 192.168.3.22
  3. host3 192.168.3.23

CentOS7 下yum安装Nginx

  • 添加nginx的yum源文件

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

http反向代理

  • 部署tomcat项目helloproject

在/var/lib/tomcat/webapps/下创建目录helloproject:

$ mkdir helloproject
$ cd helloproject
$ touch index.html

index.html:

<html>
        <head></head>
        <body>
                <h2>Hello nginx !</h2>
                <h2>I'm host1.</h2>
        </body>
</html>

重启tomcat

$ systemctl restart tomcat

用浏览器打开http://192.168.3.21:8080/hellonginx出现如下界面
screenshot

  • 增加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.3.21/hellonginx,出现如下界面,http反向代理成功。
screenshot

tcp反向代理

  • 源码安装nginx 从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.3.21:22;
}
$ nginx -s reload

在bash下测试ssh通过22222端口连接:

$ ssh -p 22222 root@192.168.3.21

ssh连接成功,tcp反向代理完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值