Kubernetes service in HostAliases

2/14/2019

Is it possible to have a service name under hostAliases in Kubernetes? I want to point a non-existent domain name to a service instead of an IP.

Something like the following:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: deployment-name
spec:
  replicas: 1
  template:
    spec:
      containers:
        hostAliases:
        - ip: "my-service-name"
          hostnames:
          - "my.domain.com"

If not, how would you guys set up a local hosts file entry for a pod to a service? I need to resolve the non-existent domain to the service.

-- Neekoy
kubernetes

2 Answers

2/14/2019

As @VKR explained in the other comment, HostAliases basically just injects into /etc/hosts which only allows for A-record type entries.

For CNAME entries, a workaround is to inject the alias into CoreDNS.

This can be done by editing the ConfirMap for CoreDNS:

$ kubectl edit configmap coredns -n kube-system

apiVersion: v1
data:
  Corefile: |
    .:53 {
        errors
        health
        rewrite name orderer0.example.com orderer0-example-com.orbix-mvp.svc.cluster.local
        rewrite name peer0.example.com peer0-example-com.orbix-mvp.svc.cluster.local
        kubernetes cluster.local {
          pods insecure
          upstream
          fallthrough in-addr.arpa ip6.arpa
        }
        prometheus :9153
        proxy . /etc/resolv.conf
        cache 30
    }

I've added the two lines that start with rewrite name and once CoreDNS is restarted, the new entries are available throughout the cluster.

CoreDNS can be restarted using the following command:

kubectl exec -n kube-system coredns-980047985-g2748 -- kill -SIGUSR1 1

The above needs to be ran for both of the CoreDNS pods.

-- Neekoy
Source: StackOverflow

2/14/2019

No, you can not use service name instead of ip under spec.template.spec in your Deployment definition. What you can do, is to get your service IP using kubectl get services and use it inside deployment, mapping it to non-existing domain.

The reason why you are not able to use the domain name instead of IP - is that the file /etc/hosts should contain IP and hostnames only. For more information you may want to read this Creating alias to domain name with /etc/hosts topic.

-- VKR
Source: StackOverflow