Services
The base of networking in Kuberneties
- Service Types
- NodePort
- Makes a pod availble by mapping the port on the node to a port on the pod
- The service is accessible from outside the cluster via <NodeIP>:<NodePort>.
- ClusterIP
- An internal setup for communication between pods
- Creates a virtual IP address accessible only from within the cluster.
- For example, Pod-A wants to communicate with Pod-B. You set up a ClusterIP service named “service-pod-b”. Pod-A can then use the DNS name “service-pod-b” to send traffic to Pod-B.
- NodePort
- Port types
- NodePort: the port on the node that someone might connect to.
- Port: The port on the service that receives traffic and forwards it to the TargetPor
- Target Port: The port on the node that is listening on / The port on the Pod that the service forwards traffic to.
- Example:
- NodePort: 40000 (external port on the Node)
- Port: 80 (service port accessible within the cluster)
- TargetPort: 3000 (port on the Pod where the application is listening)
- Explination
- External access: A client outside the cluster accesses the Pod by connecting to <NodeIP>:40000.
- Internal access: A client inside the cluster (such as a pod) uses the service’s DNS name (<service-name>) and port 80.
- Pod: The Pod’s application listens on port 3000.
So with this Pod-B accessable from inside and outside the cluster, so that should be a ClusterIP
apiVersion: v1
kind: Service
metadata:
name: service-pod-b
spec:
selector:
app: pod-b. #These are the labels from your pod/deployment files so it knows what pod this should be attached to.
ports: # Please note ports is a list, so you can setup multiple ports here
- port: 80 # The port used inside the cluster
targetPort: 3000 # The port the Pod listens on
nodePort: 40000 # The externally accessible port
type: NodePort
If it was just going to be accessable from inside the cluster it would be
apiVersion: v1
kind: Service
metadata:
name: service-pod-b
spec:
selector:
app: pod-b
ports:
- port: 80
targetPort: 3000
type: ClusterIP
If you have multiple pods the service will load-balance between them randomly.