How to set up API requests between Docker containers: React frontend and FastAPI backend?

I’m struggling with API requests between my Docker containers. I’ve got a React frontend and a FastAPI backend, both running in separate containers on the same network. My docker-compose file defines the services, but I’m confused about which URL to use for making requests.

When I try using http://backend/ in my React code, I encounter a CORS error. Surprisingly, switching to http://localhost:8000/ resolves the issue. I was under the impression that Docker containers, behaving like isolated machines, should only communicate via their service names.

Here’s a simplified version of my React code:

const URL = 'http://localhost:8000/' // works, but why?
try {
  const response = await fetch(URL);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error('Request failed');
}

My FastAPI setup includes CORS middleware configured with allowed origins. Is there something I need to modify in my Vite config to enable service name-based requests? Any insights would be appreciated!

hey there! its actually normal to use localhost in ur react code even with docker. the browser runs outside the container, so it talks to the host machine first. if u wanna use service names, you’d need a reverse proxy in ur docker setup. for now, stick with localhost:8000 and make sure ur CORS settings in fastapi allow it. hope that helps!

The issue you’re encountering is quite common when dealing with Docker containers and frontend applications. The key here is understanding the difference between how Docker’s internal networking works and how your browser interacts with the containers.

When you use ‘http://localhost:8000/’ in your React code, it works because your browser is making requests to the host machine, which then forwards them to the Docker container. This is possible because you’ve likely mapped the container’s port to the host in your docker-compose file.

To use the service name (‘backend’) for requests, you’d need to set up a reverse proxy within your Docker network. This proxy would handle requests from your React app and forward them to the appropriate container.

For now, stick with ‘http://localhost:8000/’ in your React code. Ensure your FastAPI CORS settings include this origin. If you want to use environment-specific URLs, consider using environment variables in your React app to switch between development and production URLs.

hey there! browser runs outside docker so it needs host access, thats why ‘localhost:8000’ works. maybe try using env vars in react to switch urls. what other setups have u tried?