Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Frontend docker container getting connection refused from backend container

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading