Frontend docker container getting connection refused from backend container

Advertisements

Im trying to learn how to write a docker-compose file, and im trying to use it deploy a fullstack application(backend and frontend written with java. using mysql docker image for database).
My backend can communicate with mysql container no problem, but the frontend fails to contact the endpoint exposed by my backend. I get the following error:

2024-05-08 17:04:23 2024-05-08T15:04:23.710Z ERROR 1 --- [Frontend] [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://backend:1337/api/person": Connection refused] with root cause

My docker-compose.yaml is as following:

version: '1'
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: mysecret
    restart: always
    container_name: mysql-container
    volumes:
      - mysql-db:/var/lib/mysql
    ports:
      - 3306:3306
  backend:
    build: ./Backend/
    ports:
      - 1337:8080
    container_name: backend-container
    depends_on:
      - mysql
  frontend:
    build: ./Frontend/
    ports:
      - 1338:8080
    container_name: frontend-container
    depends_on:
      - backend
volumes:
  mysql-db:
    driver: local

```

If you need any more information please let me know. Thanks

>Solution :

If your backend container publishes port 8080 then this should be the port that your frontend connects to i.e. http://backend:8080/api/person

The ports syntax binds container ports e.g. 8080 to the host (running Docker) ports e.g. 1337. This enables you to connect to e.g. backend from the host using port 1337 but from within the Compose, your containers use a shared network and the container ports must be used.

The e.g. 1337:8080 maps {host-port}:{container-port} and so you’re exposing the backend on 8080 to the host as port 1337

The same port (e.g. 8080) doesn’t conflict within the shared network because Docker uses the service name frontend and backend as the DNS names and so they are distinct backend:8080 and frontend:8080 within the shared network.

Leave a ReplyCancel reply