Windows宿主机请求Docker容器中Spring API无响应问题求助
Alright, let's figure out why your containerized Spring API isn't responding when you hit it from your host machine. The main issue here is a port mismatch in your Docker Compose setup, and it's an easy fix!
1. The Port Mapping Mistake
Look at your docker-compose.yml for the api service:
ports: - "8080:80"
This line tells Docker to map your host's port 8080 to the container's port 80. But here's the problem: your Spring Boot application is defaulting to listening on port 8080 inside the container (since you haven't changed the server port via application.properties or startup arguments).
So when you send a request to http://localhost:8080/api/task/ from your host, it's trying to connect to port 80 in the container—where nothing is running. That's why you get the "Server returned nothing" error.
Fix It
Update the ports section to map host port 8080 to container port 8080:
ports: - "8080:8080"
2. Verify the Fix (and Debug Further if Needed)
After updating the config, stop and restart your containers with:
docker-compose down && docker-compose up --build
Then:
- Test the endpoint again at
http://localhost:8080/api/task/—it should work now. - If it still doesn't respond, check if your Spring app actually started properly in the container. Run this command to view the logs:
Look for a line likedocker logs <your-api-container-name>Started SpringApiApplication in X seconds (JVM running for Y)—that confirms the app is up. If you see database connection errors, you might need to adjust yourSPRING_DATASOURCE_URLor wait a few seconds for MySQL to fully initialize (sincedepends_ononly waits for the container to start, not the database service). - You can also check which ports the app is listening on inside the container. Exec into the container:
Then installdocker exec -it <your-api-container-name> shnet-tools(if missing) and check listening ports:
You should seeapt update && apt install net-tools netstat -tulpnjavalistening on port 8080.
3. Bonus: Optional Port Configuration
If you want your app to run on port 80 inside the container (to match your original mapping), you can modify your Spring Boot setup:
- Add
server.port=80to yourapplication.propertiesfile, or - Update the entrypoint in your Dockerfile to pass the port as an argument:
Either way, keep theENTRYPOINT ["java", "-jar", "-Dserver.port=80", "spring-api-0.0.1-SNAPSHOT.jar"]ports: - "8080:80"mapping in your Compose file.
内容的提问来源于stack exchange,提问作者Tiago Martinho

