https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/
- 使用NGINX进行TCP和UDP负载平衡的配置示例
stream {
upstream stream_backend {
least_conn;
server backend1.example.com:12345 weight=5;
server backend2.example.com:12345 max_fails=2 fail_timeout=30s;
server backend3.example.com:12345 max_conns=3;
}
upstream dns_servers {
least_conn;
server 192.168.136.130:53;
server 192.168.136.131:53;
server 192.168.136.132:53;
}
server {
listen 12345;
proxy_pass stream_backend;
proxy_timeout 3s;
proxy_connect_timeout 1s;
}
server {
listen 53 udp;
proxy_pass dns_servers;
}
server {
listen 12346;
proxy_pass backend4.example.com:12346;
}
}
user nginx;
worker_processes 1;
events {
worker_connections 1024;
}
stream {
upstream group1 {
hash $remote_addr consistent;
server xxx.xxx.xxx.xxx:xxx; # ip:port
server xxx.xxx.xxx.xxx:xxx; # ip:port
}
upstream group2 {
hash $remote_addr consistent;
server xxx.xxx.xxx.xxx:xxx; # ip:port
server xxx.xxx.xxx.xxx:xxx; # ip:port
}
server {
listen 443;
listen 443 udp;
proxy_pass group1;
}
server {
listen 444;
listen 444 udp;
proxy_pass group2;
}
}
stream {
upstream group1 {
hash $remote_addr consistent; #负载均衡一致性hash算法
server 192.168.1.2:123 max_fails=1 fail_timeout=10s; # ip:port weight为轮询权重 max_fails最大失败尝试次数
server 192.168.1.3:123 max_fails=1 fail_timeout=10s; # ip:port
}
upstream group2 {
hash $remote_addr consistent;
server 192.168.1.3:123 max_fails=1 fail_timeout=10s; # ip:port
server 192.168.1.2:123 max_fails=1 fail_timeout=10s; # ip:port
}
server {
listen 23548 so_keepalive=30m::10; #如果不指定协议的话默认是TCP协议
listen 23548 udp;
proxy_pass group1;
proxy_connect_timeout 10s; #连接超时时间上限
proxy_timeout 20s; #在没有数据传输的情况下,多久之后关闭连接
}
server {
listen 23549 ;
listen 23549 udp;
proxy_pass group2;
}
}
apt-get update
apt-get install nginx -y
service nginx start
systemctl enable nginx.service
nginx -v
service nginx restart
systemctl enable nginx.service
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream appserver {
server 192.168.100.10:9222; # appserver_ip:ws_port
}
server {
listen 8888; // client_wss_port
ssl on;
ssl_certificate /path/to/crt;
ssl_certificate_key /path/to/key;
location / {
proxy_pass http://appserver;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
80端口 中转
server {
listen 12345;
location / {
proxy_http_version 1.1;
proxy_pass http://www.abc.com:80;
proxy_connect_timeout 60s;
proxy_read_timeout 120s;
proxy_send_timeout 120s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}