Sending Prometheus Alerts as SNMP Traps with kube-prometheus-stack

Many operators still run an SNMP-based NMS for alarm management. If your Kubernetes monitoring is built on kube-prometheus-stack, you can forward Prometheus alerts to that NMS as SNMP traps using snmp_notifier. This post walks through the full configuration, shows how to test it with fake alerts, and collects every troubleshooting command I used, together with real (sanitized) output, so you can compare against your own system.

1. How it fits together

PrometheusRule (alert has label oid=...)
        │
        ▼
Prometheus ──fires──► Alertmanager
                          │  route: matchers oid=~".+"
                          ▼
                   webhook receiver  (HTTP POST /alerts)
                          │
                          ▼
              alertmanager-snmp-notifier  (:9464)
                          │  SNMPv2c trap, UDP 162
                          ▼
                    NMS / trap receiver(s)

Key ideas:

  • Only alerts that carry an oid label are sent to SNMP. The label value becomes the trap's base OID.
  • Alertmanager does not speak SNMP. It sends a normal webhook to snmp_notifier, which converts it into a trap.
  • With continue: true on the route, the same alert also reaches your other receivers (Slack, e-mail, …).

2. Prerequisites

  • kube-prometheus-stack deployed with Helm (here in the monitoring namespace, release name kube-prometheus-stack).
  • The alertmanager-snmp-notifier Helm chart. In my setup it is bundled as a dependency of kube-prometheus-stack, enabled by snmpAlertNotifier.enabled. With upstream kube-prometheus-stack, install prometheus-community/alertmanager-snmp-notifier separately in the same namespace instead.
  • An enterprise OID for your traps. Below I use 1.3.6.1.4.1.XXXXX.41. Replace XXXXX with your own Private Enterprise Number.
  • UDP 162 open from the Kubernetes nodes to the trap receivers.

3. Configuration

3.1 Enable the SNMP notifier and set the trap destinations

snmpAlertNotifier:
  enabled: true                    # turns on the alertmanager-snmp-notifier sub-chart
  oid: 1.3.6.1.4.1.XXXXX.41        # oid label added to the built-in node rules
  type: service

alertmanager-snmp-notifier:
  snmpNotifier:
    extraArgs: []
    # - --log.level=debug          # handy while troubleshooting
    snmpDestinations:
      - 192.0.2.10:162             # NMS 1
      - 192.0.2.20:162             # NMS 2
    # The default community is "public". Prefer a secret:
    # snmpCommunitySecret:
    #   name: snmp-community
    #   key: community
  service:
    type: ClusterIP
    port: 9464

3.2 Trap content: description and extra varbinds

snmp_notifier lets you template the trap description and add extra varbinds. These templates put the pod, instance, namespace, host and container of the first alert into sub-OIDs 4–8:

alertmanager-snmp-notifier:
  snmpNotifier:
    snmpTemplates:
      description: |
        {{- if .Alerts -}}
        {{ len .Alerts }}/{{ len .DeclaredAlerts }} alerts are firing:

        {{ range $severity, $alerts := (groupAlertsByLabel .Alerts "severity") -}}
        Status: {{ $severity }}

        {{- range $index, $alert := $alerts }}
        - Alert: {{ $alert.Labels.alertname }}
          Summary: {{ $alert.Annotations.summary }}
          Description: {{ $alert.Annotations.description }}
        {{ end }}
        {{ end }}
        {{ else -}}
        Status: OK
        {{- end -}}
      extraFields:
        - subId: 4
          template: |
            {{- if .Alerts -}}{{ (index .Alerts 0).Labels.pod }}{{- else -}}{{- "" -}}{{- end -}}
        - subId: 5
          template: |
            {{- if .Alerts -}}{{ (index .Alerts 0).Labels.instance }}{{- else -}}{{- "" -}}{{- end -}}
        - subId: 6
          template: |
            {{- if .Alerts -}}{{ (index .Alerts 0).Labels.namespace }}{{- else -}}{{- "" -}}{{- end -}}
        - subId: 7
          template: |
            {{- if .Alerts -}}{{ or ((index .Alerts 0).Labels.host) .CommonLabels.host "" }}{{- else -}}{{- "" -}}{{- end -}}
        - subId: 8
          template: |
            {{- if .Alerts -}}{{ or ((index .Alerts 0).Labels.container) .CommonLabels.container "" }}{{- else -}}{{- "" -}}{{- end -}}

