Install Nginx on Kubernetes: Create & Expose a Deployment (NodePort)

Install Nginx on Kubernetes: Create & Expose a Deployment (NodePort)

Follow these steps to deploy Nginx, verify it is running, expose it externally with a NodePort service, and remove all resources safely.

Create Nginx Deployment

  1. Create the deployment
    kubectl create deployment nginx --image=nginx
  2. Verify the deployment
    kubectl get deployments
  3. Verify pods are running
    kubectl get pods
  4. Access the Nginx pod to modify configuration (HTML or nginx.conf)

    Get the exact pod name:

    kubectl get pods

    Open a shell in the pod:

    kubectl exec -it <nginx-pod-name> -- /bin/bash

    Navigate to the HTML directory and edit the page:

    cd /usr/share/nginx/html
    vi index.html

    Apply any content changes you need.

  5. Expose the deployment as a NodePort service
    kubectl expose deployment nginx --type=NodePort --name=nginx-service
  6. Get the NodePort
    kubectl get svc nginx-service

    Example output:

    NAME            TYPE       CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
    nginx-service   NodePort   10.96.0.1    <none>        80:30007/TCP   1m
  7. Get node IP addresses
    kubectl get nodes -o wide

    Example:

    NAME               STATUS   ROLES           AGE   VERSION   INTERNAL-IP    EXTERNAL-IP
    cluster1-master    Ready    control-plane   5d    v1.28.14  192.168.1.10   <none>
    cluster1-worker1   Ready    <none>          5d    v1.28.14  192.168.1.11   <none>
  8. Configure router port forwarding
    • Internal Port: use the NodePort (e.g., 30007).
    • External Port: the same or any port you prefer.
    • Internal IP: the INTERNAL-IP of a node from the previous step.
  9. Access Nginx externally

    Open: http://<PublicIP>:<NodePort>

    Example: http://203.0.113.10:30007

Delete Nginx Deployment

  1. Delete the service
    kubectl delete svc nginx-service
  2. Delete the deployment
    kubectl delete deployment nginx
  3. Verify deletion
    kubectl get deployments
    kubectl get svc
  4. Optional cleanup

    Remove related resources if you created any:

    kubectl delete configmap <configmap-name>
    kubectl delete secret <secret-name>
    kubectl delete pvc <pvc-name>