黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:用 Nginx 把请求分给两个实例

黄同学约 9 分钟读完免费

这一页写一个会报出自己名字的小服务,打成镜像,用 docker compose 起两个实例 a、b,前面放一个 Nginx。你会看到请求在 a、b 之间轮流;把 a 的权重调成 3,看分配的比例变了;停掉 b,看 Nginx 怎样绕开它;还会看到后端从 X-Forwarded-For 里拿到的是谁的 IP。

要先学过:

这一页的东西都放在 ~/hb-cloud/gateway-lab 里,和 ① 动手做的 Nacos、商品服务、订单服务分开,不用启动它们。Nginx 要占用电脑上的 8080 端口,开始前先确认它空着。

第一部分:一个会报名字的小服务

  1. 建目录:

    bash
    mkdir -p ~/hb-cloud/gateway-lab
    cd ~/hb-cloud/gateway-lab

    在 Spring Initializr 建项目:Project 选 Maven,Language 选 Java,Spring Boot 选 4.1.2,Group 填 com.shop,Artifact 填 whoami,Package name 是 com.shop.whoami,Java 选 21,依赖不用选,因为下一步会整个换掉 pom.xml。下载解压,把文件夹放到 ~/hb-cloud/gateway-lab/whoami。

  2. pom.xml 整个换成:

    xml
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>4.1.2</version>
            <relativePath/>
        </parent>
        <groupId>com.shop</groupId>
        <artifactId>whoami</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <properties>
            <java.version>21</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webmvc-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>

    这个服务不用 Nacos,也不用 Spring Cloud,只要 Spring Web。

  3. 在 src/main/java/com/shop/whoami/ 下新建两个文件。接口 GET /whoami 返回四样东西:这个实例的名字、算出来的用户 IP、getRemoteAddr() 拿到的地址、原样的 X-Forwarded-For 头,后面几步就看它们:

    java
    // Who.java
    package com.shop.whoami;
    
    public record Who(String instance, String clientIp, String remoteAddr, String forwardedFor) {}
    java
    // WhoamiController.java
    package com.shop.whoami;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import jakarta.servlet.http.HttpServletRequest;
    
    @RestController
    public class WhoamiController {
    
        @Value("${INSTANCE:local}")
        private String instance;            // 环境变量 INSTANCE 的值,没设时是 local
    
        @GetMapping("/whoami")
        public Who whoami(HttpServletRequest request) {
            String xff = request.getHeader("X-Forwarded-For");
            return new Who(instance, clientIp(request), request.getRemoteAddr(), xff == null ? "" : xff);
        }
    
        // 只有一层自己的 Nginx:X-Forwarded-For 的最后一段是它加的,可以信
        static String clientIp(HttpServletRequest request) {
            String xff = request.getHeader("X-Forwarded-For");
            if (xff == null || xff.isBlank()) {
                return request.getRemoteAddr();
            }
            String[] parts = xff.split(",");
            return parts[parts.length - 1].trim();
        }
    }
  4. 先在本机跑一下,确认接口是好的。在 ~/hb-cloud/gateway-lab/whoami 里:

    bash
    ./mvnw spring-boot:run

    看到 Tomcat started on port 8080 以后,另开一个终端:

    bash
    curl -s 127.0.0.1:8080/whoami; echo
    text
    {"instance":"local","clientIp":"127.0.0.1","remoteAddr":"127.0.0.1","forwardedFor":""}

    没有经过代理,所以 forwardedFor 是空的,clientIp 就是 remoteAddr。回到第一个终端按 Ctrl+C 停掉它,后面 8080 要让给 Nginx。