3.3 Alertmanager receiver and route

Add a webhook receiver that points at the notifier service, and a route that matches any alert with an oid label:

alertmanager:
  enabled: true
  config:
    global:
      resolve_timeout: 1m
    receivers:
      - name: slack-notifications
        slack_configs:
          - api_url: '<your-slack-webhook-url>'
            channel: 'alerts'
            send_resolved: true
      - name: snmp-notifications
        webhook_configs:
          - send_resolved: true
            url: http://kube-prometheus-stack-alertmanager-snmp-notifier:9464/alerts
    route:
      receiver: slack-notifications          # default receiver
      group_by: ['...']
      routes:
        - matchers:
            - oid=~".+"                      # only alerts that carry an oid label
          receiver: snmp-notifications
          group_by: ['alertname', 'pod', 'instance', 'namespace', 'host', 'container']
          continue: true                     # keep evaluating, so Slack gets it too
        - receiver: slack-notifications
          group_by: ['...']
Note: the webhook URL is <release>-alertmanager-snmp-notifier. If your release name is different, check the real service name with kubectl get svc -n monitoring | grep snmp.

3.4 Give your alerts an oid label

No oid label, no trap. In my chart, the built-in node CPU and memory rules get the label automatically when snmpAlertNotifier.enabled is true. They live in the general rule group, so that group must be enabled:

defaultRules:
  rules:
    general: true    # if false, the oid-labelled node rules are not rendered at all

For your own rules, just add the labels:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: my-app-snmp-rules
  namespace: monitoring
  labels:
    release: kube-prometheus-stack
spec:
  groups:
    - name: my-app
      rules:
        - alert: MyAppDown
          expr: up{job="my-app"} == 0
          for: 1m
          labels:
            severity: critical
            oid: 1.3.6.1.4.1.XXXXX.41
            type: service
          annotations:
            summary: "my-app is down"
            description: "Target {{ $labels.instance }} has been down for 1 minute."

3.5 Deploy

helm upgrade kube-prometheus-stack ./kube-prometheus-stack -f ./kube-prometheus-stack/my-values.yaml -n monitoring

4. Testing with a fake alert (amtool)

You don't need to wait for a real problem. amtool is included in the Alertmanager image, so you can inject an alert directly. The commands below are for bash (Linux/WSL).

4.1 Fire the alert

END=$(date -u -d '+1 hour' +%Y-%m-%dT%H:%M:%SZ)

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  amtool alert add alertname=SnmpTestAlert severity=critical oid=1.3.6.1.4.1.XXXXX.41 type=service \
  instance=test-instance namespace=monitoring pod=test-pod \
  '--annotation=summary="SNMP test alert"' '--annotation=description="Manual SNMP trap test"' \
  --end=$END --alertmanager.url=http://localhost:9093

4.2 Check that it is active

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  amtool alert query alertname=SnmpTestAlert --alertmanager.url=http://localhost:9093

Output:

Alertname      Starts At                Summary          State
SnmpTestAlert  2026-11-02 07:29:27 UTC  SNMP test alert  active

4.3 Resolve the alert

Send the alert again with exactly the same labels and an end time of now:

NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)
echo $NOW     # must be the current UTC time, NOT one hour ahead

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  amtool alert add alertname=SnmpTestAlert severity=critical oid=1.3.6.1.4.1.XXXXX.41 type=service \
  instance=test-instance namespace=monitoring pod=test-pod \
  '--annotation=summary="SNMP test alert"' '--annotation=description="Manual SNMP trap test"' \
  --end=$NOW --alertmanager.url=http://localhost:9093

