• 前言

 nginx作为负载均衡器的简单配置,只为干货!不做说明。

  • 参考资料

http://nginx.org/en/docs/http/ngx_http_upstream_module.html

  • 配置文件

[root@mysql conf]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
upstream backend {
    server 192.168.1.198:80       max_fails=3 fail_timeout=30s;
    server 192.168.1.197:80       max_fails=3 fail_timeout=30s;
}
    server {
        listen       80;
        server_name  chborg.com;
        index  index.html index.htm;
        location / {
        proxy_pass http://backend;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
  • 语法格式

Syntax: upstream name {......}
Default: --
Context: http
  • 例子

upstream backend {
    server backend1.example.com       weight=5;
    server backend2.example.com:8080;
    server unix:/tmp/backend3;

    server backup1.example.com:8080   backup;
    server backup2.example.com:8080   backup;
}

server {
    location / {
        proxy_pass http://backend;
    }
}
  • 解决session会话的问题

upstream backend {
    ip_hash;
    server 192.168.1.198:80       max_fails=3 fail_timeout=30s;
    server 192.168.1.197:80       max_fails=3 fail_timeout=30s;
}

  插入 ip_hash 会使得连接始终保持在一个ip地址上,刷新不切换服务器。

  缺点:造成流量分配不均!!