首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

nginx-实现四层协议的负载均衡

前言

nginx在1.9.0的时候,增加了一个 stream 模块,用来实现四层协议(网络层和传输层)的转发、代理、负载均衡等。stream模块的用法跟http的用法类似,允许我们配置一组TCP或者UDP等协议的监听,然后通过proxy_pass来转发我们的请求,通过upstream添加多个后端服务,实现负载均衡。

编译安装

nginx默认是没有编译这个模块的,要使用stream模块,编译的时候记得加上--with-stream这个参数即可。

./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_stub_status_module --with-stream

make

make install

检查是否已经带有stream模块

/usr/local/nginx/sbin/nginx -V

nginx version: nginx/1.12.2

built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)

built with OpenSSL 1.0.2k-fips 26 Jan 2017

TLS SNI support enabled

configure arguments: --prefix=/usr/local/nginx --user=www --group=www --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_stub_status_module --with-stream

简单配置

在nginx.conf默认配置文件里面,默认没有stream的配置。stream模块的配置跟http配置是同级的,因此要注意不要写到http里面。

user www;

worker_processes auto;

error_log /data/log/nginx/error.log;

pid /run/nginx.pid;

events {

worker_connections 1024;

}

# 这里是http模块的相关配置

http {

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 /data/log/nginx/access.log main;

sendfile on;

tcp_nopush on;

tcp_nodelay on;

keepalive_timeout 65;

types_hash_max_size 2048;

include /usr/local/nginx/etc/mime.types;

default_type application/octet-stream;

server {

listen 80 default_server;

listen [::]:80 default_server;

server_name _;

root /data/www/html;

error_page 404 /404.html;

location = /40x.html {

}

error_page 500 502 503 504 /50x.html;

location = /50x.html {

}

}

}

#这里开始才是stream模块的配置

stream {

upstream tcp_server {

server 192.168.1.10:8888;

server 192.168.1.11:8888;

}

upstream udp_server{

server 192.168.1.10:8877;

server 192.168.1.11:8877;

}

server {

listen 10133;

proxy_pass tcp_server;

}

server {

listen 10123 udp;

proxy_pass udp_server;

}

}

配置完可以使用/usr/local/nginx/sbin/nginx -t 进行测试。

总结

以前做四层协议负载均衡的时候,一般都会用到lvs、HAproxy、F5等,但是要么很贵,要么配置麻烦,而nginx配置简单,能快速完成工作。

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20190102A1DU8B00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券