Query again. An empty result means it is resolved (amtool alert query only shows active alerts):

Alertname  Starts At  Summary  State

4.4 Timing to expect

  • Firing trap: about 30 s after you send the alert (group_wait, default 30s).
  • Resolved trap: up to about 5 minutes after the resolve (group_interval, default 5m).
  • No end time: with resolve_timeout: 1m, an alert added without --end resolves itself after about a minute.

5. Verifying and troubleshooting, step by step

Work along the chain: route → webhook → notifier → network. Each step below has the command and what a healthy result looks like.

5.1 Are the pods and the service there?

kubectl get pods,svc -n monitoring | grep -E "snmp|alertmanager"

You should see a running …-alertmanager-snmp-notifier pod and a service on port 9464 whose name matches the webhook URL.

5.2 Does the alert match the SNMP route?

Test the routing tree against the config Alertmanager actually loaded:

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  amtool config routes test --config.file=/etc/alertmanager/config_out/alertmanager.env.yaml \
  alertname=SnmpTestAlert oid=1.3.6.1.4.1.XXXXX.41 severity=critical

Healthy output (both receivers, thanks to continue: true):

snmp-notifications,slack-notifications

If you only see slack-notifications, your route was not applied. Show the loaded tree with:

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  amtool config routes show --config.file=/etc/alertmanager/config_out/alertmanager.env.yaml

5.3 Did Alertmanager deliver the webhook?

Alertmanager only logs failed notifications, so an empty log is a good sign:

kubectl logs -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager --since=1h \
  | grep -iE "snmp|webhook|notify|error"

The metrics are more reliable:

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  wget -qO- http://localhost:9093/metrics | grep -E 'alertmanager_notifications_(total|failed_total)\{.*webhook'

Healthy output:

alertmanager_notifications_failed_total{integration="webhook",reason="clientError"} 0
alertmanager_notifications_failed_total{integration="webhook",reason="contextCanceled"} 0
alertmanager_notifications_failed_total{integration="webhook",reason="contextDeadlineExceeded"} 0
alertmanager_notifications_failed_total{integration="webhook",reason="other"} 0
alertmanager_notifications_failed_total{integration="webhook",reason="serverError"} 0
alertmanager_notifications_total{integration="webhook"} 3

Run it before and after firing a test alert. The notifications_total counter should go up by one (3 → 4 in my test), and every failed_total should stay at 0.

5.4 What does the notifier say?

kubectl logs -n monitoring deploy/kube-prometheus-stack-alertmanager-snmp-notifier --since=1h
kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  wget -qO- http://kube-prometheus-stack-alertmanager-snmp-notifier:9464/metrics | grep -i snmp

If there isn't enough detail, add --log.level=debug to snmpNotifier.extraArgs and run helm upgrade again.

5.5 Bypass Alertmanager: call the notifier directly

This tells you whether the notifier and network work on their own:

kubectl exec -n monitoring alertmanager-kube-prometheus-stack-alertmanager-0 -c alertmanager -- \
  wget -qO- --header='Content-Type: application/json' --post-data='{"receiver":"snmp-notifications","status":"firing","alerts":[{"status":"firing","labels":{"alertname":"SnmpDirectTest","oid":"1.3.6.1.4.1.XXXXX.41","severity":"critical","instance":"test"},"annotations":{"summary":"direct test","description":"direct webhook test"},"startsAt":"2026-11-02T08:00:00Z"}],"groupLabels":{"alertname":"SnmpDirectTest"},"commonLabels":{"alertname":"SnmpDirectTest","oid":"1.3.6.1.4.1.XXXXX.41","severity":"critical"},"commonAnnotations":{},"externalURL":"http://alertmanager","version":"4","groupKey":"test"}' \
  http://kube-prometheus-stack-alertmanager-snmp-notifier:9464/alerts

