Linux (Centos )搭建Nginx TCP反向代理

        Nginx除了能实现Http的反向代理和负载均衡外,还能实现Tcp的反向代理,做数据库的负载均衡,或者是自己Tcp应用的反向代理,非常的方便,有时还可作为Nat网关使用。

        Nginx在版本1.9.0以后支持Tcp的负载均衡,具体可以参照官网关于模块ngx_stream_core_module的叙述。默认是不安装Tcp模块的,需要自己编译Nginx源码进行安装,从nginx 1.9.0版本开始,安装包内就自带了Tcp模块,需要用到编译需添加--with-stream配置参数。具体步骤如下:

1、安装Nginx

wget http://nginx.org/download/nginx-1.12.1.tar.gz
yum -y install gcc gcc-c++ automake pcre pcre-devel zlib zlib-devel openssl openssl-devel        ## 安装依赖包
tar -zxvf nginx-1.12.1.tar.gz      ## 解压
mv nginx-1.12.1 /usr/local/       ## 放入/usr/local/目录下,推荐,当然也可以是别的位置
cd  /usr/local/nginx-1.12.1        ## 进入解压后的文件价
groupadd nginx                        ## 添加用户组
useradd nginx -g nginx -s /sbin/nologin -M       ## 添加用户名
./configure --with-stream --with-stream_ssl_module --with-http_stub_status_module --user=nginx --group=nginx         ## 加入tcp模块,https模块和状态监控模块一起编译(需要什么模块根据自己的需求进行编译),并指定用户名,用户组
make && make install     ## 编译 安装
 

2、配置

安装完后,在/usr/local/下会有nginx文件夹,里面sbin里的nginx则为运行文件,配置文件为conf/nginx.conf 

2.1 配置Nginx服务器,添加服务器池,实现TCP/UDP反向代理功能

1)修改/usr/local/nginx/conf/nginx.conf配置文件,添加如下配置即可

stream {                  ## stream模块,就跟http模块一样
        server {             ## 配置监听端口和代理的ip和端口就可以进行tcp代理了。
         listen 5580;                    //Nginx监听的端口
         proxy_connect_timeout 100s;
         proxy_timeout 60s;
         proxy_pass backend;
        }
        ## 在tcp请求代理中,也是可以使用负载均衡的upstream的
        upstream backend {
            server 192.168.94.104:5530;
            server 192.168.94.54:5530;
        }
}

2、重启nginx服务

/usr/local/nginx/sbin/nginx -s reload
#请先确保nginx是启动状态才可以执行命令成功,否则报错,报错信息如下:
#[error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
如果还没启动就运行:/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

借此nginx配置完成。

1、在新的服务器安装nginx,在make编译时报错:

make: *** No rule to make target `build', needed by `default'. Stop.

重新安装依赖项

2、如果出现问题提示:

Downloading packages:

warning: /var/cache/yum/x86_64/7/base/packages/wget-1.14-13.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Retrieving key from http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-6


The GPG keys listed for the "CentOS-7 - Base - 163.com" repository are already installed but they are not correct for this package.
Check that the correct key URLs are configured for this repository.


 Failing package is: wget-1.14-13.el7.x86_64
 GPG Keys are configured as: http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-6

解决方法:
运行:rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

修改配置:

猜你喜欢

转载自blog.csdn.net/SkyChaserYu/article/details/88532454