nginx负载均衡配置

一、业务需求

使用IDEA启动两个后端服务,主服务监听3000端口、备用服务监听4000端口。

当主服务正常运行,使用主服务,主服务掉线后自动切换到备用服务。

Snipaste_2025-11-20_18-02-43

前端项目使用npm run dev打包dist文件存放在nginx/html目录下:

image

二、nginx配置

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

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  0;
    keepalive_timeout  65;
    #gzip  on;
    # 定义上游服务器组
    upstream api_backend {
        server localhost:3000 weight=100000 max_fails=2 fail_timeout=5s;
        server localhost:4000 weight=1 max_fails=2 fail_timeout=5s;
    }
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        # API接口代理配置
        location /api/ {
             # 移除 /api 前缀
            rewrite ^/api/(.*)$ /$1 break;
            # 代理到上游服务器组
            proxy_pass http://api_backend;
            # 重要:设置代理头信息
            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_set_header X-Forwarded-Proto $scheme;
           # 超时配置(触发故障切换的关键:连接/读取超时视为失败)
            proxy_connect_timeout 3s;  # 3 秒内连接不上主服务,视为失败
            proxy_read_timeout 5s;     # 连接后 5 秒内没收到响应,视为失败
            proxy_send_timeout 5s;
            # 触发故障切换的条件:遇到以下情况,自动切换到备服务
            proxy_next_upstream error timeout invalid_header 
                                 http_500 http_502 http_503 http_504;
            # 可选:限制重试次数(避免无限重试)
            proxy_next_upstream_tries 2;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

三、演示效果

主服务正常,访问打到3000端口。

image

 关闭3000端口服务,自动连接4000端口。

image

 

posted @ 2025-11-20 18:45  温布利往事  阅读(6)  评论(0)    收藏  举报