5.6 Capture the traps with ksniff

ksniff runs tcpdump in a pod's network namespace. Capture both the incoming webhook (TCP 9464) and the outgoing traps (UDP 162):

POD=$(kubectl get pods -n monitoring -o name | grep snmp-notifier | head -1 | cut -d/ -f2)

kubectl sniff $POD -n monitoring -p -f "udp port 162 or tcp port 9464" -o snmp_trap_test.pcap
  • -p (privileged mode) is needed because the notifier image is minimal and non-root, so ksniff can't upload a static tcpdump into it.
  • -o writes to a file. Without it, ksniff tries to open Wireshark, which won't work in WSL.
  • On containerd clusters you may need --socket /run/containerd/containerd.sock. On air-gapped clusters, point --image and --tcpdump-image at your own registry.

Start the capture first, then fire the test alert, wait about a minute, resolve it, wait about 5 minutes, and stop with Ctrl+C.

In Wireshark, filter out the health-probe noise with:

http.request.method == "POST" || udp.port == 162

A successful capture looks like this:

No.  Source          Destination     Protocol   Info
147  10.244.1.20     10.244.1.30     HTTP/JSON  POST /alerts HTTP/1.1
149  10.244.1.30     192.0.2.10      SNMP       snmpV2-trap 1.3.6.1.2.1.1.3.0 ...
150  10.244.1.30     192.0.2.20      SNMP       snmpV2-trap 1.3.6.1.2.1.1.3.0 ...

Alertmanager (10.244.1.20) posts the alert to the notifier (10.244.1.30). About 3 ms later, the notifier sends one trap to each destination.

Don't be fooled by probes: if your capture only shows GET / HTTP/1.1 every 10 seconds from the node IP, that's the kubelet's liveness/readiness probes, not alerts. Alert deliveries are always POST /alerts.

6. Anatomy of the trap

Expanding the trap in Wireshark:

Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: snmpV2-trap (7)
        variable-bindings: 10 items
            1.3.6.1.2.1.1.3.0: 3629193000
            1.3.6.1.6.3.1.1.4.1.0: 1.3.6.1.4.1.XXXXX.41.1
            1.3.6.1.4.1.XXXXX.41.2.1: "1.3.6.1.4.1.XXXXX.41[alertname=SnmpTestAlert,instance=test-instance,namespace=monitoring,pod=test-pod]"
            1.3.6.1.4.1.XXXXX.41.2.2: "critical"
            1.3.6.1.4.1.XXXXX.41.2.3: 312f3120616c657274732061726520666972696e673a...
            1.3.6.1.4.1.XXXXX.41.2.8: <MISSING>
            1.3.6.1.4.1.XXXXX.41.2.4: "test-pod"
            1.3.6.1.4.1.XXXXX.41.2.5: "test-instance"
            1.3.6.1.4.1.XXXXX.41.2.6: "monitoring"
            1.3.6.1.4.1.XXXXX.41.2.7: <MISSING>
VarbindMeaning
1.3.6.1.2.1.1.3.0sysUpTime
1.3.6.1.6.3.1.1.4.1.0snmpTrapOID: the alert's oid label + .1
<oid>.2.1Alert ID: the OID plus the route's group_by labels
<oid>.2.2Severity (severity label)
<oid>.2.3Description from the description template. Wireshark shows it as hex because it contains newlines; it decodes to "1/1 alerts are firing: …"
<oid>.2.4 – .2.8Extra fields: pod, instance, namespace, host, container

<MISSING> just means the value is empty. The test alert had no host or container label. Add them to the amtool alert add command and fields 7 and 8 are filled in.

7. Troubleshooting cheat sheet

