I just want to know, is it possible to refer to a service rather than a deployment (using service labels instead of deployment matchLabels) in a Kubernetes service definition?
What I mean to say is suppose I have a service A defined which exposes a deployment A-D and now I want to define another service B but this time instead of its selector referring to a deployment A-D I want it to point to the previous service defined i.e. service A? Is this even possible in Kubernetes? For eg see the scenario below
**Deployment A-D**
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
run: my-nginx
replicas: 2
template:
metadata:
labels:
run: my-nginx
spec:
containers:
- name: my-nginx
image: nginx
ports:
- containerPort: 80
**ServiceA**
apiVersion: v1
kind: Service
metadata:
name: my-nginx
labels:
run: my-nginx-1
spec:
ports:
- port: 80
protocol: TCP
selector:
run: my-nginx
**ServiceB**
apiVersion: v1
kind: Service
metadata:
name: my-nginx-wrapper-service
labels:
run: my-nginx-2
spec:
ports:
- port: 80
protocol: TCP
selector:
run: my-nginx-1 //service label instead of deployment
UPDATE:
headless service
apiVersion: v1
kind: Service
metadata:
name: access-service
annotations:
getambassador.io/config: |
---
apiVersion: ambassador/v1
kind: Mapping
name: productreadservice-mapping
prefix: /Apps/ProductReadService/.*
prefix_regex: true
rewrite: ""
service: access-service:80
spec:
clusterIP: None
ports:
- name: http
port: 80
targetPort: 8082
endpoint object
apiVersion: v1
kind: Endpoints
metadata:
name: access-service
subsets:
- addresses:
- ip: ip of the service i wish to access
ports:
- port: 8082
protocol: TCP
It is not possible. The selector needs to select pod labels only.
Yes, it is possible! Not through selectors though.
Ones you have the service pointing to the pods A-D, you have an IP address. You can create an Endpoints
object with that IP address. Then, you can create a headless service
without selectors with the same name as the Endpoints
object.
Example:
Say your service IP address (The one pointing to the Depoyments A-D) is 10.0.0.10. Create the Endpoints
object:
apiVersion: v1
kind: Endpoints
metadata:
name: my-headless-service
subsets:
- addresses:
- ip: 10.0.0.10
ports:
- port: 80
protocol: TCP
Now, create the headless service with the same name as the Endpoints
object. Note that it has no label selectors, so it is not selecting any backend. When this happens, the request is send to the DNS, and there it will search for either en ExternalName
type service with the same name or an Endpoints
object with the same name.
apiVersion: v1
kind: Service
metadata:
name: my-headless-service
spec:
clusterIP: None
ports:
- name: http
port: 80
targetPort: 80
The resolution happens at DNS, not at iptables.