DNS in k8s
-
In k8s we have lots of pods and accessing each pod by its ip is not a good idea as when pod gets recreated it might not get same ip.
-
K8s comes with two possible DNS implementations
- kube-dns: this was used in early versions of k8s
- core-dns: This is majorly used in k8s
- DNS in k8s helps in service discovery that is accesing pods by names rather than ephemeral pod ip addresses.
Services in k8s
-
Refer Here
-
A service can expose with a ip address (fixed) and name which will point to some pods based on labels matched.
-
Lets create a new deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpd-deployment
labels:
app: httpd
spec:
replicas: 3
selector:
matchLabels:
app: httpd
template:
metadata:
labels:
app: httpd
spec:
containers:
- name: httpd
image: httpd:2.4
ports:
- containerPort: 80
- A serivce in k8s will get a cluster ip (internal ip address)
- A service also gets a name which can be resolved by
<service-name>.<namespace>.svc.cluster.local
-
A service can be created without ip address only with a name (headless services)
-
Service types
-
Lets create a service for nginx pods
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
selector:
app: nginx
type: ClusterIP
ports:
- name: web
port: 80
protocol: TCP
targetPort: 80
-
A service can be discovered via
- DNS Resolutions
- All pods created after the service created will have additional environmental variables injected
-
Lets create a nodeport
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
selector:
app: nginx
type: NodePort
ports:
- name: web
port: 80
protocol: TCP
targetPort: 80