Kubernetes: Service, Ingress, NetworkPolicy
Networking in Kubernetes — Service types, ports, Ingress with paths and TLS, NetworkPolicy and default-deny
Pods come and go, and their IPs change. So you don't reach them directly but through networking objects:
| Object | Purpose |
|---|---|
| Service | a stable name and IP for a group of pods selected by labels; load-balances requests between them |
| Ingress | HTTP(S) routing from outside the cluster: domain and path → Service; TLS |
| NetworkPolicy | a firewall between pods: who can talk to whom |
Inside the cluster a Service is reachable by the DNS name <service> from its own namespace and <service>.<namespace>.svc.cluster.local from any namespace.
Syntax
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector: {app: web} # which pods to send traffic to (by labels)
ports:
- port: 80 # the service port
targetPort: 8080 # the port in the container
Service and Ingress skeletons are generated by kubectl create service … and kubectl create ingress … with --dry-run=client -o yaml. There's no generator for NetworkPolicy — write it by hand.
Service: types
spec.type | How it's reachable | Notes |
|---|---|---|
ClusterIP | a virtual IP inside the cluster | default |
ClusterIP + clusterIP: None | headless: no IP, the service's DNS name returns the pod IPs | for StatefulSets and client-side load balancing |
NodePort | a port on every node: node-IP:nodePort | also gets a ClusterIP |
LoadBalancer | an external cloud load balancer | also a NodePort and ClusterIP; without a cloud controller EXTERNAL-IP stays <pending> |
ExternalName | a DNS alias (CNAME) to the external host from externalName | no selector and no port proxying |
Service: fields
| Field | Meaning | Default / notes |
|---|---|---|
spec.selector | labels of the pods that receive traffic | without a selector Kubernetes doesn't know the pods: addresses are set manually (EndpointSlice) |
spec.ports[].port | the port the service listens on | required |
spec.ports[].targetPort | the container port: a number or a name from containerPort | equals port |
spec.ports[].nodePort | the port on the nodes for NodePort/LoadBalancer | picked automatically from 30000–32767 |
spec.ports[].protocol | TCP / UDP / SCTP | TCP |
spec.ports[].name | port name | required if there's more than one port |
spec.clusterIP | a specific IP or None (headless) | assigned automatically |
spec.externalName | host for ExternalName | |
spec.sessionAffinity | ClientIP — a client always goes to the same pod | None |
spec.externalTrafficPolicy | Cluster / Local — external traffic goes only to pods on the receiving node, the client IP is preserved | Cluster |
spec.publishNotReadyAddresses | include pods that aren't Ready in DNS | false |
Ingress
An Ingress is just rules. They work only if an Ingress controller (ingress-nginx, Traefik and others) is installed in the cluster.
| Field | Meaning | Default / notes |
|---|---|---|
spec.ingressClassName | which controller handles this Ingress (nginx, traefik) | the class marked as default in the cluster |
spec.rules[].host | domain: example.com, *.example.com | without host — any domain |
spec.rules[].http.paths[].path | URL path | |
spec.rules[].http.paths[].pathType | Prefix / Exact / ImplementationSpecific | required |
…paths[].backend.service.name | where to route the request | |
…paths[].backend.service.port.number / .name | the service port (not the container's) — by number or name | one of the two |
spec.defaultBackend | where requests matching no rule go | depends on the controller |
spec.tls[].hosts | which domains get HTTPS | |
spec.tls[].secretName | a kubernetes.io/tls Secret with the certificate and key | see k8s-config |
metadata.annotations | controller-specific settings: nginx.ingress.kubernetes.io/rewrite-target and so on |
pathType:
| Value | What matches path: /api |
|---|---|
Exact | only /api |
Prefix | /api, /api/, /api/users — by whole path segments; /apiv2 doesn't match |
ImplementationSpecific | up to the controller |
If several paths match, the longest one wins.
NetworkPolicy
As long as no policy applies to a pod, everything is allowed for it. As soon as at least one policy for a given direction selects it (Ingress — incoming traffic, Egress — outgoing), only what the policies allow is permitted in that direction. There are no deny rules — policies only add permissions.
| Field | Meaning | Default / notes |
|---|---|---|
spec.podSelector | which pods of its own namespace the policy applies to | required; {} — all of them |
spec.policyTypes | [Ingress], [Egress] or both | if omitted: Ingress, plus Egress if there's an egress section |
spec.ingress[].from[] | who incoming traffic is allowed from | an empty rule list = all incoming traffic denied |
spec.ingress[].ports[] | {protocol: TCP, port: 8080}; port — a number or port name; endPort for a range | without ports — all ports |
spec.egress[].to[], spec.egress[].ports[] | where outgoing traffic is allowed to |
from / to elements:
| Element | What it selects |
|---|---|
podSelector: {matchLabels: …} | pods with these labels in the same namespace |
namespaceSelector: {matchLabels: …} | all pods in namespaces with these labels; every namespace has the label kubernetes.io/metadata.name: <name> |
podSelector + namespaceSelector in one element | pods with the labels and in matching namespaces |
ipBlock: {cidr: 10.0.0.0/8, except: [10.1.0.0/16]} | an IP range (usually addresses outside the cluster) |
Separate elements of the from list are combined with "or", and selectors within one element with "and".
Examples
# Services of different types: --tcp=service_port:container_port
kubectl create service clusterip web --tcp=80:8080 --dry-run=client -o yaml > svc.yaml
kubectl create service nodeport web --tcp=80:8080 --node-port=30080 --dry-run=client -o yaml
kubectl create service clusterip db --clusterip=None --dry-run=client -o yaml # headless
kubectl create service externalname mail --external-name=smtp.example.com --dry-run=client -o yaml
# the generator uses the selector app=<service name>; if the pods have other labels, fix it
yq -i '.spec.selector = {"app": "frontend"}' svc.yaml
# Ingress: a path with * is Prefix, without * is Exact; tls=secret enables HTTPS for the host
kubectl create ingress site --class=nginx \
--rule='example.com/api*=api:80' \
--rule='example.com/*=web:80,tls=site-tls' \
--dry-run=client -o yaml > ingress.yaml
# view the paths and types
yq '.spec.rules[].http.paths[] | .path + " " + .pathType + " -> " + .backend.service.name' ingress.yaml
kubeconform -strict -summary svc.yaml ingress.yaml
# in a cluster (won't work here):
# kubectl get svc,endpointslices -l app=web # were pods found behind the service
# kubectl get ingress site
# kubectl run tmp --rm -it --image=busybox -- wget -qO- http://web
A service with two named ports, targetPort by the container port's name:
apiVersion: v1
kind: Service
metadata:
name: api
spec:
type: NodePort
selector: {app: api}
ports:
- name: http
port: 80
targetPort: http # containerPort with name: http
nodePort: 30080
- name: metrics
port: 9090
targetPort: 9090
An Ingress with HTTPS and two services:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: site
spec:
ingressClassName: nginx
tls:
- hosts: [example.com]
secretName: site-tls
rules:
- host: example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: api
port: {number: 80}
- path: /
pathType: Prefix
backend:
service:
name: web
port: {name: http}
Deny all incoming traffic in a namespace, then allow selectively:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
spec:
podSelector: {} # all pods in the namespace
policyTypes: [Ingress] # no ingress rules — incoming traffic denied
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-from-api
spec:
podSelector:
matchLabels: {app: db}
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels: {app: api}
- namespaceSelector: # separate element: "or" — the whole monitoring namespace
matchLabels:
kubernetes.io/metadata.name: monitoring
ports:
- {protocol: TCP, port: 5432}
Outgoing traffic only to DNS and to its own database:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-egress
spec:
podSelector:
matchLabels: {app: api}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector: # same element: "and" — kube-dns in kube-system
matchLabels: {k8s-app: kube-dns}
ports:
- {protocol: UDP, port: 53}
- {protocol: TCP, port: 53}
- to:
- podSelector:
matchLabels: {app: db}
ports:
- {protocol: TCP, port: 5432}
Pitfalls
- The service selector doesn't match the pod labels — there's no error, the service simply has no addresses, and requests get
connection refusedor a timeout.kubeconformdoesn't catch this. First compare the service'sspec.selectorwith thelabelsin the pod template. portandtargetPortmixed up.portis the service port that clients connect to;targetPortis the port the container listens on. An Ingress refers to the service'sport, not the container port.- A port as a string.
port: "80"fails the schema.targetPort: "8080"passes, but is treated as a port name. - Several ports without
nameare rejected by the API server, but the schema lets them through. - A
nodePortoutside30000–32767is rejected by the API (that's the default range), but the schema lets it through. LoadBalancerwithout a cloud (minikube, kind, bare metal) stays<pending>forever unless MetalLB or similar is installed.kubectl create ingresswithout*in the path givespathType: Exact: the ruleexample.com/=web:80catches only the root, and/aboutno longer matches. For "the whole site" write/*.pathType: Prefixcompares segments, not strings:/apidoesn't match/apiv2.- An Ingress without a controller does nothing, without errors. And without
ingressClassNameand without a default class, no controller may pick it up. podSelectorin a NetworkPolicy is required by the schema: write a policy "for all pods" explicitly aspodSelector: {}.- Egress default-deny breaks DNS. Deny all outgoing traffic and pods can no longer resolve service names. Allow UDP and TCP 53 to kube-dns.
- One dash changes the meaning.
- namespaceSelector: …and- podSelector: …as separate elements mean "or", while apodSelectorwithout its own dash undernamespaceSelectormeans "and". Check indentation especially carefully. - NetworkPolicy works only if the network plugin supports it (Calico, Cilium and others). With a plugin that doesn't (e.g. flannel), the API accepts policies but they block nothing.
podSelectorandnamespaceSelectordon't select nodes or external addresses. For traffic from outside the cluster you needipBlock.
See also
kubectl · kubeconform · yq · k8s-workloads · k8s-config · nginx · dig · curl · openssl