nginx在1.9版本以後能夠充當端口轉發的做用,即:訪問該服務器的指定端口,nginx就能夠充當端口轉發的做用將流量導向另外一個服務器,同時獲取目標服務器的返回數據並返回給請求者。html
nginx的TCP代理功能跟nginx的反向代理不一樣的是:請求該端口的全部流量都會轉發到目標服務器,而在反向代理中能夠細化哪些請求分發給哪些服務器;另外一個不一樣的是,nginx作TCP代理並不單單侷限於WEB的URL請求,還能夠轉發如memcached、MySQL等點到點的請求nginx
實現步驟以下:vim
(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 其中 /usr/local/src/ngx_cache_purge-2.3 是下載 ngx_cache_purge-2.3 解壓後的目錄 /usr/local/src/pcre-8.38 是下載 pcre-8.38 解壓後的目錄
(2)修改nginx配置文件nginx.conf:併發
[root@tkde-iphone ~]# 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端口上app
(3)查看是否監聽端口:iphone
[root@app01 nginx]# netstat -apn | grep 8080:
(4)測試鏈接目標端口:tcp
[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端口端口:memcached
[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服務器的地址,若是業務沒有出現問題的話,則說明已經配置完成了測試
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
stream { upstream test-server-sr { server 20.0.1.104:11000; } server { #so_keepalive=on 保證鏈接持續 listen 12000 so_keepalive=on; #listen 12000; # proxy_connect_timeout 1s; # # proxy_timeout 3s; proxy_pass test-server; } } }