In kubernetes how to access a service using dns names?

3/19/2020

How do i provide a service with a dns name in the deployment file so that i can access that service from some other service from the same cluster?

apiVersion: apps/v1
kind: Deployment

metadata:
  name: db
spec:
  selector:
    matchLabels:
      app: db
  replicas: 1
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
      - name: db
        image: mysql:5.7.29
        env:
        - name: MYSQL_ROOT_PASSWORD
          value: "root"
        volumeMounts:
        - mountPath: /var/log/mysql/
          name: mysql
      volumes:
      - name: mysql
        hostPath:
          path: "/home/sandeep/logs/mysql/"
---
apiVersion: v1
kind: Service
metadata:
  name: database
  labels:
    app: db
spec:
  selector:
    app: db
  type: ClusterIP
  ports:
  - name: database
    port: 3306
    targetPort: 3306

This is mysql deployment file so how can i provide this service with a dns name? In which do i need to make change?

-- sandeep P
kubernetes

2 Answers

3/19/2020

The DNS is based on the service name and namespace. In most cases you just use the service name but the full name would be database.default.svc.cluster.local or similar depending on your domain config.

-- coderanger
Source: StackOverflow

3/19/2020

Assuming that you created the database service in default namespace you can access mysql via database.default.svc.cluster.local from any namespace and via database.svc.cluster.local from the same namespace.

-- Arghya Sadhu
Source: StackOverflow