Example: Use ClusterIP to Expose an Nginx Pod Internally - neerajk555/Kubernetes GitHub Wiki

We'll do the following:

  1. Create a Namespace
  2. Create a Pod (running Nginx)
  3. Create a ClusterIP Service to expose the Pod
  4. Create a temporary Pod to access the service internally
  5. Cleanup

Step-by-Step Execution

1. Create a Namespace

kubectl create namespace demo-clusterip

2. Create the Nginx Pod

Create a file named nginx-pod.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  namespace: demo-clusterip
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80

Apply it: kubectl apply -f nginx-pod.yaml

3. Create a ClusterIP Service

Create a file nginx-clusterip-service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: demo-clusterip
spec:
  type: ClusterIP
  selector:
    app: nginx
  ports:
  - port: 80          # Service port (inside the cluster)
    targetPort: 80    # Container port

Apply it: kubectl apply -f nginx-clusterip-service.yaml

4. Access the Service from Inside the Cluster

You can't access ClusterIP services directly from your browser or curl on your host. But you can access it from another pod.

Run a temporary curl Pod in the same namespace:

kubectl run curl --rm -it --restart=Never \
  --image=busybox:1.28 \
  --namespace=demo-clusterip \
  --command sh

Inside the Pod, run:

wget -qO- http://nginx-service

You should see the Nginx welcome HTML output. Exit: exit


Cleanup

kubectl delete -f nginx-clusterip-service.yaml
kubectl delete -f nginx-pod.yaml
kubectl delete namespace demo-clusterip