Creating Services by Exposing Ports
Learn how to create Kubernetes Services by exposing ports.
Creating ReplicaSets#
Before we dive into services, we should create a ReplicaSet similar to the one we used in the previous chapter. It’ll provide the Pods we can use to demonstrate how Services work.
Let’s take a quick look at the ReplicaSet definition go-demo-2-rs
.
The only significant difference is the db
container definition. It is as follows.
We customized the command and the arguments so that MongoDB exposes the REST interface. We also defined the containerPort
. Those additions are needed so that we can test that the database is accessible through the Service.
Let’s create the ReplicaSet.
We created the ReplicaSet and retrieved its state from Kubernetes. The output is as follows.
You might need to wait until both replicas are up-and-running. If, in your case, the READY
column does not yet have the value 2
, please wait for a while and get
the state again. We can proceed after both replicas are running.
Exposing a resource#
We can use the kubectl expose
command to expose a resource as a new Kubernetes Service. That resource can be a Deployment, another Service, a ReplicaSet, a ReplicationController, or a Pod. We’ll expose the ReplicaSet since it is already running in the cluster.
-
Line 1: We specified that we want to expose a ReplicaSet (
rs
). -
Line 2: The name of the new Service should be
go-demo-2-svc
. -
Line 3: The port that should be exposed is
28017
(the port MongoDB interface is listening to). -
Line 4: we specified that the type of the Service should be
NodePort
.
As a result, the target port will be exposed on every node of the cluster to the outside world, and it will be routed to one of the Pods controlled by the ReplicaSet.
Other types of services#
There are other Service types we could have used to establish communication:
ClusterIP#
ClusterIP
(the default type) exposes the port only inside the cluster. Such a port would not be accessible from anywhere outside. ClusterIP
is useful when we want to enable communication between Pods and still prevent any external access.
If
NodePort
is used,ClusterIP
will be created automatically.
LoadBalancer#
The LoadBalancer
type is only useful when combined with cloud provider’s load balancer.
ExternalName#
ExternalName
maps a service to an external address (e.g., kubernetes.io
).
In this chapter, we’ll focus on NodePort
and ClusterIP
types. LoadBalancer
will have to wait until we move our cluster to one of the cloud providers and ExternalName
has a very limited usage.
Try it youself#
All the commands used in this lesson are given below.
You can practice the commands in the following code playground by pressing the Run button and waiting for the cluster to set up.
/
- go-demo-2-rs.yml