Docker部署的React应用通过VPC内网IP连接Node.js后端是否可行?
Hey there! Let's break down your question step by step. The short answer is: this connection approach works in specific scenarios, but it's failing for you because of how React apps run in production.
Why curl works from your frontend Docker container
Your frontend and backend containers are both inside the same VPC, so the backend's internal IP is fully routable and resolvable within that private network. When you run curl <backend-internal-ip> from the frontend container, you're making a request directly from one VPC-internal service to another—this is totally valid and expected to work.
Why the React app in the browser throws net::ERR_NAME_NOT_RESOLVED
Here's the key thing you might not realize: React apps run in the user's browser, not inside your frontend Docker container, once they're deployed.
- In production, your React app gets built into static files (HTML, CSS, JS) that are served to the client's browser. The browser runs this code outside your VPC, so it has no way to resolve or reach the backend's internal IP address—internal VPC IPs aren't exposed or routable from outside the private network.
What are your working options?
Here are a few practical solutions to fix this:
- Use a reverse proxy (like Nginx)
Set up an Nginx container (or a cloud load balancer) that's accessible via a public IP/domain. Configure Nginx to forward requests from paths like/apito your backend's internal IP. Your React app can then make requests to relative paths (e.g.,fetch('/api/data')) instead of hardcoding the internal IP. This way, the browser only communicates with the public proxy, which handles routing to the backend inside the VPC. - Enable DNS resolution for internal clients
If your users are accessing the app from within the same VPC (e.g., internal team members on your company network), you can set up VPC-internal DNS to map a friendly name to your backend's IP. Then your React app can use that internal domain instead of the raw IP, and clients inside the VPC will be able to resolve it. - Development mode proxy
If you're still in development, add aproxyfield to your React app'spackage.json:
This tells the React development server to forward API requests to the backend's internal IP. Since the browser communicates with the dev server (which runs inside your VPC or has access to it), the request gets routed correctly.{ "proxy": "http://<backend-internal-ip>:<port>" }
Final takeaway
Using the backend's internal IP works for service-to-service communication (like your frontend container curling the backend), but it won't work for browser-based requests unless the browser is also inside the VPC. For public-facing apps, you need a public entry point (like a proxy or load balancer) to bridge the browser and your internal backend services.
内容的提问来源于stack exchange,提问作者taraf

