GitHub Actions运行测试连接localhost:80被拒,如何配置端口映射?
问题根源
- 你的测试类硬编码请求端口为
80,但SpringBoot内置服务默认监听8080端口,且你注入的serverPort变量未被实际使用 - GitHub Actions的Ubuntu runner默认使用普通用户执行任务,普通用户没有权限绑定1024以下的端口,就算你在测试配置里指定
server.port=80,服务也会启动失败 - 当前你的测试直接运行在runner主机环境,没有用到容器,所以不存在「容器端口映射」的需求,只有当服务运行在Docker容器中时才需要做端口映射配置
推荐解决方案(无需特殊权限)
直接修改测试代码,使用你已经注入的serverPort变量构造请求地址,避免硬编码端口,同时可以调整测试注解使用随机端口避免端口冲突:
// 可选:将webEnvironment改为RANDOM_PORT避免端口冲突 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @Slf4j public class CoreDbEventControllerITest { @Value("${server.port}") private int serverPort; private String orderNumber = "DEB-12345"; @Test public void when_get_core_db_event_endpoint_is_called_then_http_response_is_returned_and_http_status_200(){ // 替换硬编码的80为注入的serverPort变量 var endpointUrl = String.format("http://localhost:%s/event/%s", serverPort, orderNumber); log.info("endpointurl : "+ endpointUrl); TestRestTemplate testRestTemplate = new TestRestTemplate(); ResponseEntity<CoreDbEventResponse> response = testRestTemplate.getForEntity(endpointUrl, CoreDbEventResponse.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } }
该方案不需要修改workflow配置,修改测试代码后重新运行即可。
强制使用80端口的解决方案
如果你确实需要服务监听80端口,可以在workflow的单元测试执行步骤前添加授权步骤,给Java程序开放绑定低端口的权限:
- uses: actions/setup-java@v1 with: java-version: 11 # 新增授权步骤 - name: Grant Java permission to bind low ports run: sudo setcap cap_net_bind_service=+ep $(readlink -f $(which java)) - name: Run unit test run: mvn -s ${MAVEN_SETTINGS_FILE} clean test -U -Dspring.profiles.active=test
同时需要确保你的test配置文件中server.port设置为80,和测试代码里硬编码的端口保持一致。
补充:容器场景的端口映射配置
如果你后续调整方案,将SpringBoot服务打包成Docker容器运行测试,启动容器时添加端口映射参数即可:docker run -p 80:8080 你的镜像名
其中80是主机端口,8080是容器内服务监听的端口,按需替换即可。
内容的提问来源于stack exchange,提问作者Vinaya Nayak
相关产品推荐
相关产品推荐

