You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot应用在K8s中无法接收X-Forwarded-For头但Docker运行正常

问题描述

基于Spring Boot 3.5.3(内嵌Tomcat服务器)开发的应用,本地通过docker run运行时,能正常接收X-Forwarded-For请求头;但部署到Kubernetes集群后,直接调用Pod IP或通过kubectl exec进入Pod内部执行curl localhost时,该请求头无法被应用接收(HttpServletRequest#getHeaderNames()结果中不存在此头)。其他自定义请求头可正常接收,未使用Kubernetes Service、Ingress、代理或Sidecar,应用也没有自定义过滤器。

相关代码与操作命令

HeaderController.java代码

package com.example.headerdemo.controller;

import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/headers")
public class HeaderController {

    @GetMapping
    public Map<String, String> getAllHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();

        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                headers.put(headerName, headerValue);
                System.out.printf("Header: %s = %s%n", headerName, headerValue);
            }
        }

        return headers; 
    }
}

Dockerfile内容

# Stage 1: Build the application
FROM maven:3.9.6-eclipse-temurin-17 as builder
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests

# Stage 2: Create a minimal runtime image
FROM eclipse-temurin:17-jdk-alpine
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar

# Expose port
EXPOSE 8080

# Run the Spring Boot app
ENTRYPOINT ["java", "-jar", "app.jar"]

本地Docker运行测试命令

docker run -p 8080:8080 myapp
curl -H "X-Forwarded-For: 1.1.1.1" http://localhost:8080/headers

Kubernetes环境测试命令

kubectl exec -it <my-pod> -- curl -H "X-Forwarded-For: 1.1.1.1" http://localhost:8080/headers

内容的提问来源于stack exchange,提问作者Hoàng Minh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 19:07:13