Kubernetes Service Discovery and Secrets

Himanshu Lohiya
2 min readOct 18, 2018

--

Creating 2 services

  1. Database service
  2. App service accessing database by Service Discovery and using Secrets.

Secrets :

Used to store sensitive data with encryption.

DNS :

Used within pods to find other services running on the same cluster.

Containers within one pod don’t need this service, they contact directly. A container in the same pod can connect to the port of the other container directly using “localhost: port”.

How does this DNS really work?
When you look up with servicename resolver automatically adds later part in it servicename.default.svc.cluster.local

Service Discovery

If you want to connect from a web service in one pod to a database in another pod, then you need Service Discovery because you cannot just access database pod as you don’t know the IP address or port.

Only when you create a service for a pod, then the pod really becomes accessible for other pod, and Service Discovery will work.

Create Secret

secrets.yml

apiVersion: v1
kind: Secret
metadata:
name: helloworld-secrets
type: Opaque
data:
username: aGVsbG93b3JsZA==
password: cGFzc3dvcmQ=

Create Database Pod

database.yml

apiVersion: v1
kind: Pod
metadata:
name: database
labels:
app: database
spec:
containers:
- name: mysql
image: mysql:5.7
ports:
- name: mysql-port
containerPort: 3306
env:
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: helloworld-secrets
key: username
- name: MYSQL_PASSWORD
valueFrom:
secretKeyRef:
name: helloworld-secrets
key: password

Create Database Service

database-service.yml

apiVersion: v1
kind: Service
metadata:
name: database-service
spec:
ports:
- port: 3306
protocol: TCP
selector:
app: database
type: NodePort

Create Application Deployement

app_deployment.yml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: helloworld-deployment
spec:
replicas: 3
template:
metadata:
labels:
app: helloworld-db
spec:
containers:
- name: k8s-demo
image: wardviaene/k8s-demo
command: ["node", "index-db.js"]
ports:
- name: nodejs-port
containerPort: 3000
env:
- name: MYSQL_HOST
value: database-service
- name: MYSQL_USER
value: root
- name: MYSQL_PASSWORD
valueFrom:
secretKeyRef:
name: helloworld-secrets
key: password

Create Application Service

app-service.yml

apiVersion: v1
kind: Service
metadata:
name: helloworld-db-service
spec:
ports:
- port: 3000
protocol: TCP
selector:
app: helloworld-db
type: NodePort

kubectl create -f secrets.yml
kubectl create -f database.yml
kubectl create -f database-service.yml
kubectl create -f app_deployment.yml
kubectl create -f app_service.yml
minikupe service helloworld-db-service — url
kubectl get pods
kubectl get svc
kubectl exec database -i -t — mysql -u root -p

--

--

No responses yet