dockerconsulgo-micro

let docker access consul in docker compose


The docker compose file:

version: '3'

services:
  rs:
    build: .
    ports:
      - "9090:9090"
  consul:
    image: "consul"
    ports:
      - "8500:8500"
    hostname: "abc"

rs is a go micro server app which will access consul and the consul address configured in a file like:

"microservice": {
        "serviceName": "hello",
        "registry": "consul=abc:8500",

However this don't work, the rs report error log:

register error: Put http://abc:8500/v1/agent/service/register: dial tcp: lookup abc on 127.0.0.11:53: no such host

I can access consul ui in host machine by http://127.0.0.1:8500, it works properly.

How to configure the network let rs can access consul?


Solution

  • You have changed hostname of the consul container, however rs service is not aware of this, and it attempts to resolve abc by querying default DNS server which is 127.0.0.11 port 53. You can see this in error message, since this DNS server is unable to resolve abc as it has no information about it.

    The easiest way to solve this, and have it working in docker-compose, on the network created between the services in docker-compose is following:

    version: '3'
    
    services:
      rs:
        build: .
        # image: aline:3.7
        ports:
          - "9090:9090"
        # command: sleep 600
        networks:
          rs-consul:
      consul:
        image: "consul"
        ports:
          - "8500:8500"
        hostname: "abc"
        networks:
          rs-consul:
            aliases:
              - abc
    
    networks:
      rs-consul:
    

    This will create new network rs-consul (check with docker network ls, it will have some prefix, mine had working_directory_name_ as prefix). And on this network the Consul machine has alias abc. Now your rs service should be able to reach Consul service via http://abc:8500/

    I have used commented lines (image:alpine:3.7 and command: sleep 600) instead of build: ., to test the connection, since I don't have your rs service code to use in build:. Once containers are started, I used docker exec -it <conatiner-id> sh to start shell on rs container, then installed curl and was able to retrieve Consul UI page via following command:

    curl http://abc:8500/ui/
    

    Hope this helps.