magnoz
magnoz

Reputation: 1995

How to make REST calls between Frontend and Backend using Docker containers

I have 3 docker containers:

Backend (Spring boot rest api) Frontend (Js and html in the apache image) Mongodb

I'm orchestrating them through docker-compose and works nicely.

However I don't know how to let my frontend javascript client know the backend container's host/ip in order to reach it.

This is my docker-compose.yml:

version: '3.1'

services:
  project-server:
    build: .
    restart: always
    container_name: project-server
    ports:
      - 8200:8200
    working_dir: /opt/app
    depends_on:
      - mongo

  httpd:
    image: project-ui
    container_name: project-ui
    ports:
      - 8201:80


  mongo:
    image: project-mongo
    container_name: project-mongo
    ports:
      - 27018:27017
    volumes:
      - $HOME/data/mongo-data:/data/db
      - $HOME/data/mongo-bkp:/data/bkp
    restart: always

So i've tried with this in my js client app:

export default {
  REMOTE_HOST: 'http://project-server:8200'
}

But it doesn't work. (Failed to load resource: net::ERR_NAME_NOT_RESOLVED)

And i'm pretty sure it's because JS runs locally on the browser so it has no way to resolve that.

What's the right way to do this? There is any way for the frontend service (apache) to pass/render the real host to Javascript and get it somehow?

Thanks a lot

Upvotes: 2

Views: 1698

Answers (1)

b0gusb
b0gusb

Reputation: 4721

project-server can be resolved only within the network created by docker-compose. As you mentioned, to connect from the outside world you need to export the IP of your host instead of project-server. The problem is the guest container doesn't know the IP of the guest. Here is a detailed discussion about that: How to get the IP address of the docker host from inside a docker container

What you probably need in your situation is to run the container passing the IP of the host as an environment variable:

run --env <IP>=<value>

Then in node you can just read that variable. Hope it helps

Upvotes: 1

Related Questions