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
Serviceto 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 likeClusterIP,NodePort, orLoadBalancer.
yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIPExample
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: ClusterIPOutput
service/my-service created
Common Pitfalls
Common mistakes when creating a Kubernetes Service include:
- Incorrect or missing
selectorlabels, so the Service does not find any Pods. - Mismatched
portandtargetPortvalues causing traffic to fail. - Using
NodePortorLoadBalancertypes without proper cluster or cloud setup. - Not applying the YAML file with
kubectl apply -for usingkubectl createrepeatedly 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: ClusterIPQuick Reference
Summary tips for creating Kubernetes Services:
- Use
kubectl apply -f service.yamlto create or update services. ClusterIPexposes service inside the cluster only.NodePortexposes service on each node’s IP at a static port.LoadBalancercreates an external load balancer (cloud only).- Ensure
selectorlabels 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.