nginx除了代理http协议外,从1.9.0版本开始新增了tcp协议的代理。
代理tcp协议准备工作
代理tcp需要使用stream模块(ngx_stream_core_module),默认configure不包含该模块,需要在configure的时候加上–with-stream
代理tcp的基本配置
官网示例
worker_processes auto;
error_log /var/log/nginx/error.log info;
events {
worker_connections 1024;
}
stream {
upstream backend {
hash $remote_addr consistent;
server backend1.example.com:12345 weight=5;
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
upstream dns {
server 192.168.0.1:53535;
server dns.example.com:53;
}
server {
listen 12345;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass backend;
}
server {
listen 127.0.0.1:53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}
自己使用示例
stream {
upstream cmp_zookeeper {
hash $remote_addr consistent;
server 10.9.71.11:22181 max_fails=3 fail_timeout=30s;
}
server {
listen 2181;
proxy_connect_timeout 10s;
proxy_timeout 300s;
proxy_pass cmp_zookeeper;
}
}
若仅仅是需要反向代理,而不需要负载均衡的话。可以将这个示例简化一下。proxy_pass
后边直接写ip和端口
stream {
server {
listen 3310;
proxy_connect_timeout 10s;
proxy_timeout 300s;
proxy_pass 10.130.29.99:3306;
}
}
官网地址:http://nginx.org/en/docs/stream/ngx_stream_core_module.html
中文地址:https://www.docs4dev.com/docs/zh/nginx/current/reference/stream-ngx_stream_core_module.html