如题所示,nginx在1.9版本之后可以充当端口转发的作用,即:访问该服务器的指定端口,nginx就可以充当端口转发的作用将流量导向另一个服务器,同时获取目标服务器的返回数据并返回给请求者。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:
[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
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)查看是否监听端口:
[[email protected] nginx]# netstat -apn | grep 8080:
(4)测试连接目标端口:
[[email protected] nginx]# telnet 10.10.100.31 8000 Trying 10.10.100.31... Connected to 10.10.100.31. Escape character is ‘^]‘.
(5)在其他客户机上测试连接nginx服务器的8080端口端口:
[[email protected] ~]# 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服务器的地址,如果业务没有出现问题的话,则说明已经配置完成了
时间: 2024-10-10 15:04:55