AspiringMat
AspiringMat

Reputation: 2269

Docker-compose doesn't resolve DNS to correct service

I have two services, web and helloworld. The following is my docker-compose YAML file:

version: "3"

services:
  helloworld:
    build: ./hello
    volumes:
      - ./hello:/usr/src/app
    ports:
      - 5001:80
  web:
    build: ./web
    volumes:
      - ./web:/usr/share/nginx/html
    ports:
      - 5000:80
    depends_on:
      - helloworld

Inside the index.html in web, I made a button that opens http://helloworld when clicked on. However, my button ends up going to helloworld.com instead of the correct service. Both services work fine when I do localhost:5001 and localhost:5000. Am I missing something?

Upvotes: 1

Views: 951

Answers (1)

BMitch
BMitch

Reputation: 263637

Docker's embedded DNS for service discovery is for container-to-container networking. For connections from outside of docker (e.g. from your browser) you need to publish the port (e.g. 5000 and 5001 in your file) and connect to that published port.

To use the container-to-container networking, you would need the DNS lookup to happen inside of the web container and the connection to go from web to helloworld, instead of from your browser to the container.


Edit: from your comment, you may find a reverse proxy helpful. Traefik and nginx-proxy are two examples out there. You can configure these to forward to containers by hostname or by a virtual path, and in your situation, I think path based routing would be easier. The resulting compose file would look something like:

version: "3"

services:
  traefik:
    image: traefik
    command: --docker --docker.watch
    volumes:
      - /var/lib/docker.sock:/var/lib/docker.sock
    ports:
      - 8080:80

  helloworld:
    build: ./hello
    volumes:
      - ./hello:/usr/src/app
    labels:
      - traefik.frontend.rule=PathPrefixStrip:/helloworld
      - traefik.port=80

  web:
    build: ./web
    volumes:
      - ./web:/usr/share/nginx/html
    labels:
      - traefik.frontend.rule=PathPrefixStrip:/
      - traefik.port=80

The above is all untested off the top of my head configuration, but should get you in the right direction. With the PathPrefixStrip rule, you can make a link in web to "/helloworld" which will go to the other container. And since the link doesn't have a hostname or port, it will go to the same traefik hostname/port you are already using.

Upvotes: 4

Related Questions