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

如何让Spring Boot应用在指定的其他端口正常运行?

Spring Boot切换端口后curl访问超时的排查与解决

问题背景

运行在CentOS防火墙后的Spring Boot 2.5.3应用,8767端口可正常通过HTTPS访问,但切换到其他端口(如8768、9000)时:

  • 应用日志显示已监听目标端口
  • netstat能查到端口处于监听状态
  • 已通过firewall-cmd开放对应端口
  • 但curl访问超时,仅8767端口可用

应用构建运行步骤:

  1. 构建命令:mvn clean package spring-boot:repackage
  2. 启动命令:java -jar target/service.jar --spring.config.location=/path/to/config.properties
  3. 访问命令:curl --key /a/b --cert /x/y "https://server-name:8767/path?arg=..."

核心依赖配置:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
</parent>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

排查与解决步骤

1. 确认防火墙规则的有效性与持久化

CentOS的firewalld规则分临时和持久化两种,若仅添加临时规则,重启后会丢失:

  • 检查当前生效的端口规则:
    firewall-cmd --list-ports --zone=public
    
    确认目标端口(如8768/tcp)在输出列表中
  • 检查持久化规则:
    firewall-cmd --list-ports --zone=public --permanent
    
    若目标端口不在其中,添加并重载规则:
    firewall-cmd --add-port=xxxx/tcp --zone=public --permanent
    firewall-cmd --reload
    

    注意:HTTPS基于TCP协议,必须指定/tcp

2. 检查端口监听的IP地址

若应用仅监听127.0.0.1,则外部无法访问:

  • 查看端口监听详情:
    ss -tulpn | grep xxxx
    
    输出中若LISTEN对应的地址是127.0.0.1:xxxx,而非0.0.0.0:xxxx,需修改应用配置:
    • 在application.properties中添加:server.address=0.0.0.0
    • 或启动时通过CLI传递:java -jar target/service.jar --server.address=0.0.0.0 --server.port=xxxx

3. 排查SELinux限制

CentOS默认开启SELinux,会限制非标准端口的网络请求:

  • 临时关闭SELinux测试:
    setenforce 0
    
    若此时curl能正常访问,说明是SELinux的问题
  • 永久允许目标端口(将xxxx替换为你的端口):
    semanage port -a -t http_port_t -p tcp xxxx
    

    该命令将端口添加到SELinux允许的HTTP服务端口列表中,适配Spring Boot Web应用的网络访问

4. 验证curl请求参数与本地访问

  • 确保curl命令中的端口已修改为目标端口,例如:
    curl --key /a/b --cert /x/y "https://server-name:xxxx/path?arg=..."
    
  • 在虚拟机本地执行curl访问localhost:
    curl --key /a/b --cert /x/y "https://localhost:xxxx/path?arg=..."
    
    若本地能通但外部不行,需排查虚拟机所在网络的路由、NAT规则

5. 确认应用SSL配置无端口绑定

检查application.properties中的server.ssl相关配置,确保没有硬编码端口的情况(Spring Boot 2.5中server.ssl.port已废弃,统一使用server.port),同时查看启动日志,确认Server initialized with port: xxxx中的端口与预期一致。


内容的提问来源于stack exchange,提问作者chocalaca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:06:18