How do I enable direct internet access to Kubernetes Pods?
In this guide, we will enable direct internet access to Kubernetes Pods by creating a Kubernetes service of type LoadBalancer
. This will expose the Pods to the internet by provisioning a cloud load balancer that routes external traffic to the Pods.
A LoadBalancer
service type automatically creates an external load balancer in the cloud provider, which assigns a public IP address to the service. This allows the Pods to be accessed from the internet.
Below is the Pulumi program in TypeScript to achieve this:
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
// Create a new Kubernetes namespace
const namespace = new k8s.core.v1.Namespace("example-namespace", {
metadata: {
name: "example-namespace",
},
});
// Define a Kubernetes Deployment for the application Pods
const appLabels = { app: "nginx" };
const deployment = new k8s.apps.v1.Deployment("nginx-deployment", {
metadata: {
namespace: namespace.metadata.name,
},
spec: {
selector: { matchLabels: appLabels },
replicas: 3,
template: {
metadata: { labels: appLabels },
spec: {
containers: [
{
name: "nginx",
image: "nginx",
ports: [{ containerPort: 80 }],
},
],
},
},
},
});
// Create a Kubernetes Service of type LoadBalancer to expose the Deployment
const service = new k8s.core.v1.Service("nginx-service", {
metadata: {
namespace: namespace.metadata.name,
},
spec: {
type: "LoadBalancer",
selector: appLabels,
ports: [{ port: 80, targetPort: 80 }],
},
});
// Export the public IP of the service
export const serviceIP = service.status.loadBalancer.ingress[0].ip;
Key Points
- Namespace: A new namespace is created to organize the resources.
- Deployment: A deployment is defined to manage a set of identical Pods running the NGINX web server.
- Service: A service of type
LoadBalancer
is created to expose the deployment to the internet. - Public IP: The public IP address of the service is exported, which can be used to access the application.
Summary
In this guide, we created a Kubernetes namespace, a deployment for running NGINX Pods, and a service of type LoadBalancer
to expose the Pods to the internet. This setup allows the NGINX application to be accessed directly from the internet using the public IP address assigned to the service.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.