简体   繁体   中英

Access host machine dns from a docker container

/I'm using docker beta on a mac an have some services set up in service-a/docker-compose.yml :

version: '2'
services:
  service-a:
    # ...
    ports:
      - '4000:80'

I then set up the following in /etc/hosts :

::1  service-a.here
127.0.0.1 service-a.here

and I've got an nginx server running that proxies service-a.here to localhost:4000 . So on my mac I can just run: curl http://service-a.here . This all works nicely.

Now, I'm building another service, service-b/docker-compose.yml :

version: '2'
services:
  service-b:
    # ...
    ports:
      - '4001:80'
    environment:
      SERVICE_A_URL: service-a.here

service-b needs service-a for a couple of things:

  1. It needs to redirect the user in the browser to the $SERVICE_A_URL
  2. It needs to perform HTTP requests to service-a , also using the $SERVICE_A_URL

With this setup, only the redirection (1.) works. HTTP requests (2.) do not work because the service-b container has no notion of service-a.here in it's DNS.

I tried adding service-a.here using the add_hosts configuration variable, but I'm not sore what to set it to. localhost will not work of course.

Note that I really want to keep the docker-compose files separate (joining them would not fix my problem by the way) because they both already have a lot of services running inside of them.

Is there a way to have access to the DNS resolving on localhost from inside a docker container, so that for instance curl service-a.here will work from inside a container?

You can use 'link' instruction in your docker-compose.yml file to automatically resolve the address from your container service-b.

service-b:
    image: blabla
    links:
       - service-a:service-a
service-a:
    image: blablabla

You will now have a line in the /etc/hosts of you service-b saying:

service-a 172.17.0.X

And note that service-a will be created before service-b while composing your app. I'm not sure how you can after that specify a special IP but Docker's documentation is pretty well done. Hope that's what you were looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM