Exposing a service in Kubernetes allows it to be accessible from outside the cluster. There are several ways to achieve this, and I’ll cover two common methods: using a NodePort and creating an Ingress resource.
Method 1: Using NodePort
- Create a Service YAML file: Create a file named
nginx-service.yamlwith the following content:
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: NodePortThis YAML file creates a NodePort service named nginx-service that exposes port 80.
- Apply the Service: Apply the service using the following command:
kubectl apply -f nginx-service.yamlThis will create the service.
- Get the NodePort: To access the service, you’ll use the NodePort. Get the port number:
kubectl get svc nginx-serviceThe output will show the NodePort (e.g., 30001).
- Access the Service: You can now access your service using any node’s IP address and the NodePort (e.g.,
http://).:30001
Method 2: Using Ingress
Ingress is used to expose HTTP and HTTPS routes from outside the cluster to services within the cluster.
- Enable Ingress Controller: Before using Ingress, you need to have an Ingress controller running in your cluster. For example, you can use NGINX or Traefik as the Ingress controller. Follow the specific instructions for your chosen controller.
- Create an Ingress YAML file: Create a file named
nginx-ingress.yamlwith the following content:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-ingress
spec:
rules:
- host: example.com # Replace with your domain
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: nginx-service
port:
number: 80This YAML file creates an Ingress resource that routes traffic from the specified domain to the nginx-service.
- Apply the Ingress: Apply the Ingress using the following command:
kubectl apply -f nginx-ingress.yamlThis will create the Ingress resource.
- Update DNS (if needed): If you specified a domain in the Ingress, make sure it points to one of your cluster nodes.
- Access the Service: Once DNS is set up (if needed), you can access your service using the specified domain.
Remember to replace placeholders like example.com and nginx-service with your actual values.
These are two common methods to expose services in Kubernetes. Choose the one that best suits your application’s needs.