skip to Main Content

So, I have this project for my university which uses a react app for frontend, an express app for backend, and mongodb as a database. Before putting it in docker containers, I would launch the express app and the react app separately, and everything would work just fine. Now we are tasked to put it all in docker containers. After some time (and chatGPT, forgive me for that), I ended up with this docker-compose file:

version: '3'

services:
  mongo:
    image: mongo
    container_name: mongo
    ports:
      - "27017:27017"

  backend:
    build: ./backend
    container_name: backend
    ports:
      - "5000:5000"

  frontend:
    build: ./finallylist
    container_name: frontend
    ports:
      - "3000:3000"

I did change the links to connect to those things from localhost ones to the ones used here. Now, this composes without any issues, and it even outputs in console "Connection to the database has been successful" (which I put in my express app to, well, indicate that) at some point. Also, the react app seems to compose too, and I am able to open it in browser (and it does load some of the first frontend properly), but then, a second later (it is supposed to make requests to the express app when it loads), it outputs a really long "Failed to fetch" error.

Note, that getList is a function that does connect to the express app from frontend. It is called when the app is loaded.

This error only appears when the thing is dockerized. If I run the app manually, as I did before, it won’t output this error even if the express app or/and the database aren’t active.

How do I fix that?

I honestly have no idea what should I try here.

2

Answers


  1. Chosen as BEST ANSWER

    Okay guys, I found what was the issue. It potentially was because of 2 issues: I didn't create a network to connect between those 2 app and I used a link, made in the docker-compose file. For some reason, when I changed the link react used to connect to express from http://backend:5000 to http://localhost:5000, it worked just fine.


  2. backend is a name/alias used inside of Docker to which Docker assigns internal network container IP addresses – that is why it does not work for you when you try to reach your backend from React. When you map ports all of them are mapped agains localhost. Mongo will also be at localhost:27017 from the outside but internally in the Docker network it will be mongo:27017. mongo as being in internal network can communicate by backend, but React communicates from the outside, from your browser and needs localhost.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search