1. Answers
  2. Expose Kubernetes Service using NodePort

How do I expose a Kubernetes service using NodePort?

In this guide, we will learn how to expose a Kubernetes service using NodePort. The NodePort service type allows you to expose a service on each node’s IP address at a static port. This can be useful for accessing services from outside the cluster without using a load balancer.

We will create a Kubernetes deployment and a service that uses NodePort to expose the deployment.

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Create a Kubernetes namespace
const namespace = new k8s.core.v1.Namespace("my-namespace", {
    metadata: { name: "my-namespace" },
});

// Create a Kubernetes deployment
const appLabels = { app: "my-app" };
const deployment = new k8s.apps.v1.Deployment("my-deployment", {
    metadata: {
        namespace: namespace.metadata.name,
    },
    spec: {
        selector: { matchLabels: appLabels },
        replicas: 3,
        template: {
            metadata: { labels: appLabels },
            spec: {
                containers: [{
                    name: "my-app",
                    image: "nginx:1.14.2",
                    ports: [{ containerPort: 80 }],
                }],
            },
        },
    },
});

// Create a Kubernetes service of type NodePort
const service = new k8s.core.v1.Service("my-service", {
    metadata: {
        namespace: namespace.metadata.name,
    },
    spec: {
        type: "NodePort",
        selector: appLabels,
        ports: [{
            port: 80,
            targetPort: 80,
            nodePort: 30007,  // Static port on each node's IP
        }],
    },
});

// Export the service name and NodePort URL
export const serviceName = service.metadata.name;
export const serviceUrl = pulumi.interpolate`http://${pulumi.getStack()}.example.com:${service.spec.ports[0].nodePort}`;

Key Points

  • Namespace: We created a namespace to logically isolate the resources.
  • Deployment: A deployment was created to manage a set of identical pods.
  • Service: A service of type NodePort was created to expose the deployment on each node’s IP at a static port.
  • NodePort: The nodePort field specifies the static port on each node’s IP.

Summary

In this guide, we created a Kubernetes deployment and exposed it using a NodePort service. This allows the service to be accessible on each node’s IP address at a specified static port.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up