之前一直在用HaProxy做TCP的负载均衡,但UDP上一直没有启用可行的方案,这次需要UDP,便使用Nginx作为代理服务来使用。记录下具体步骤。

编译安装Nginx并启用stream模块

以下命令均在Ubuntu 16.04中执行。
安装所需的依赖库:

apt install proc* openssl* pcre*

下载所需的版本:

wget -c https://nginx.org/download/nginx-1.14.0.tar.gz 

解压并进入相关目录,执行:

./configure  --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-threads --with-stream --with-mail --with-file-aio  --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic'

注意:以上编译的选项根据自己需求进行编译,也可最简易的配置。

接下来编译:

make & make install

编译完成后会输出配置的结果:

  
nginx path prefix: "/etc/nginx"
nginx binary file: "/usr/sbin/nginx"
nginx modules path: "/etc/nginx/modules"
nginx configuration prefix: "/etc/nginx"
nginx configuration file: "/etc/nginx/nginx.conf"
nginx pid file: "/var/run/nginx.pid"
nginx error log file: "/var/log/nginx/error.log"
nginx http access log file: "/var/log/nginx/access.log"
nginx http client request body temporary files: "/var/cache/nginx/client_temp"
nginx http proxy temporary files: "/var/cache/nginx/proxy_temp"
nginx http fastcgi temporary files: "/var/cache/nginx/fastcgi_temp"
nginx http uwsgi temporary files: "/var/cache/nginx/uwsgi_temp"
nginx http scgi temporary files: "/var/cache/nginx/scgi_temp"

然后尝试启动Nginx,是否有问题:

sudo /usr/sbin/nginx -c /etc/nginx/nginx.conf

配置负载

备份原有的配置文件

cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
cp /dev/null /etc/nginx/nginx.conf
vi /etc/nginx/nginx.conf

填入如下内容:

#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;
}
stream {

    upstream lvs {
       server 101.89.134.11:8989;
       server 101.89.134.12:8989;
       server 101.89.134.13:8989;
    }

    server {
        listen 8989 udp;
        proxy_responses 1;
        proxy_timeout 20s;
        proxy_bind $server_addr:$remote_port;
        proxy_pass dns;
    }
}