Can a single K8s deployment map to multiple K8s service objects?

1.5k Views Asked by At

I want to deploy an app on K8s cluster using the deployment, service object. I want to create two service objects and map it to the deployment (using labels and selectors). I want to know if this possible?

deployment:
name: test-deploy
labels: test

service 1:
name: test-service-1
selectors: test

service 2:
name: test-service-2
selectors: test

I'm confused on how K8s resolves this conflict? Can I try this in order to create two services?

deployment:
name: test-deploy
labels: 
    - test
    - svc1
    - svc2

service 1:
name: test-service-1
selectors: 
  - test
  - svc1

service 2:
name: test-service-2
selectors: 
  - test
  - svc2
1

There are 1 best solutions below

3
gohm'c On

I want to create two service objects and map it to the deployment (using labels and selectors). I want to know if this possible?

Yes. Apply the following spec:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      key1: test
      key2: svc1
      key3: svc2
  template:
    metadata:
      labels:
        key1: test
        key2: svc1
        key3: svc2
    spec:
      containers:
      - name: nginx
        image: nginx:alpine
        ports:
          - name: http
            containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service-1
spec:
  selector:
    key1: test
    key2: svc1
  ports:
  - name: http
    port: 8080
    targetPort: http
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service-2
spec:
  selector:
    key1: test
    key3: svc2
  ports:
  - name: http
    port: 8080
    targetPort: http
...

Test with:

kubectl port-forward svc/nginx-service-1 8080:http

kubectl port-forward svc/nginx-service-2 8081:http

curl localhost:8080

curl localhost:8081

You get response from respective service that back'ed by the same Deployment.