What are Services
Services: A Service is an abstract way to expose an application running on a set of Pods as a network service. This gives your application a single, stable entry point.
Service Types: There are different types of services for different purposes.
ClusterIP: Exposes the service on a cluster-internal IP. This is the default and is only reachable from within the cluster.
NodePort: Exposes the service on each Node's IP at a static port (the NodePort). This makes the service accessible from outside the cluster.
LoadBalancer: Exposes the service externally using a cloud provider's load balancer. This is the most common way to expose an application on a public cloud.
ExternalName: Maps the service to a DNS name.
Labels and Selectors: Services use selectors to determine which Pods they should route traffic to. This is where the labels you added to your Deployment and Pods come into play. A Service with the app: nginx selector will automatically load balance traffic to all Pods with that same label.
Step 1: Create a Namespace
A namespace helps organize and isolate Kubernetes resources.
Run:
kubectl create namespace my-namespace
Replace my-namespace
with a name of your choice (e.g., day33-ns
).
To verify:
kubectl get namespaces
Step 2: Update Your Deployment YAML
Edit your deployment.yml
and add the namespace
field at the top level:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: my-namespace # <-- add this line
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
Step 3: Apply Deployment in the Namespace
kubectl apply -f deployment.yml -n my-namespace
Step 4: Verify Resources in the Namespace
Check deployments:
kubectl get deployments -n my-namespace
Check pods:
kubectl get pods -n my-namespace
Step 5: Understand Services
Services allow your Pods to be accessed inside or outside the cluster.
- ClusterIP (default): Exposes the service only within the cluster.
- NodePort: Exposes the service on each Node’s IP at a static port.
- LoadBalancer: Exposes the service externally using a cloud provider’s load balancer.
Example Service YAML (to expose Nginx Deployment):
apiVersion: v1
kind: Service
metadata:
name: nginx-service
namespace: my-namespace
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80 # Service port
targetPort: 80 # Pod containerPort
type: NodePort # Can be ClusterIP / NodePort / LoadBalancer
Apply:
kubectl apply -f service.yml -n my-namespace
Check service:
kubectl get svc -n my-namespace
Now your Nginx Deployment is running in its own namespace and exposed via a Service.