Creating a Service
Now that we have a running pod, let's create a Service to expose it. In Kubernetes, a Service is an abstraction that defines a logical set of Pods and a policy by which to access them. Think of it as a way to expose your application to the network, either within the cluster or externally.
Create a file named nginx-service.yaml
in your project directory:
nano ~/project/nginx-service.yaml
Add the following content to the file:
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: NodePort
Let's break down this YAML file:
selector
: This determines which Pods the Service will send traffic to. In this case, it will select any Pods with the label app: nginx
.
ports
: This specifies which ports the Service should use.
type: NodePort
: This means the Service will be accessible on a port on each node in your cluster.
Save the file and exit the editor.
Now, create the service by running:
kubectl apply -f nginx-service.yaml
To check the status of your service, use:
kubectl get services
You should see output similar to this:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1h
nginx-service NodePort 10.110.126.65 <none> 80:30080/TCP 30s
The nginx-service
line shows that your service has been created. The 80:30080/TCP
under PORT(S) means that port 80 inside the cluster is mapped to port 30080 on the node.
To get more detailed information about the service, use:
kubectl describe service nginx-service
This command provides information about the service's type, IP addresses, ports, and endpoints. The endpoints are the IP addresses of the Pods that the Service is sending traffic to.