Skip to content

Kubernetes Networking & Services

Un Service espone uno o più Pod tramite un endpoint stabile. Fa da “bridge” tra Pod e il resto del cluster. È accessibile solo internamente.

apiVersion: v1
kind: Service
metadata:
  name: sample-service
  labels:
    app: sample
spec:
  type: ClusterIP
  selector:
    app: sample
  ports:
    - name: http
      port: 80
      targetPort: 8080

Espone il servizio su una porta specifica di ogni Nodo (range standard: 30000–32767). Rende il servizio accessibile dall'esterno tramite <NodeIP>:<NodePort>.

apiVersion: v1
kind: Service
metadata:
  name: sample-nodeport
spec:
  type: NodePort
  selector:
    app: sample
  ports:
    - name: http
      port: 80          # porta interna al cluster
      targetPort: 8080  # porta del container/pod
      nodePort: 30080   # porta esposta sul nodo

Espone il servizio esternamente utilizzando il Load Balancer del cloud provider (AWS, GCP, Azure).

apiVersion: v1
kind: Service
metadata:
  name: sample-loadbalancer
spec:
  type: LoadBalancer
  selector:
    app: sample
  ports:
    - name: http
      port: 80
      targetPort: 8080

Gestisce l'accesso esterno ai servizi, tipicamente HTTP/S. Fornisce routing basato su hostname e path, terminazione SSL e load balancing applicativo.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: sample-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
    - host: app.local
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: sample-service
                port:
                  number: 80

Risorsa Custom (CRD) specifica per Traefik. Offre una configurazione più flessibile e nativa per gestire middleware, entrypoints e routing avanzato.

apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
  name: webapp-demo
  namespace: nginx
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`nginx.locale`)
      kind: Rule
      services:
        - name: webapp-demo
          port: 80

In questo scenario, isoliamo i Pod con label app: database nel namespace my-namespace, permettendo l'ingresso esclusivamente dai Pod che hanno label role: client

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-external-namespace-pod
  namespace: my-namespace # Namespace di destinazione (dove sta il DB)
spec:
  podSelector:
    matchLabels:
      app: database # Target: i pod che devono essere protetti
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          project: frontend # Filtra il namespace sorgente
      podSelector:
        matchLabels:
          role: client # Filtra il pod specifico dentro quel namespace
    ports:
    - protocol: TCP
      port: 5432 # Opzionale: restringe il traffico a una porta specifica