MirrorYuChen
MirrorYuChen
Published on 2025-07-07 / 6 Visits
0
0

Nginx反向代理将服务分发到不同端口学习笔记

Nginx反向代理将服务分发到不同端口

1.起因

​ 服务部署了多个实例,绑定了不同端口,需要提供一个统一的访问接口,然后让用户请求访问。考虑用nginx来做反向代理,使用轮询的方式将访问9000端口的请求给代理到8081,8082,8083和8084上。

2.nginx安装

# 1.更新包
>> sudo apt update
# 2.安装nginx
>> sudo apt install nginx -y
# 3.验证安装
>> nginx -v
nginx version: nginx/1.18.0 (Ubuntu)

3.增加反向代理配置

  • (1) 创建或编辑配置文件:
>> sudo vim /etc/nginx/conf.d/load-balancer.conf
  • (2) 将下面内容贴入:
# 定义后端服务器组(负载均衡池)
upstream backend_servers {
    # 默认使用轮询策略
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
    server 127.0.0.1:8083;
    server 127.0.0.1:8084;
}

server {
    listen 0.0.0.0:9000;
    server_name _;

    # 代理所有根路径请求到后端服务器组
    location / {
        proxy_pass http://backend_servers;
      
        # 标准代理头部设置
        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 5s;
        proxy_read_timeout 60s;
        proxy_send_timeout 60s;
      
        # 启用keepalive连接
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }

    # 可选:健康检查端点
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

4.配置生效

# 1.检查配置用法
>> sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 2.重新加载配置
>> sudo systemctl reload nginx

Comment