Docker Community Forums

Share and learn in the Docker community.

Calling API from server side requires service name as API host, but on client it's unaccessible

I’m setting up Laravel API and Nuxt front end with docker-compose. I have in two seperate projects (and two docker-compose.yml) and I connect them through network. The problem is that when I make some call to API on Nuxt’s server side, API hostname is Laravel’s service, but on client side the service is unaccessible.

API is mapped from port 80 in container to 8080 on my host. On client side, I can access API by calling http://localhost:8080/api/ but I also do some calls on Nuxt server side, which does not have access to host from container, so it has to call API on http://app-dev/api

#backend.yml
version: '3.5'
services:
  database:
    image: mariadb:10.3
    networks:
    - my-network
    #...

  app-dev:
    depends_on:
      - "database"
    ports:
    - 8080:80
    networks:
    - my-network
    #...

networks:
  my-network:
    name: my-network
#------------------------
#frontend.yml
version: '3.5'
services:
  front-app-dev:
    ports:
      - ${FRONTEND_SERVER_PORT}:${FRONTEND_SERVER_PORT}
    networks:
      - my-network
    #...

networks:
  my-network:
    external: true

How can I unify calling API from server side and client side? Is there some way to make host’s port 8080 accessible in front-app-dev, so server side can make calls there?

My Docker version is 18.06.1-ce, OS Ubuntu 19, but solution has to work also on Windows and MacOS.

I managed to do this with traefik. I added service:

traefik:
  image: traefik:alpine
  ports:
    - 8000:80
  volumes:
    - ./docker/traefik:/etc/traefik
    - /var/run/docker.sock:/var/run/docker.sock
  networks:
    - my-network
  restart: always

My ./docker/traefik.toml:

defaultEntryPoints = ["http"]

[entryPoints]
  [entryPoints.http]
    address = ":80"

[docker]
watch = true
endpoint = "unix:///var/run/docker.sock"
exposedByDefault = false
debug = true

I changed app-dev container, so apache serves API on port 8000. In compose, I added following lines to app-dev:

labels:
  - "traefik.enable=true"
  - "traefik.docker.network=my-network"
  - "traefik.port=8000"
  - "traefik.frontend.rule=Host:app-dev"

I also added app-dev to /etc/hosts, it points to 127.0.0.1. So when I enter app-dev:8000 in my browser (or when client calls it), traefik redirects me to port 8000 in app-dev container. When I call API on server, it also calls app-dev:8000 and it points directly to container as it did before. So both client and server use the same address.