nginx负载均衡的配置

作者:谢高升 发布:2019-01-16 浏览:2260次

记录一下nginx配置负载均衡和Keepalived高可用的nginx双机热备

下面准备4台测试虚拟机192.168.44.131-134;四台机器环境是相同的

nginx/1.14.0     PHP 7.2.11


44.131的服务器作为主的转发来使用nginx.conf配置如下

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;#添加的内容
    upstream mynginx{
      server 192.168.44.132:8082; #nginx转发
      server 192.168.44.133:8082; #nginx转发
      server 192.168.44.134:8082;
    } 
    include /etc/nginx/conf.d/*.conf;
}


添加一个配置端口是8082

server {
    listen       8082;
    server_name  localhost;
    root /var/www/html;
    index index.html index.htm index.php;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    #转发
    location / {
     proxy_pass  http://mynginx;
    }
    }

到此44.131配置完成;重启一下nginx;下面配置剩下的3台如下

server {
    listen       8082;
    server_name  localhost;
    root /var/www/html;
    index index.html index.htm index.php;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ \.php$ {
        root           /var/www/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

}

为了区分新建一个test.php内容分别输出这是192.168.44.132-134;效果如图

image.png

image.png

image.png

如果132-134有一个宕掉不会影响总体的服务


统计日志访问数量

cat xx.log |grep 'GET /action'|cut -d ' ' -f4|uniq -c|sort -n -r