SymptomLikely causeFix / check
No traps from real alerts, but test alerts work Your rules have no oid label, or the rule group carrying it is disabled (e.g. defaultRules.rules.general: false) Enable the group, or add oid/type labels to your PrometheusRules
routes test returns only the default receiver The SNMP route isn't in the loaded config, or the matcher is wrong amtool config routes show (§5.2)
alertmanager_notifications_failed_total{integration="webhook"} increasing Wrong service name or port in the webhook URL, or the notifier pod is down kubectl get svc -n monitoring | grep snmp; Alertmanager logs
Webhook counter goes up, POST visible in pcap, no UDP 162 Notifier problem (template error, bad destination) Notifier logs with --log.level=debug
Pcap shows only GET / every 10 s Those are kubelet probes. The capture started after the alert was delivered Start ksniff before firing the alert
Traps leave the pod but the NMS sees nothing Firewall/routing between the nodes and the NMS, or a community mismatch tcpdump -nn udp port 162 on the NMS; set snmpCommunity/snmpCommunitySecret
Alert stays active after "resolving" --end was in the future (e.g. NOW computed with -d '+1 hour'), or a label differs echo $NOW must be the current UTC time; labels must match exactly
Test alert disappears by itself after ~1 minute No --end given; resolve_timeout: 1m resolves it Pass --end one hour ahead
-bash: syntax error near unexpected token `(' A PowerShell command ((Get-Date)…) was pasted into bash Use the bash date -u … versions above
level=warn msg="Alertmanager is moving to a new parser…" Only a warning: annotation values with spaces aren't double-quoted Wrap as '--annotation=summary="SNMP test alert"'
Resolved trap "missing" It is sent at the next group_interval (default 5 min) Keep capturing for about 5 minutes after resolving
Summary: if amtool config routes test lists snmp-notifications, the webhook counter goes up with no failures, and a capture shows POST /alerts followed by snmpV2-trap packets to your NMS addresses, the kube-prometheus-stack side is working end to end. Anything left is between the cluster and the NMS.

How to deploy MySQL on Kubernetes Cluster ?

Pre-Requisite

  1. kubernetes cluster is ready if not Follow this blog.
kubectl get nodes -o wide

OUTPUT

NAME        STATUS   ROLES           AGE     VERSION    INTERNAL-IP    EXTERNAL-IP   OS-IMAGE                         KERNEL-VERSION         CONTAINER-RUNTIME
kubmaster   Ready    control-plane   5h26m   v1.28.15   192.168.10.6   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-32-cloud-amd64   containerd://1.7.27
kubnode1    Ready    <none>          5h3m    v1.28.15   192.168.10.5   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-35-cloud-amd64   containerd://1.7.27
kubnode2    Ready    <none>          5h2m    v1.28.15   192.168.10.7   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-35-cloud-amd64   containerd://1.7.27

Create Namespace (Optoinal)

Create file kamailio-namespace.yaml

vim kamailio-namespace.yaml

paste the following content

# kamailio-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: kamailio

Apply It

kubectl apply -f kamailio-namespace.yaml

Create Physical Volume for MySQL Database

create file mysql-pv.yaml

vim mysql-pv.yaml

paste the following content in the file

apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-pv
  namespace: kamailio
spec:
  storageClassName: manual
  capacity:
    storage: 3Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data/mysql"

apply it

kubectl apply -f mysql-pv.yaml

confirmation command

kubectl get pv -A
NAME       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                STORAGECLASS   REASON   AGE
mysql-pv   3Gi        RWO            Retain           Available    kamailio/mysql-pvc   manual                  5h16m

Important

Status must be Available

Create ConfigMap

create file mysql-configmap.yaml

vim mysql-configmap.yaml

paste the following content in the file

# mysql-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql-config
  namespace: kamailio
data:
  my.cnf: |
    [mysqld]
    default-authentication-plugin=mysql_native_password
    skip-name-resolve
    max_connections=1000

Create Secret File

create file mysql-secret.yaml

vim mysql-secret.yaml

copy and paste the following content in the file

# mysql-secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: mysql-secrets
  namespace: kamailio
type: Opaque
data:
  mysql-root-password: MTIzNDU2Nw==
  mysql-password: MTIzNDU2Nw==

password must be base64 encrypted

echo -n 1234567 | base64 

OUTPUT

MTIzNDU2Nw==

Create a PersistentVolumeClaim for MySQL Data

create file mysql-pvc.yaml

vim mysql-pvc.yaml

copy and paste the following content in the file

# mysql-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pvc
  namespace: kamailio
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 3Gi

create the MySQL Deployment

create file mysql-deployment.yaml

vim mysql-deployment.yaml

copy and paste the following content in the file

# mysql-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  namespace: kamailio
spec:
  selector:
    matchLabels:
      app: mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
      - name: mysql
        image: mysql:5.7
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secrets
              key: mysql-root-password
        - name: MYSQL_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secrets
              key: mysql-password
        - name: MYSQL_USER
          value: "kamailio"
        - name: MYSQL_DATABASE
          value: "kamailio"
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: mysql-persistent-storage
          mountPath: /var/lib/mysql
        - name: mysql-config
          mountPath: /etc/mysql/conf.d
      volumes:
      - name: mysql-persistent-storage
        persistentVolumeClaim:
          claimName: mysql-pvc
      - name: mysql-config
        configMap:
          name: mysql-config

Create MySQL Service

create file mysql-service.yaml

vim mysql-service.yaml

copy and paste the following content in the file

apiVersion: v1
kind: Service
metadata:
  name: mysql
  namespace: kamailio
spec:
  type: NodePort
  ports:
  - port: 3306
    targetPort: 3306
    nodePort: 30306
  selector:
    app: mysql

Apply all of the files

kubectl apply -f mysql-configmap.yaml -f mysql-secret.yaml -f mysql-pvc.yaml -f mysql-deployment.yaml -f mysql-service.yaml

Check the pod

kubectl get pods -n kamailio

OUTPUT

NAMESPACE         NAME                                       READY   STATUS    RESTARTS   AGE
kamailio          mysql-d4b767577-58v2n                      1/1     Running   0          5h15m

Check PV Status

kubectl get pv -A

OUTPUT

NAME       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                STORAGECLASS   REASON   AGE
mysql-pv   3Gi        RWO            Retain           Bound    kamailio/mysql-pvc   manual                  8m42s

Confirm nameserver IP

kubectl -n kamailio exec -it mysql-5448dbc87f-5gm97 -- cat /etc/resolv.conf

OUTPUT

search kamailio.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5

Add Port Forwarding

kubectl port-forward --address 192.168.10.6 pod/mysql-d4b767577-58v2n -n kamailio 3306:3306

This command will start listening on master node IP 192.168.10.6:3306 and forward all traffic to mysql pod port 3306.

Enjoy 😉

How to configure a Kubernetes Cluster ?

image

Pre-Requisite

  1. Three Linux Machines/VMs (Minimum Specs: 2 cores, 4GB RAM, 16GB Hard Disk)
  2. Can communicate with each other (Preferred to be on Same LAN)
  3. Open ports: 22 (SSH), 6443 (Kubernetes API), 2379-2380 (etcd), 10250 (kubelet)

Linux Server Preparation for Kubernetest Cluster

Update system and install prerequisites

apt update && apt upgrade -y
apt install -y curl gnupg2 software-properties-common apt-transport-https ca-certificates chrony

Disable swap (Kubernetes requirement)

swapoff -a
sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

Enable kernel modules and sysctl params

cat <<EOF | tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF

Load kernel Modules

modprobe overlay
modprobe br_netfilter

set system variables

cat <<EOF | tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward                 = 1
EOF

Load system variables

sysctl --system

Install Docker and Kubernetes

Note

Execute the following steps on all Three Nodes.

Add Docker Repo

curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian bookworm stable" | tee /etc/apt/sources.list.d/docker.list

Update and install Docker

apt update
apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Configure containerd

mkdir -p /etc/containerd
containerd config default | tee /etc/containerd/config.toml

Set cgroup driver to systemd

sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml

Restart containerd

systemctl restart containerd
systemctl enable containerd

Add Kubernetes repo

curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.28/deb/Release.key | gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
echo 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.28/deb/ /' | tee /etc/apt/sources.list.d/kubernetes.list

Install kubelet, kubeadm, kubectl

apt update
apt install -y kubelet kubeadm kubectl
apt-mark hold kubelet kubeadm kubectl

Initiate Kubernetes Cluster

Note

Execute the following commands only on Master Nodes.

Initialize cluster with Calico network (recommended for Debian)

kubeadm init

OR if want to define CIDR do it as below

kubeadm init \
  --pod-network-cidr=192.168.100.0/24 \
  --service-cidr=192.168.101.0/24  # Example: Different CIDR for services

OUTPUT of the above command will guide to executethe further commands

I0522 10:17:11.162566   18880 version.go:256] remote version is much newer: v1.33.1; falling back to: stable-1.28
[init] Using Kubernetes version: v1.28.15
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
W0522 10:17:19.988252   18880 checks.go:835] detected that the sandbox image "registry.k8s.io/pause:3.8" of the container runtime is inconsistent with that used by kubeadm. It is recommended that using "registry.k8s.io/pause:3.9" as the CRI sandbox image.
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local kubmaster] and IPs [10.96.0.1 192.168.10.6]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [kubmaster localhost] and IPs [192.168.10.6 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [kubmaster localhost] and IPs [192.168.10.6 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 6.002958 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node kubmaster as control-plane by adding the labels: [node-role.kubernetes.io/control-plane node.kubernetes.io/exclude-from-external-load-balancers]
[mark-control-plane] Marking the node kubmaster as control-plane by adding the taints [node-role.kubernetes.io/control-plane:NoSchedule]
[bootstrap-token] Using token: oi42uq.qkhghzhbgbekm81a
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] Configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] Configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

Alternatively, if you are the root user, you can run:

  export KUBECONFIG=/etc/kubernetes/admin.conf

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 192.168.10.6:6443 --token oi42uq.qkhghzhbgbekm81a --discovery-token-ca-cert-hash sha256:353a1ad9271fdfc883cf2a7fa47b232580dd10a5fc3dcce11377d79daeed7518

Copy commands from the OUTPUT

mkdir -p $HOME/.kube

sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config

sudo chown (id−u):(id -g) $HOME/.kube/config

kubeadm join 192.168.10.6:6443 --token oi42uq.qkhghzhbgbekm81a --discovery-token-ca-cert-hash sha256:353a1ad9271fdfc883cf2a7fa47b232580dd10a5fc3dcce11377d79daeed7518

Now Execute it in the following order

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

After that Install Calico network plugin

kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/tigera-operator.yaml
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.1/manifests/custom-resources.yaml
kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml

Now Join Master node to cluster

kubeadm join 192.168.10.6:6443 --token oi42uq.qkhghzhbgbekm81a --discovery-token-ca-cert-hash sha256:353a1ad9271fdfc883cf2a7fa47b232580dd10a5fc3dcce11377d79daeed7518

Now Execute the following commands

kubectl get nodes -o wide

OUTPUT

NAME        STATUS   ROLES           AGE     VERSION    INTERNAL-IP    EXTERNAL-IP   OS-IMAGE                         KERNEL-VERSION         CONTAINER-RUNTIME
kubmaster   Ready    control-plane   5h26m   v1.28.15   192.168.10.6   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-32-cloud-amd64   containerd://1.7.27

confirm coreDNS IP as well.

kubectl get svc -n kube-system | grep -E 'kube-dns|coredns'

OUTPUT

kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP,9153/TCP   3m2s

Add node to Kubernetes Cluster

Important

Please make sure that follwoing ports are reachable TCP/6443 Try telnel port 6443

apt install telnet
 telnet 192.168.10.8 6443
Trying 192.168.10.8...
Connected to 192.168.10.8.
Escape character is '^]'.
^]
telnet> quit
Connection closed.

Note

Execute the following commands only on Worker Nodes.

Go to each Node and execute the following command

kubeadm join 192.168.10.6:6443 --token oi42uq.qkhghzhbgbekm81a --discovery-token-ca-cert-hash sha256:353a1ad9271fdfc883cf2a7fa47b232580dd10a5fc3dcce11377d79daeed7518

Execute the follwoing command again on Master Node

kubectl get nodes -o wide

OUTPUT

NAME        STATUS   ROLES           AGE     VERSION    INTERNAL-IP    EXTERNAL-IP   OS-IMAGE                         KERNEL-VERSION         CONTAINER-RUNTIME
kubmaster   Ready    control-plane   5h26m   v1.28.15   192.168.10.6   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-32-cloud-amd64   containerd://1.7.27
kubnode1    Ready    <none>          5h3m    v1.28.15   192.168.10.5   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-35-cloud-amd64   containerd://1.7.27
kubnode2    Ready    <none>          5h2m    v1.28.15   192.168.10.7   <none>        Debian GNU/Linux 12 (bookworm)   6.1.0-35-cloud-amd64   containerd://1.7.27

Troubleshooting

Commands which can help in troubleshooting Check Logs

journalctl -u kubelet -f

Check if system pods are working fine

kubectl get pods -n kube-system 

OUTPUT

NAME                                       READY   STATUS    RESTARTS   AGE
calico-kube-controllers-658d97c59c-gvn5s   1/1     Running   0          5h21m
calico-node-hw42j                          1/1     Running   0          5h21m
calico-node-p55zs                          1/1     Running   0          5h11m
calico-node-qdwlh                          1/1     Running   0          5h12m
coredns-5dd5756b68-r85lr                   1/1     Running   0          5h35m
coredns-5dd5756b68-zxsss                   1/1     Running   0          5h35m
etcd-kubmaster                             1/1     Running   0          5h35m
kube-apiserver-kubmaster                   1/1     Running   0          5h35m
kube-controller-manager-kubmaster          1/1     Running   0          5h35m
kube-proxy-cllll                           1/1     Running   0          5h12m
kube-proxy-pkxcp                           1/1     Running   0          5h11m
kube-proxy-s5c2c                           1/1     Running   0          5h35m
kube-scheduler-kubmaster                   1/1     Running   0          5h35m

Check if thee are any errors in containerd

systemctl status containerd
crictl ps  # Verify container runtime

How to Reset Master Node

Drain all Worker Nodes

for node in $(kubectl get nodes -o name | grep -v master); do
  kubectl drain $node --ignore-daemonsets --delete-emptydir-data
done

Stop Control Plane Services

sudo kubeadm reset -f
sudo systemctl stop kubelet
sudo systemctl stop docker

How to Reset a Worker Node

sudo kubeadm reset
sudo rm -rf /etc/kubernetes/
sudo rm -rf /var/lib/kubelet/
sudo rm -rf /var/lib/etcd/
sudo rm -rf $HOME/.kube

sudo iptables -F
sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -X

sudo systemctl stop kubelet
sudo systemctl disable kubelet
sudo systemctl stop docker || sudo systemctl stop containerd
sudo systemctl daemon-reload

confirm that there is no servce listening on port 10250

sudo netstat -tulnp | grep 10250

For Next Steps use this link

Enjoy 😉

Sending Prometheus Alerts as SNMP Traps with kube-prometheus-stack

Many operators still run an SNMP-based NMS for alarm management. If your Kubernetes monitoring is built on kube-prometheus-stack , you c...