简言

nginx在1.9版本之后可以充当端口转发的作用,即:访问该服务器的指定端口,nginx就可以充当端口转发的作用将流量导向另一个服务器,同时获取目标服务器的返回数据并返回给请求者。nginx的TCP代理功能跟nginx的反向代理不同的是:请求该端口的所有流量都会转发到目标服务器,而在反向代理中可以细化哪些请求分发给哪些服务器;另一个不同的是,nginx做TCP代理并不仅仅局限于WEB的URL请求,还可以转发如memcached、MySQL等点到点的请求.。
实现步骤如下:

一、安装nginx的依赖库

1.安装prce(重定向支持)和openssl(https支持,如果不需要https可以不安装。)
推荐使用yum装方便,也可以下载tar编译安装

1
2
3
yum -y install pcre*
yum -y install openssl*

2.安装ngx_cache_purge

1
2
wget -O /usr/src/ngx_cache_purge-2.3.tar.gz  http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz

下载后,解压放到/usr/local/src/目录即可,无需编译安装

二、下载并安装nginx

1.下载nginx包

1
2
wget http://nginx.org/download/nginx-1.9.9.tar.gz

2.解压并且安装

1
2
tar -zxvf nginx-1.9.9.tar.gz

3.进入到nginx目录编译安装

1
2
3
4
cd nginx-1.9.9
./configure --prefix=/usr/local/nginx --add-module=/usr/local/src/ngx_cache_purge-2.3 --with-http_stub_status_module --with-stream
make && make install;

其中 /usr/local/src/ngx_cache_purge-2.3 是下载 ngx_cache_purge-2.3 解压后的目录

4.修改nginx的配置文件nginx.conf
内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
worker_processes  32; 

events {
#use epoll;
worker_connections 65535;
}

stream {
upstream zifangsky {
hash $remote_addr consistent;
server 192.168.4.137:8360;
}
server {
listen 80;
proxy_connect_timeout 5s;
proxy_timeout 5s;
proxy_pass zifangsky;
}
}
http {
include mime.types;
default_type application/octet-stream;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;

server {
listen 9000;
server_name localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root html;
index index.html index.htm;
}
}

}

三、相关命令

1.查看是否监听端口

1
2
netstat -apn | grep 8080:

2.查看nginx的进程

1
2
ps -ef | grep nginx

3.查看nginx的版本

1
2
nginx -V

4.记得关闭防火墙或者开启相关端口
查看防火墙的状态
关闭防护墙
开机关闭防火墙

1
2
3
4
firewall-cmd --state
systemctl stop firewalld.service
systemctl disable firewalld.service

5.杀掉占用80端口的进程

1
2
3
4
fuser -k 80/tcp
如果没有fuser命令,则用yum安装
yum install -y psmisc