Docker部署Jenkins配Nginx反向代理,重定向丢失端口问题咨询
你遇到的重定向丢失端口问题,核心原因有两个:一是Nginx传递给Jenkins的Host头不包含端口,导致Jenkins生成重定向URL时遗漏了端口;二是Nginx的反向代理路径和Jenkins的上下文路径(prefix)没有正确匹配,加重了这个问题。
具体原因
当你访问http://localhost:8080/jenkins时,Nginx会把请求转发给Jenkins,但你配置的proxy_set_header Host $host;中,Nginx的$host变量会自动去掉请求Host头中的端口(也就是把localhost:8080变成localhost)。Jenkins收到这个不带端口的Host后,生成的重定向URL自然就没有了8080端口,导致跳转到http://localhost/jenkins/。
同时,你的Jenkins配置了--prefix=/jenkins,但Nginx的proxy_pass http://docker-jenkins;会把/jenkins路径直接转发到Jenkins的根路径/,这会导致Jenkins的内部路径和外部暴露的路径不匹配,进一步引发重定向异常。
解决方案
我提供两种可行的调整方案,你可以根据自己的需求选择:
方案一:保留Jenkins的prefix配置,修正Nginx参数
这种方案适合你希望Jenkins内部也使用/jenkins作为上下文路径的场景:
修改Nginx的
nginx.conf:worker_processes 1; events { worker_connections 1024; } http { sendfile on; upstream docker-jenkins { server jenkins:8080; } server { listen 80; location /jenkins/ { # 用$http_host传递包含端口的原始Host头 proxy_set_header Host $http_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-Port 8080; # 转发到Jenkins的/jenkins路径,和prefix匹配 proxy_pass http://docker-jenkins/jenkins/; proxy_redirect off; } } }保持Jenkins的环境变量不变:
environment: - JENKINS_OPTS="--prefix=/jenkins"
方案二:移除Jenkins的prefix,让Nginx处理路径映射
这种方案更简洁,Jenkins运行在默认的根路径,由Nginx负责把外部的/jenkins路径映射到Jenkins的根路径:
修改Jenkins的Docker Compose配置:
去掉JENKINS_OPTS中的--prefix=/jenkins:jenkins: image: jenkins:2.60.3 volumes: - "./storage/jenkins:/var/jenkins_home" # 移除prefix配置,使用默认根路径修改Nginx的
nginx.conf:worker_processes 1; events { worker_connections 1024; } http { sendfile on; upstream docker-jenkins { server jenkins:8080; } server { listen 80; location /jenkins/ { # 传递包含端口的Host头 proxy_set_header Host $http_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-Port 8080; # 将/jenkins/路径转发到Jenkins的根路径/,注意末尾的斜杠 proxy_pass http://docker-jenkins/; # 修正Jenkins返回的重定向URL,替换根路径为/jenkins/ proxy_redirect http://$http_host/ http://$http_host/jenkins/; } } }
验证调整效果
修改完配置后,重启Docker Compose:
docker-compose down && docker-compose up --build -d
然后用curl测试:
curl -v localhost:8080/jenkins
你应该会看到重定向的Location变成http://localhost:8080/jenkins/,登录/登出操作也不会再丢失端口了。
内容的提问来源于stack exchange,提问作者Maksim Sorokin

