wbq813 Record Space

One who wants to wear the crown bear the crown.

ToC
Nginx 常用配置
/  

Nginx 常用配置 Updated!

最好的资料是官网 https://nginx.org/en/docs/http/load_balancing.html,以下内容只是自己翻译整理,并结合自己的使用。

负载均衡配置

  1. 3种负载均衡方式
    • round-robin 默认,循环;
    • least-connected 下一个请求被分配给连接数量最少的worker,适用于有些请求完成时间较长的情况;
    • ip-hash 来自同一ip的请求分配到同一个worker;
    	http {
    	    upstream myapp1 {
    		# least_conn;
    		# ip_hash;
    	        server srv1.example.com;
    	        server srv2.example.com;
    	        server srv3.example.com;
    	    }
    	    server {
    	        listen 80;
    	        location / {
    	            proxy_pass http://myapp1;
    	        }
    	    }
    	}
    
  2. 带权重的负载均衡
    	upstream myapp1 {
    	    server srv1.example.com weight=3;
    	    server srv2.example.com;
    	    server srv3.example.com;
    	}
    

    这样的配置,假设有5个请求,3个转发给srv1,1个转发给srv2,1个转发给srv3.

  3. keepalive
    减少nginx于后端服务器之间的频繁连接,能够提高性能。
    	upstream http_backend {
    	    server 127.0.0.1:8080;
    	    keepalive 16;
    	}
    
    	server {
    	    ...
    	    location /http/ {
    	        proxy_pass http://http_backend;
    	        proxy_http_version 1.1;
    	        proxy_set_header Connection "";
    	        ...
    	    }
    	}
    

    这里需要设置proxy_http_version 为1.1,并且设置Connection;此外HTTP/1.0 可以通过传递Connection: Keep-Alive”这个头给upstream来实现长连接(不推荐)。


Title: Nginx 常用配置
Author: wbq813
Traget: http://codeyourlife.cn/articles/2019/10/08/1570525629210.html

Comment