Services create an abstraction layer which provides network access to a dynamic set of pods.
Most services use a selector to determine which pods will receive traffic though the service. As pods included in the service are created and removed dynamically, clients can receive uninterrupted access by using the service.
Services are Kubernetes objects which means that they can be created using yaml descriptors. Here is an example of a simple service:
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
type: ClusterIP
selector:
app: nginx
ports:
- protocol: TCP
port: 8080
targetPort: 80
There are four service types in Kubernetes.
By default, all pods in the cluster can communicate with any other pod, and reach out to any available IP.
NetworkPolicies allow you to limit what network traffic is allowed to and from pods in your cluster.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: my-network-policy
spec:
podSelector:
matchLabels:
app: MyApp
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: MyApp
ports:
- protocol: TCP
port: 6379