Use a Service to Access an Application in a Cluster
You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
To check the version, enter .
Objectives
- Run two instances of a Hello World application.
- Create a Service object that exposes a node port.
- Use the Service object to access the running application.
Here is the configuration file for the application Deployment:
service/access/hello-application.yaml
Run a Hello World application in your cluster: Create the application Deployment using the file above:
kubectl apply -f https://k8s.io/examples/service/access/hello-application.yaml
The preceding command creates a and an associated ReplicaSet. The ReplicaSet has two each of which runs the Hello World application.
Display information about your ReplicaSet objects:
kubectl get replicasets
kubectl describe replicasets
Create a Service object that exposes the deployment:
Display information about the Service:
kubectl describe services example-service
The output is similar to this:
Name: example-service
Namespace: default
Annotations: <none>
Selector: run=load-balancer-example
IP: 10.32.0.16
Port: <unset> 8080/TCP
TargetPort: 8080/TCP
NodePort: <unset> 31496/TCP
Endpoints: 10.200.1.4:8080,10.200.2.5:8080
Events: <none>
Make a note of the NodePort value for the service. For example, in the preceding output, the NodePort value is 31496.
List the pods that are running the Hello World application:
kubectl get pods --selector="run=load-balancer-example" --output=wide
Get the public IP address of one of your nodes that is running a Hello World pod. How you get this address depends on how you set up your cluster. For example, if you are using Minikube, you can see the node address by running
kubectl cluster-info
. If you are using Google Compute Engine instances, you can use thegcloud compute instances list
command to see the public addresses of your nodes.On your chosen node, create a firewall rule that allows TCP traffic on your node port. For example, if your Service has a NodePort value of 31568, create a firewall rule that allows TCP traffic on port 31568. Different cloud providers offer different ways of configuring firewall rules.
Use the node address and node port to access the Hello World application:
curl http://<public-node-ip>:<node-port>
where
<public-node-ip>
is the public IP address of your node, and<node-port>
is the NodePort value for your service. The response to a successful request is a hello message:
Using a service configuration file
As an alternative to using , you can use a to create a Service.
To delete the Service, enter this command:
kubectl delete services example-service
What’s next
Learn more about .