nginx的TCP代理功能跟nginx的反向代理不同的是:请求该端口的所有流量都会转发到目标服务器,而在反向代理中可以细化哪些请求分发给哪些服务器;另一个不同的是,nginx做TCP代理并不仅仅局限于WEB的URL请求,还可以转发如memcached、MySQL等点到点的请求
实现步骤如下:
(1)nginx在编译时添加“–with-stream”:
./configure –prefix=/usr/local/nginx –user=www –group=www –with-http_stub_status_module –with-pcre=/usr/local/src/pcre-8.38 –add-module=/usr/local/src/ngx_cache_purge-2.3 –with-http_gzip_static_module –with-stream
(2)修改nginx配置文件nginx.conf:
1
|
[root@tkde-iphone ~] # vim /usr/local/nginx/conf/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
48
|
user www www; worker_processes 32; pid logs /nginx .pid;
events { #use epoll; #Linux最常用支持大并发的事件触发机制
worker_connections 65535;
} stream { upstream zifangsky {
hash $remote_addr consistent;
server 10.10.100.31:8000;
}
server {
listen 8080;
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;
}
}
} |
在上面的配置文件中配置了在访问此服务器的8080端口时,会将流量相应转发到10.10.100.31这个服务器的8000端口上
(3)查看是否监听端口:
1
|
[root@app01 nginx] # netstat -apn | grep 8080:
|
(4)测试连接目标端口:
1
2
3
4
|
[root@app01 nginx] # telnet 10.10.100.31 8000
Trying 10.10.100.31... Connected to 10.10.100.31. Escape character is '^]' .
|
(5)在其他客户机上测试连接nginx服务器的8080端口端口:
1
2
3
4
5
|
[root@app05 ~] # telnet 192.168.1.30 8080
Trying 192.168.1.30... Connected to 192.168.1.30. Escape character is '^]' .
Connection closed by foreign host. |
当然,后面就是在客户机上将原来连接10.10.100.31的地方改成连接nginx服务器的地址,如果业务没有出现问题的话,则说明已经配置完成了
本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1864242,如需转载请自行联系原作者