当前nginx-13.1已经支持tcp,ucp,unix域套接字三种负载均衡模式(http肯定支持,这个不用说)。最近有需求需要对后端服务做负载均衡,因此考虑使用nginx来做。
1. 下载nginx,我下载的是nginx-release-1.13.1:
https://github.com/nginx/nginx
2. 编译,安装:
./auto/configure --prefix=/home/stars/support/nginx-release-1.13.1/install --with-threads --with-stream
make && make install
3. 编辑/home/stars/support/nginx-release-1.13.1/install/conf/nginx.conf:
#user nobody;
worker_processes ; #error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info; #pid logs/nginx.pid; events {
worker_connections ;
} 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 ;
keepalive_timeout ; #gzip on; server {
listen ;
server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / {
root html;
index index.html index.htm;
} #error_page /.html; # redirect server error pages to the static page /50x.html
#
error_page /50x.html;
location = /50x.html {
root html;
} # proxy the PHP scripts to Apache listening on 127.0.0.1:
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#} # deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
} # another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen ;
# listen somename:;
# server_name somename alias another.alias; # location / {
# root html;
# index index.html index.htm;
# }
#} # HTTPS server
#
#server {
# listen ssl;
# server_name localhost; # ssl_certificate cert.pem;
# ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on; # location / {
# root html;
# index index.html index.htm;
# }
#} } stream{
119 upstream dds{
120 least_conn;
121 server 127.0.0.1:18890 weight=1;
122 server 127.0.0.1:17088 weight=1;
123 }
124 server{
125 listen 55055;
126 proxy_pass dds;
127 }
128 }
红颜色部分为新添加部分。
当前负载均衡算法有三类:
1)least_conn: 对于每个请求,nginx plus选择当前连接数最少的server来处理;
2)least_time: 对于每个链接,nginx pluns 通过几点来选择server的;
3)普通的hash算法:nginx plus选择这个server是通过user_defined 关键字,就是IP地址:$remote_addr;
4. 参数说明:
weight:权重
max_conns:最大连接数
max_fails:最大连接失败数
fail_timout:在这个时间段中进行了多少次连接的尝试失败了,那么就认为是不可达了并标记不可达