kubernetes – What are the differences between kubectl expose deployment and create service?

kubectl create service nodeport myservice --tcp=80:80

it’s just create the service with servicename as labels/selector.

kubectl expose deployment myservice --type=NodePort --port=80 --target-port=80

it creates the service based on labels/selector specified in deployment. So using this you can expose all the PODs of specific one deployment over a single Nodeport.

Explanation :

Both have difference in labels mainly or selectors in other words.

kubectl create service nodeport myservice --tcp=80:80

If you will run above command it will create the service with selector myservice in it.

Example :

apiVersion: v1
kind: Service
metadata:
  labels:
    app: myservice
  name: myservice
spec:
  ports:
  - name: 80-80
    nodePort: 30858
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: myservice
  type: NodePort

as you can see your selector : myservice and same set in labels & servicename. So service name goes as labels and selector. Your service was created here but won’t be able to talk to deployment as the selector is different (unless you create the service with the name of matching selector from deployment).

While with command :

kubectl expose deployment nginx-deployment --type=NodePort --port=80 --target-port=80

it will use the labels and selector of deployment. Which mean if you have deployment running of Nginx and it has selector : nginx it will get it from there as you are exposing that deployment.

Example deployment :

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.2
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
          protocol: TCP

Now if you will run command like

kubectl expose deployment nginx-deployment --type=NodePort --port=80 --target-port=80

service will have selector: nginx used in deployment.

Example service :

apiVersion: v1
kind: Service
metadata:
  labels:
    app: nginx
  name: nginx-deployment
spec:
  ports:
  - name: 80-80
    nodePort: 30858
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx
  type: NodePort

Read more here: Source link