How to expose deployment as service?

I have created deployment and node port service. Next I need service endpoint to exposes deployment.

Create a new service: name = vote-service
port = ‘5000’
targetPort = ‘80’
nodePort= ‘31000’
service endpoint exposes deployment ‘vote-deployment’

Tried this command: kubectl expose deployment vote-deployment --type=NodePort --port=80 --target-port=5000

But not working. Kindly help.

You have “–port” and “–target-port” reversed. The container port of the voting app container is 80, so target-port should be 80. “port” refers to the clusterIP port of the service, not the pod. And you’d need to edit the service afterwards to set the nodePort to 31000,

1 Like

@rob_kodekloud pretty much explained what you need to do. but I see that your requirement also contains a “name” requirement. so your command should read more like:

kubectl expose deployment vote-deployment --name vote-service --port 5000 --target-port 80 --type NodePort --dry-run=client -o yaml > vote-service.yaml

then you, edit vote-service.yaml using:

vi vote-service.yaml

You should end up with something like:

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels: #use the right labels (if you need it)
    app: vote-deployment #use the right labels please
  name: vote-service
spec:
  ports:
  - port: 5000
    protocol: TCP
    targetPort: 80
    nodePort: 31000
  selector: #This should automatically populate to match your deployment labels (that's the beauty of using expose command)
    app: vote-deployment
  type: NodePort
status:
  loadBalancer: {}

@rob_kodekloud @olakunlecrown28 …thanks. Port value was typo. Was passing it correctly in actual file.

Steps I was doing (which was not working)

  1. Create vote deployement
  2. Create vote service from yml file with node port type and details
  3. Exposing vote deployement to service

Steps I have done now (which is working)

  1. Create vote deployement
  2. Exposing vote deployement to service
  3. Create vote service from yml file with node port type and details
  4. Running apply command for vote service

Hope I have done it correctly as lab session has marked it as complete