React+Spring Boot应用Docker部署时代理请求失败问题求助
Hey there, let's tackle this proxy error you're facing! The root cause here is how localhost works inside Docker containers—let's break it down step by step.
Why the Proxy Fails
When your React app runs inside a Docker container, localhost:8080 points to the React container itself, not the Spring Boot server container. Docker Compose creates an internal network where each service is reachable by its service name (in your case, server). Your current proxy configuration is trying to hit the React container's 8080 port, which isn't running the backend—hence the proxy error.
Step 1: Update the React Proxy Configuration
Modify your proxy.js to target the Docker service name instead of localhost:
export default { dev: { '/api/': { target: 'http://server:8080/', // Use the Docker service name here changeOrigin: true, pathRewrite: { '^': '', }, }, } }
Step 2: Ensure React Listens on All Interfaces
Your React container needs to bind to 0.0.0.0 instead of just localhost so other containers (and your host machine) can reach it. Check your package.json's dev script—make sure it includes the --host flag:
"scripts": { "dev": "your-dev-command --host 0.0.0.0" // Example: "vite --host 0.0.0.0" or "react-scripts start --host 0.0.0.0" }
This ensures the React server inside the container accepts connections from outside the container (including the Docker internal network).
Step 3: Verify Docker Compose Network & Service Setup
- You can remove the
linksfield in yourdocker-compose.yml—Docker Compose v3 automatically puts all services in the same default network, soclientcan reachserverdirectly via the service name. - Double-check that your Spring Boot container is running correctly: run
docker-compose logs serverto confirm it's started and listening on port 8080. - Ensure your Spring Boot app isn't bound to
localhost(default configuration uses0.0.0.0, so this shouldn't be an issue, but you can verify inapplication.propertieswithserver.address=0.0.0.0).
Step 4: Rebuild and Restart Containers
After making these changes, rebuild your images and restart the containers:
docker-compose down docker-compose up --build
This should resolve the proxy connection issue—your React app will now correctly route API requests to the Spring Boot server container via the internal Docker network.
内容的提问来源于stack exchange,提问作者Quangg Duy

