0
0
KubernetesHow-ToBeginner · 3 min read

How to Create a Service in Kubernetes: Step-by-Step Guide

To create a Service in Kubernetes, define a YAML manifest specifying the Service type, selector, and ports, then apply it using kubectl apply -f. This exposes your Pods to network traffic with a stable IP and DNS name inside the cluster or externally.
📐

Syntax

A Kubernetes Service manifest includes these key parts:

  • apiVersion: The API version, usually v1.
  • kind: Must be Service to create a service.
  • metadata: Contains the service name.
  • spec: Defines the service details:
    • selector: Labels to match Pods.
    • ports: List of ports to expose.
    • type: Service type like ClusterIP, NodePort, or LoadBalancer.
yaml
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP
💻

Example

This example creates a ClusterIP service named my-service that routes traffic on port 80 to Pods labeled app: MyApp on port 8080.

yaml
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP
Output
service/my-service created
⚠️

Common Pitfalls

Common mistakes when creating a Kubernetes Service include:

  • Incorrect or missing selector labels, so the Service does not find any Pods.
  • Mismatched port and targetPort values causing traffic to fail.
  • Using NodePort or LoadBalancer types without proper cluster or cloud setup.
  • Not applying the YAML file with kubectl apply -f or using kubectl create repeatedly causing conflicts.
yaml
### Wrong selector example (no matching Pods)
apiVersion: v1
kind: Service
metadata:
  name: wrong-service
spec:
  selector:
    app: WrongApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP

### Correct selector example
apiVersion: v1
kind: Service
metadata:
  name: correct-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP
📊

Quick Reference

Summary tips for creating Kubernetes Services:

  • Use kubectl apply -f service.yaml to create or update services.
  • ClusterIP exposes service inside the cluster only.
  • NodePort exposes service on each node’s IP at a static port.
  • LoadBalancer creates an external load balancer (cloud only).
  • Ensure selector labels exactly match your Pods’ labels.

Key Takeaways

Define a Service YAML with apiVersion, kind, metadata, and spec including selector and ports.
Apply the Service manifest using kubectl to expose Pods inside or outside the cluster.
Match the selector labels exactly to your Pods’ labels to route traffic correctly.
Choose the right Service type based on your exposure needs: ClusterIP, NodePort, or LoadBalancer.
Avoid common mistakes like missing selectors or port mismatches to ensure connectivity.