4

My application communicates to some services via hostnames. When running my application as a docker container i used to add hostnames to the /etc/hosts of the hostmachine and run the container using --net=host.

Now I'm running my containers in kubernetes cluster. I would like to know how can i add the /etc/hosts entries to the pod via yaml.

I'm using kubernetes v1.5.3.

Karthik
  • 929
  • 2
  • 12
  • 24

4 Answers4

12

From k8s 1.7 you can add hostAliases. Example from the docs:

apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "foo.local"
    - "bar.local"
  - ip: "10.1.2.3"
    hostnames:
    - "foo.remote"
    - "bar.remote"
isalgueiro
  • 1,973
  • 16
  • 20
1

Host files are going to give you problems, but if you really need to, you could use a configmap.

Add a configmap like so

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-app-hosts-file-configmap
data:
  hosts: |-
    192.168.0.1 gateway
    127.0.0.1 localhost

Then mount that inside your pod, like so:

  volumeMounts:
    - name: my-app-hosts-file
      mountPath: /etc/
volumes:
  - name: my-app-hosts-file
    configMap:
    name: my-app-hosts-file-configmap
jaxxstorm
  • 12,422
  • 5
  • 57
  • 67
1

This works and also looks simpler:

kind: Service
apiVersion: v1 
metadata:
    name: {HOST_NAME} 
    spec:
      ports:
        - protocol: TCP
          port: {PORT}
          targetPort: {PORT}
      type: ExternalName
      externalName: {EXTERNAL_IP}

Now you can use the HOST_NAME from the pod directly to access the external machine.

J.W.F.
  • 641
  • 2
  • 12
  • 24
Karthik
  • 929
  • 2
  • 12
  • 24
  • Alas, this wouldn't let you to add a FQDN: `Invalid value: "example.com": a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character (e.g. 'my-name', or 'abc-123', regex used for validation is '[a-z]([-a-z0-9]*[a-z0-9])?')` – beatcracker May 18 '18 at 11:50
  • 1
    @beatcracker For this, you can use HostAliases to solve the problem. https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/ – daemonsl Jun 27 '18 at 16:37
  • @sunnykrgupta I'm using terraform and its k8s provider doesn't support `HostAliases` yet. I was hoping to achieve it via this hack, but alas... – beatcracker Jun 27 '18 at 20:38
0

Another approach could be to use postStart hook on the pod lifecycle as below:

lifecycle:
      postStart:
        exec:
         command: ["/bin/sh", "-c", "echo '192.168.1.10 weblogic-jms1.apizone.io' >> /etc/hosts; echo '192.168.1.20

weblogic-jms2.apizone.io' >> /etc/hosts; echo '192.168.1.30 weblogic-jms3.apizone.io' >> /etc/hosts; echo '192.168.1.40 weblogic-jms4.apizone.io' >> /etc/hosts"]

Shoaib Khan
  • 899
  • 14
  • 26