nginx反向代理、负载均衡配置

yum安装nginx



实现场景


需要三台服务器:
  1. 192.168.1.100 代理服务器
  2. 192.168.1.101 web服务器
  3. 192.168.1.102 web服务器

要实现nginx代理和负载均衡,只需要在192.168.1.100服务器安装、配置nginx。

配置反向代理


1、配置文件nginx.conf


如果是yum安装的nginx,配置文件位置是
/etc/nginx/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;
    include /etc/nginx/conf.d/*.conf;
}

这是nginx默认配置文件,不需要任何改动。

2、配置文件 conf.d/defalut.conf


进入 /etc/nginx/conf.d/ 目录, 打开default.conf,配置反向代理
server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
        proxy_pass http://192.168.1.101:8080;
    }
 }

     反向代理配置完毕,打开192.168.1.100,访问的是192.168.1.101:8080 服务器

配置 负载均衡


进入 /etc/nginx/conf.d/ 目录,删除default.conf文件,执行命令vim slb.conf,填写如下配置
upstream testserver {
        server 192.168.1.101:8080 weight=1 max_fails=2 fail_timeout=3;
        server 192.168.1.102:8080 weight=1 max_fails=2 fail_timeout=3;
}

server {

        listen 80;
        server_name localhost;

        location / {

                #设置主机头和客户端真实地址,以便服务器获取客户端真实IP
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                #禁用缓存
                proxy_buffering off;

                #反向代理的地址
                proxy_pass http://testserver;
        }
}

重启nginx service nginx restart

最简单的负载均衡配置完毕,因为设置101 和 102 的权重weight=1,所以当访问192.168.1.100时候会轮流访问100和102两个服务器。

总结


反向代理配置:default.conf
负载均衡配置:slb.conf (注意:去掉default.conf,否则代理配置会让slb.conf负载均衡失效)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值