How to Fix ERR_NAME_NOT_RESOLVED When Dockerized Frontend Calls Backend

0
0
Asked By CreativeCoder42 On

I'm working with a Docker setup that has three containers: one for Vite (the frontend), one for Node (the backend), and one for MongoDB. When my frontend attempts to make a GET request to the backend at `http://mern-backend:4531/api/workouts`, I encounter the error `net::ERR_NAME_NOT_RESOLVED`. However, when I use `wget http://mern-backend:4531/api/workouts` from within the CLI of the frontend container, it works perfectly and returns the JSON response as expected. I'm using the following fetch function in my Vite code:

```javascript
async function fetchWorkouts () {
const response = await fetch(`http://mern-backend:4531/api/workouts`);
const json = await response.json();
if (response.ok) {
setWorkouts(json);
}
}
```

Also, for context, the backend connects to the MongoDB database fine with this line:
`mongoose.connect("mongodb://testuser:testpassword@mern-database:27017")`.

Here's my `compose.yaml` for reference:

```yaml
services:
frontend:
container_name: mern-frontend
build:
context: ./frontend
dockerfile: dockerfile
target: runner
env_file:
- ./frontend/.env.prod
ports:
- 8080:8080
backend:
container_name: mern-backend
build:
context: ./backend
dockerfile: dockerfile
target: runner
env_file:
- ./backend/.env.prod
ports:
- "4531:4531"
mongodb:
image: mongo:8.0.20
container_name: mern-database
ports:
- "27017:27017"
env_file:
- ./mongodb/.env
volumes:
- mongodb-data:/data/db
volumes:
mongodb-data:
```

Any guidance on why this ERR_NAME_NOT_RESOLVED error is happening on the frontend would be greatly appreciated!

1 Answer

Answered By DockerDude89 On

Hey there! It sounds like you're trying to access the backend directly from your browser, right? The `mern-backend` name is only recognized within the Docker network, not from the browser. Here are a few options to consider:
1. Set up a reverse proxy that exposes your backend at a specific path, like `/api`, then you can fetch it via `http://localhost/api/workouts`.
2. Make the frontend container act as a reverse proxy during development.
3. Just expose the backend's port (4531) to your local network, so from your browser you'd use `http://localhost:4531/api/workouts`.
Hope this gets you started!

HelpfulHannah3 -

Thanks for the explanation! I tried the localhost method and it's working great now. I hadn't thought of that before, so really appreciate your help!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.