第二部分:两个实例加一个 Nginx

  1. 打包出 jar:

    bash
    cd ~/hb-cloud/gateway-lab/whoami
    ./mvnw -q package -DskipTests
    ls target/*.jar
    text
    target/whoami-0.0.1-SNAPSHOT.jar

    在 whoami 目录里新建 Dockerfile。jar 已经在电脑上打好了,镜像里只要 JRE 和这个 jar:

    dockerfile
    FROM eclipse-temurin:21.0.13_9-jre-noble
    WORKDIR /app
    COPY target/whoami-0.0.1-SNAPSHOT.jar app.jar
    # 建一个普通用户,不用 root 运行
    RUN useradd --system app
    USER app
    EXPOSE 8080
    CMD ["java", "-jar", "app.jar"]
  2. 回到 ~/hb-cloud/gateway-lab,新建 nginx.conf:

    nginx
    upstream whoami {
        zone whoami 64k;                         # 几个工作进程共用一份轮询的进度
        server app1:8080 max_fails=1 fail_timeout=10s;
        server app2:8080 max_fails=1 fail_timeout=10s;
    }
    
    server {
        listen 80;
    
        location / {
            proxy_pass http://whoami;
            proxy_connect_timeout 1s;            # 1 秒连不上,就换下一台
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    和反向代理和 Nginx里那份比,多了几样。app1、app2 是下一步 compose 里的服务名,同一个 compose 文件里的容器能按服务名互相找到。max_fails=1 fail_timeout=10s 的意思是:转给某台失败 1 次,就在 10 秒里不再往它那里发,这两个值就是 Nginx 的默认值,写出来是为了看清楚。zone 让 Nginx 的几个工作进程共用一份「轮到谁了」的记录,不写的话每个进程各轮各的,你连着发 10 个请求,看到的就不一定是一个 a 一个 b 地交替。

  3. 新建 compose.yaml:

    yaml
    # ~/hb-cloud/gateway-lab/compose.yaml
    services:
      app1:
        build: ./whoami                 # 用 whoami 目录里的 Dockerfile 做镜像
        environment:
          INSTANCE: a
        healthcheck:                    # 8080 端口能连上,就算准备好了
          test: ["CMD", "bash", "-c", "echo > /dev/tcp/127.0.0.1/8080"]
          interval: 2s
          retries: 30
    
      app2:
        build: ./whoami
        environment:
          INSTANCE: b
        healthcheck:
          test: ["CMD", "bash", "-c", "echo > /dev/tcp/127.0.0.1/8080"]
          interval: 2s
          retries: 30
    
      nginx:
        image: nginx:1.30.6
        ports:
          - "8080:80"                   # 电脑上的 8080 接到 Nginx 的 80
        volumes:
          - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
        depends_on:                     # 等两个实例都准备好,再启动 Nginx
          app1:
            condition: service_healthy
          app2:
            condition: service_healthy

    app1、app2 用同一份代码,只有环境变量 INSTANCE 不一样,Spring Boot 把它读进 @Value("${INSTANCE:local}")。它们没有写 ports,电脑上连不到它们,只能经过 Nginx。

    depends_on 加 condition: service_healthy 的意思是:等 app1、app2 都过了 healthcheck,再启动 Nginx。这一步不能省,因为 Spring Boot 启动要几秒,Nginx 先起来的话,最早的几个请求转给还没准备好的实例会失败,按上一步的 max_fails 那个实例就被晾 10 秒,你看到的就全是另一个。healthcheck 里那条命令用 bash 试着连一下 8080 端口,连得上就算准备好了。

  4. 启动:

    bash
    docker compose up -d --build --wait

    第一次要下载 JRE 和 Nginx 的镜像。命令结束时,最后几行里 app1、app2 的状态是 Healthy,大致是这样(不同版本的 docker compose 排版略有不同):

    text
     ✔ Container gateway-lab-app1-1   Healthy
     ✔ Container gateway-lab-app2-1   Healthy

    nginx 那一行写的可能是 Started,也可能是 Running,两种都说明它起来了。

第三部分:轮流、改权重、伪造的头

  1. 请求一次:

    bash
    curl -s localhost:8080/whoami; echo
    text
    {"instance":"a","clientIp":"192.168.65.1","remoteAddr":"172.19.0.4","forwardedFor":"192.168.65.1"}

    几个 IP 以你看到的为准,看的是它们之间的关系:remoteAddr 是 Nginx 容器在 Docker 网络里的地址,反向代理和 Nginx里说过,getRemoteAddr() 拿到的是 Nginx;forwardedFor 是 Nginx 加上的头,clientIp 从它取出来,是 Nginx 看到的你的地址。它不是 127.0.0.1,是因为你的请求先到了 Docker,Docker 再转给 Nginx 容器,所以 Nginx 看到的是 Docker 那一跳的地址,常见的是 172.x.0.1 或 192.168.65.1 这样的内网地址。

  2. 连着请求 10 次,只看 instance:

    bash
    for i in $(seq 10); do curl -s localhost:8080/whoami | grep -o '"instance":"[a-z]*"'; done
    text
    "instance":"a"
    "instance":"b"
    "instance":"a"
    "instance":"b"
    "instance":"a"
    "instance":"b"
    "instance":"a"
    "instance":"b"
    "instance":"a"
    "instance":"b"

    第一个是 a 还是 b 不一定,之后一个隔一个。数一数各几次:

    bash
    for i in $(seq 10); do curl -s localhost:8080/whoami | grep -o '"instance":"[a-z]*"'; done | sort | uniq -c
    text
       5 "instance":"a"
       5 "instance":"b"
  3. 自己带一个假的 X-Forwarded-For:

    bash
    curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/whoami; echo
    text
    {"instance":"b","clientIp":"192.168.65.1","remoteAddr":"172.19.0.4","forwardedFor":"1.2.3.4, 192.168.65.1"}

    Nginx 没有删掉你写的 1.2.3.4,只是在后面接上了它看到的地址。取第一段的话,你说自己是谁,后端就信谁;clientIp 取的是最后一段,所以还是上一步那个地址。

  4. 改权重。把 nginx.conf 里 app1 那一行改成:

    nginx
        server app1:8080 weight=3 max_fails=1 fail_timeout=10s;

    Nginx 不会自己发现配置文件改了,所以重启它,让它重新读一遍配置,再请求 8 次:

    bash
    docker compose restart nginx
    sleep 1                              # 等 Nginx 重新开始监听
    for i in $(seq 8); do curl -s localhost:8080/whoami | grep -o '"instance":"[a-z]*"'; done | sort | uniq -c
    text
       6 "instance":"a"
       2 "instance":"b"

    权重 3:1,8 个请求按 6:2 分。不加 sort | uniq -c 再跑一次,能看到顺序是 a a b a a a b a,b 插在 a 中间,这就是负载均衡算法里的平滑加权轮询。

    看完把 weight=3 删掉,再 docker compose restart nginx 一次,下一步要两台一样。

第四部分:停掉一个实例

  1. 停掉 b,然后请求 10 次,这次只看状态码和每个请求花了多久:

    bash
    docker compose stop app2
    for i in $(seq 10); do curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' localhost:8080/whoami; done
    text
    200 0.006s
    200 1.008s
    200 0.004s
    200 0.003s
    200 0.004s
    200 0.003s
    200 0.004s
    200 0.003s
    200 0.004s
    200 0.003s

    10 个全是 200,其中有一个明显慢一些,最多 1 秒左右(排在第几个不一定,时间也会差一点)。那个请求本来轮到 b,Nginx 去连 b 没连上(最多等 proxy_connect_timeout 的 1 秒),就把它转给了 a;按 max_fails=1 fail_timeout=10s,之后 10 秒里不再试 b,所以后面的请求都很快。过了 10 秒,Nginx 会再拿一个请求去试 b,那个请求又会慢 1 秒。

    再看一眼这些请求是谁回的:

    bash
    for i in $(seq 10); do curl -s localhost:8080/whoami | grep -o '"instance":"[a-z]*"'; done | sort | uniq -c
    text
      10 "instance":"a"

    Nginx 的日志里能看到它连 b 失败的记录:

    bash
    docker compose logs nginx | grep error

    有一行带着 [error] 和 while connecting to upstream,前面写的原因可能是 upstream timed out,也可能是 No route to host,看你的 Docker 怎样处理连一个不存在的地址。

  2. 把 b 开回来。Nginx 只在启动时查一次 app2 的地址,b 重新启动后地址可能变了,所以也重启一下 Nginx:

    bash
    docker compose start app2
    docker compose up -d --wait
    docker compose restart nginx
    sleep 1
    for i in $(seq 10); do curl -s localhost:8080/whoami | grep -o '"instance":"[a-z]*"'; done | sort | uniq -c
    text
       5 "instance":"a"
       5 "instance":"b"

    第二条 up -d --wait 是为了等 app2 重新变成 Healthy。

做完了

做对了的话:第 10 步 a、b 各 5 次;第 11 步的 clientIp 不是你写的 1.2.3.4,也不是 remoteAddr 那个 Nginx 的地址;第 13 步停掉 b 以后 10 个请求全是 200、全是 a。

清理:

bash
cd ~/hb-cloud/gateway-lab
docker compose down
docker image rm gateway-lab-app1 gateway-lab-app2

这个目录后面的页面不再用,想删就 rm -rf ~/hb-cloud/gateway-lab。~/hb-cloud 里 ① 建的 compose.yaml、product-service、order-service 别删,后面还要用。

做不出来时

  • 第 4 步或第 8 步说 8080 端口被占用:Docker 的报错里有 port is already allocated,或者 Spring Boot 报 Port 8080 was already in use。多半是第 4 步的 spring-boot:run 没停,回那个终端按 Ctrl+C;不是的话,lsof -i :8080 看是谁占着(见看进程和端口)。
  • 第 8 步报找不到 whoami-0.0.1-SNAPSHOT.jar:报错里有 not found。第 5 步的 ./mvnw package 没跑,或者跑在了别的目录,ls whoami/target/ 看一眼。
  • 第 8 步一直等,最后说 app1 或 app2 不健康:docker compose logs app1 看 Spring Boot 的启动日志,最后有没有 Tomcat started on port 8080,有报错就照报错改。
  • 请求回 502 Bad Gateway:Nginx 连不上任何一个实例。docker compose ps 看 app1、app2 是不是都在跑;nginx.conf 里的端口是不是 8080。
  • 第 10 步不是一个隔一个:nginx.conf 里漏了 zone 那一行,或者改完没有 docker compose restart nginx。
  • Nginx 起不来,docker compose logs nginx 里有 host not found in upstream "app2:8080":app2 停着的时候重启了 Nginx,Nginx 找不到这个名字就不肯启动。先 docker compose start app2,再重启 Nginx。
  • 第 14 步以后还是全是 a:Nginx 还记着 b 原来的地址。docker compose restart nginx 再试。

做完这一页,② 就结束了。请求进得来以后,下一个问题是进来得太多怎么办:固定窗口和滑动窗口。