Search code examples
kubernetesservice

From kubernetes cluster how to have access to external service with host file?


We need to connect to nginx-test.dup.com on port 80 from our kubernetes cluster.

We are using ExternalName but nginx-test.dup.com is only defined in /etc/hosts.

Is there a way to make that service available from within kubernetes cluster? We also tried adding hostNetwork: true as described in How do I access external hosts from within my cluster? and we got the following error:

error validating data: ValidationError(Service.spec): unknown field "hostNetwork" in io.k8s.api.core.v1.ServiceSpec

 kind: Service
    apiVersion: v1
    metadata:
     name: nginx-test
    spec:
      ports:
      - name: test-https
        port: 8080
        targetPort: 80
      type: ExternalName
      externalName: nginx-test.dup.com

Solution

  • CoreDNS doesn't take /etc/hosts into account. You can add the hosts section to the configMap of the CoreDNS manually.

    # kubectl edit cm coredns -n kube-system
    
    apiVersion: v1
    data:
      Corefile: |
        .:53 {
            errors
            health {
               lameduck 5s
            }
            ready
            # Add the hosts section from here
            hosts {
               xxx.xxx.xxx.xxx nginx-test.dup.com
               fallthrough
            }
            # to here
            kubernetes cluster.local in-addr.arpa ip6.arpa {
               pods insecure
               fallthrough in-addr.arpa ip6.arpa
               ttl 30
            }
            ...
        }
    

    Please note that it will take some time for the new setting to be used.