0

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
enigma
  • 93
  • 1
  • 10

1 Answers1

1

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.

gohm'c
  • 13,492
  • 1
  • 9
  • 16
  • Thanks. I see you curled on different ports and both the service manifests have port:8080. Should one of them be 8081? I'm asking because this may lead to conflict isn't it? – enigma Aug 15 '22 at 04:10
  • yes, 8080 cannot be open twice on your local machine. – gohm'c Aug 15 '22 at 06:31
  • I've observed in the past that `kubectl port-forward` doesn't send traffic "through the service"; it uses the service selector and port data to select a specific pod and connects directly to it. That may or may not affect this experiment; maybe try to `kubectl run` a debugging container and use `curl` as an alternative. – David Maze Aug 15 '22 at 11:48