Search code examples
kuberneteskubectl

How to expose 2 port in one deployement and service


I want to expose 2 ports on one service:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: etools
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: etools
    spec:
      containers:
      - name: etools
        image: eregistry.azurecr.io/etools:latest
        ports:
        - containerPort: 8080
        - containerPort: 3100
---
apiVersion: v1
kind: Service
metadata:
  name: etools
spec:
  ports:
  - port: 8080
  selector:
    app: etools
  ports:
  - port: 3100
  selector:
    app: etools

How can I achieve it?


Solution

  • Your Service is very close, but in the ports: array, the ports need to be named if there is more than one (they ideally would always have names), and the selector: is just once per Service, not per-port:

    spec:
      selector:
        app: etools
      ports:
      - name: web
        port: 8080
        targetPort: 8080
      - name: other-port-something
        port: 3100
        targetPort: 3100
    

    Be aware that while you will often see port: and targetPort: equal to the same number, they don't have to be. So your container could listen on 8080, because docker image says it will, but your Service could expose that to other members of your cluster as port: 80 to be closer to what one would expect.

    It's also possible to name the ports in your PodSpec with natural language names, and then point the Service at that value:

    ports:
    - name: http
      port: 80
      targetPort: http-in-my-pod
    

    which I recommend because it decouples your Service from having to change just because the containerPort changed in your PodSpec, but at your discretion.

    I'm a little surprised that kubectl didn't offer helpful feedback when you provided it that malformed yaml, but either way, I believe the snippet above is correct. As the docs specify, the names must be both unique within the Service, and also "DNS-compatible" names, so no underscores, spaces, crazy characters