← Full reference

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:

ObjectPurpose
Servicea stable name and IP for a group of pods selected by labels; load-balances requests between them
IngressHTTP(S) routing from outside the cluster: domain and path → Service; TLS
NetworkPolicya 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.typeHow it's reachableNotes
ClusterIPa virtual IP inside the clusterdefault
ClusterIP + clusterIP: Noneheadless: no IP, the service's DNS name returns the pod IPsfor StatefulSets and client-side load balancing
NodePorta port on every node: node-IP:nodePortalso gets a ClusterIP
LoadBalanceran external cloud load balanceralso a NodePort and ClusterIP; without a cloud controller EXTERNAL-IP stays <pending>
ExternalNamea DNS alias (CNAME) to the external host from externalNameno selector and no port proxying

Service: fields

FieldMeaningDefault / notes
spec.selectorlabels of the pods that receive trafficwithout a selector Kubernetes doesn't know the pods: addresses are set manually (EndpointSlice)
spec.ports[].portthe port the service listens onrequired
spec.ports[].targetPortthe container port: a number or a name from containerPortequals port
spec.ports[].nodePortthe port on the nodes for NodePort/LoadBalancerpicked automatically from 30000–32767
spec.ports[].protocolTCP / UDP / SCTPTCP
spec.ports[].nameport namerequired if there's more than one port
spec.clusterIPa specific IP or None (headless)assigned automatically
spec.externalNamehost for ExternalName
spec.sessionAffinityClientIP — a client always goes to the same podNone
spec.externalTrafficPolicyCluster / Local — external traffic goes only to pods on the receiving node, the client IP is preservedCluster
spec.publishNotReadyAddressesinclude pods that aren't Ready in DNSfalse

Ingress

An Ingress is just rules. They work only if an Ingress controller (ingress-nginx, Traefik and others) is installed in the cluster.

FieldMeaningDefault / notes
spec.ingressClassNamewhich controller handles this Ingress (nginx, traefik)the class marked as default in the cluster
spec.rules[].hostdomain: example.com, *.example.comwithout host — any domain
spec.rules[].http.paths[].pathURL path
spec.rules[].http.paths[].pathTypePrefix / Exact / ImplementationSpecificrequired
…paths[].backend.service.namewhere to route the request
…paths[].backend.service.port.number / .namethe service port (not the container's) — by number or nameone of the two
spec.defaultBackendwhere requests matching no rule godepends on the controller
spec.tls[].hostswhich domains get HTTPS
spec.tls[].secretNamea kubernetes.io/tls Secret with the certificate and keysee k8s-config
metadata.annotationscontroller-specific settings: nginx.ingress.kubernetes.io/rewrite-target and so on

pathType:

ValueWhat matches path: /api
Exactonly /api
Prefix/api, /api/, /api/users — by whole path segments; /apiv2 doesn't match
ImplementationSpecificup 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.

FieldMeaningDefault / notes
spec.podSelectorwhich pods of its own namespace the policy applies torequired; {} — all of them
spec.policyTypes[Ingress], [Egress] or bothif omitted: Ingress, plus Egress if there's an egress section
spec.ingress[].from[]who incoming traffic is allowed froman empty rule list = all incoming traffic denied
spec.ingress[].ports[]{protocol: TCP, port: 8080}; port — a number or port name; endPort for a rangewithout ports — all ports
spec.egress[].to[], spec.egress[].ports[]where outgoing traffic is allowed to

from / to elements:

ElementWhat 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 elementpods 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 refused or a timeout. kubeconform doesn't catch this. First compare the service's spec.selector with the labels in the pod template.
  • port and targetPort mixed up. port is the service port that clients connect to; targetPort is the port the container listens on. An Ingress refers to the service's port, 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 name are rejected by the API server, but the schema lets them through.
  • A nodePort outside 30000–32767 is rejected by the API (that's the default range), but the schema lets it through.
  • LoadBalancer without a cloud (minikube, kind, bare metal) stays <pending> forever unless MetalLB or similar is installed.
  • kubectl create ingress without * in the path gives pathType: Exact: the rule example.com/=web:80 catches only the root, and /about no longer matches. For "the whole site" write /*.
  • pathType: Prefix compares segments, not strings: /api doesn't match /apiv2.
  • An Ingress without a controller does nothing, without errors. And without ingressClassName and without a default class, no controller may pick it up.
  • podSelector in a NetworkPolicy is required by the schema: write a policy "for all pods" explicitly as podSelector: {}.
  • 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 a podSelector without its own dash under namespaceSelector means "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.
  • podSelector and namespaceSelector don't select nodes or external addresses. For traffic from outside the cluster you need ipBlock.

See also

kubectl · kubeconform · yq · k8s-workloads · k8s-config · nginx · dig · curl · openssl