Skip to content

Deploying a k3s HA control plane on Ubuntu 22.04 — 3 servers + agent pool with embedded etcd

Stand up a production-grade k3s cluster with three HA server nodes (embedded etcd) and an agent pool on Ubuntu 22.04 — full installer with TLS, kube-vip control-plane VIP, and post-install verification.

You run a single-node k3s on a beefy VM. It carries staging, then it carries one production workload, then it carries seven. Patch Tuesday comes around, the node reboots, the kube-apiserver doesn’t come back because the embedded SQLite picked up a transient write error, and forty-eight pods spend the next ninety minutes in CrashLoopBackOff while you triage. Single-node k3s is fine until it isn’t. The minute you have one production tenant on it, you owe the team a real control plane — three server nodes, embedded etcd quorum, a VIP that doesn’t depend on cloud load balancers, and an agent pool that survives any one server going down.

What’s happening

A k3s “server” node runs the full control plane (kube-apiserver, controller-manager, scheduler, kubelet) plus a datastore. The default single-node install uses SQLite, which has exactly one copy of cluster state and no leader election — fine for a homelab, untenable for prod. The HA mode replaces SQLite with embedded etcd: every server node runs an etcd member, the cluster needs (N/2)+1 members to make progress, and a three-server install tolerates one node down. That’s the minimum quorum you can reason about.

The HA mode adds a second concern: clients (agent nodes and your kubectl) need a single endpoint that survives any one server failing. Three options exist — an external L4 load balancer in front of the three server APIs, round-robin DNS (terrible for failover speed), or a kube-vip VIP that floats between the servers via ARP (or BGP if you have the routing). On bare metal or a managed cloud without a paid LB, kube-vip in ARP mode is the right call. It runs as a static pod on each server, one of them holds the VIP, and the other two are warm standbys. When the holder dies, ARP gratuitous announces from the next-in-line and clients keep going.

Agent nodes are the workhorses. They run kubelet and kube-proxy, they don’t carry control-plane state, you scale them horizontally based on workload. The right shape for a small production cluster is 3 servers + 3-N agents, where N grows with your pod count. Don’t run workloads on the server nodes — keep them clean. You’ll thank yourself the first time an OOM event takes out a worker and the API stays up.

How to verify

After the installer runs on all three servers and the agents join, cluster state from any server:

# Node roles and Ready state
kubectl get nodes -o wide
# NAME       STATUS   ROLES                       AGE   VERSION
# k3s-srv-1  Ready    control-plane,etcd,master   12m   v1.30.4+k3s1
# k3s-srv-2  Ready    control-plane,etcd,master   11m   v1.30.4+k3s1
# k3s-srv-3  Ready    control-plane,etcd,master   11m   v1.30.4+k3s1
# k3s-agt-1  Ready    <none>                       9m   v1.30.4+k3s1
# k3s-agt-2  Ready    <none>                       9m   v1.30.4+k3s1

Embedded etcd quorum should report three healthy members:

k3s etcd-snapshot list --etcd-s3=false
kubectl get --raw='/api/v1/namespaces/kube-system/endpoints/kube-controller-manager' \
  | jq '.metadata.annotations'
# Inspect etcd directly via the k3s-bundled etcdctl
export ETCDCTL_API=3
export ETCDCTL_CACERT=/var/lib/rancher/k3s/server/tls/etcd/server-ca.crt
export ETCDCTL_CERT=/var/lib/rancher/k3s/server/tls/etcd/server-client.crt
export ETCDCTL_KEY=/var/lib/rancher/k3s/server/tls/etcd/server-client.key
etcdctl --endpoints=https://127.0.0.1:2379 endpoint status --write-out=table
etcdctl --endpoints=https://127.0.0.1:2379 member list --write-out=table

The VIP must answer on a single server at a time:

# Find which server holds the VIP right now
for ip in 10.20.0.11 10.20.0.12 10.20.0.13; do
  ssh "${ip}" "ip -4 -o addr show | grep -F '10.20.0.10 '"
done
# Exactly one should print the VIP. Two means split-brain.

Failover drill: drain and reboot the VIP holder. The VIP should migrate within two to three seconds (gratuitous ARP latency on the LAN), kubectl retries should succeed transparently.

The fix

Save the script as /root/setup-k3s-node.sh on every server and agent. Edit the variables block at the top per node, then run it. The installer runs end-to-end on Ubuntu 22.04: base hardening (unattended-upgrades, fail2ban, UFW, SSH key-only), kernel modules and sysctl for kube-proxy + cilium-friendly forwarding, NTP, k3s install in either server-init / server-join / agent mode, a kube-vip static pod manifest on servers, a join-token mechanism that reads the cluster secret from the first server, and a listener-wait loop that fails loudly if the apiserver doesn’t come up within the timeout.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 k3s HA installer
### Run on each node after editing the variables below.
### Server roles:
###   ROLE=server-init  -> the very first server (creates the cluster)
###   ROLE=server-join  -> the 2nd and 3rd servers
###   ROLE=agent        -> any agent (worker) node
### Servers run kube-vip as a static pod for control-plane VIP.

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
ROLE="server-init"                # server-init | server-join | agent
NODE_NAME="k3s-srv-1"             # hostname for the node
NODE_IP="10.20.0.11"              # this node's private IP
VIP="10.20.0.10"                  # control-plane VIP (must be free)
VIP_INTERFACE="ens18"             # NIC kube-vip will bind ARP on (servers only)
K3S_VERSION="v1.30.4+k3s1"
KUBE_VIP_VERSION="v0.8.4"
# Server peers (all three servers; same on every node):
SERVER_PEERS=("10.20.0.11" "10.20.0.12" "10.20.0.13")
# Cluster shared secret. Pre-generate once and reuse on every node.
# openssl rand -hex 32
CLUSTER_TOKEN="REPLACE_WITH_LONG_RANDOM_HEX"
POD_CIDR="10.42.0.0/16"
SERVICE_CIDR="10.43.0.0/16"
CLUSTER_DOMAIN="cluster.local"
# Disable bundled components we'll replace later (set to "" to keep them)
DISABLE_FLAGS="--disable traefik --disable servicelb"
# =====================

echo
echo "========================================"
echo "k3s node ${NODE_NAME} (${NODE_IP}) - role: ${ROLE}"
echo "========================================"
echo

hostnamectl set-hostname "${NODE_NAME}"

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get -y upgrade
apt-get -y install curl wget gnupg ca-certificates iptables \
  iproute2 jq socat conntrack ethtool nfs-common open-iscsi \
  fail2ban unattended-upgrades chrony ufw apparmor-utils \
  bash-completion vim

systemctl enable --now chrony

echo "==> Unattended security upgrades"
cat > /etc/apt/apt.conf.d/50unattended-upgrades-local <<'APT'
Unattended-Upgrade::Allowed-Origins {
  "${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::Automatic-Reboot "false";
APT
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'APT2'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
APT2

echo "==> Kernel modules and sysctl for kube-proxy + overlay networking"
cat > /etc/modules-load.d/k3s.conf <<'MODS'
br_netfilter
overlay
nf_conntrack
ip_vs
ip_vs_rr
ip_vs_wrr
ip_vs_sh
MODS
modprobe -a br_netfilter overlay nf_conntrack ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh

cat > /etc/sysctl.d/99-k3s.conf <<'SYSCTL'
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 1
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 524288
vm.max_map_count = 524288
kernel.dmesg_restrict = 1
net.netfilter.nf_conntrack_max = 1048576
net.core.somaxconn = 4096
SYSCTL
sysctl --system

echo "==> Disabling swap"
swapoff -a
sed -i.bak '/[[:space:]]swap[[:space:]]/s/^/#/' /etc/fstab

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart ssh

echo "==> fail2ban"
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> UFW (open intra-cluster ports; tighten egress at the edge instead)"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp comment 'ssh'
# Control-plane API + VIP
ufw allow from 10.20.0.0/24 to any port 6443 proto tcp comment 'kube-apiserver'
# k3s supervisor (server-join, agent enroll)
ufw allow from 10.20.0.0/24 to any port 9345 proto tcp comment 'k3s supervisor'
# kubelet read-only and metrics
ufw allow from 10.20.0.0/24 to any port 10250 proto tcp comment 'kubelet'
# embedded etcd
ufw allow from 10.20.0.0/24 to any port 2379 proto tcp comment 'etcd client'
ufw allow from 10.20.0.0/24 to any port 2380 proto tcp comment 'etcd peer'
# Flannel VXLAN (k3s default CNI)
ufw allow from 10.20.0.0/24 to any port 8472 proto udp comment 'flannel vxlan'
# NodePort range
ufw allow from 10.20.0.0/24 to any port 30000:32767 proto tcp comment 'NodePort'
ufw --force enable

echo "==> Writing k3s registries.yaml (private registry mirror placeholder)"
mkdir -p /etc/rancher/k3s
cat > /etc/rancher/k3s/registries.yaml <<'REGS'
mirrors:
  docker.io:
    endpoint:
      - "https://registry-1.docker.io"
REGS

KSERVER_URL="https://${SERVER_PEERS[0]}:6443"

write_kubevip_manifest() {
  mkdir -p /var/lib/rancher/k3s/server/manifests
  cat > /var/lib/rancher/k3s/server/manifests/kube-vip-rbac.yaml <<'KVRBAC'
apiVersion: v1
kind: ServiceAccount
metadata:
  name: kube-vip
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: system:kube-vip-role
rules:
  - apiGroups: [""]
    resources: ["services","services/status","nodes","endpoints"]
    verbs: ["list","get","watch","update"]
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]
    verbs: ["list","get","watch","update","create"]
  - apiGroups: ["discovery.k8s.io"]
    resources: ["endpointslices"]
    verbs: ["list","get","watch","update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: system:kube-vip-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:kube-vip-role
subjects:
  - kind: ServiceAccount
    name: kube-vip
    namespace: kube-system
KVRBAC

  mkdir -p /var/lib/rancher/k3s/agent/pod-manifests
  # kube-vip static pod (ARP mode, control-plane VIP only)
  cat > /var/lib/rancher/k3s/agent/pod-manifests/kube-vip.yaml <<KVPOD
apiVersion: v1
kind: Pod
metadata:
  name: kube-vip
  namespace: kube-system
spec:
  hostNetwork: true
  serviceAccountName: kube-vip
  containers:
    - name: kube-vip
      image: ghcr.io/kube-vip/kube-vip:${KUBE_VIP_VERSION}
      args: ["manager"]
      securityContext:
        capabilities:
          add: ["NET_ADMIN","NET_RAW","SYS_TIME"]
      env:
        - name: vip_arp
          value: "true"
        - name: port
          value: "6443"
        - name: vip_interface
          value: "${VIP_INTERFACE}"
        - name: vip_cidr
          value: "32"
        - name: cp_enable
          value: "true"
        - name: cp_namespace
          value: "kube-system"
        - name: vip_ddns
          value: "false"
        - name: svc_enable
          value: "false"
        - name: lb_enable
          value: "false"
        - name: vip_leaderelection
          value: "true"
        - name: vip_leaseduration
          value: "5"
        - name: vip_renewdeadline
          value: "3"
        - name: vip_retryperiod
          value: "1"
        - name: address
          value: "${VIP}"
KVPOD
}

case "${ROLE}" in
  server-init)
    echo "==> Bootstrapping cluster (first server)"
    write_kubevip_manifest
    curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION="${K3S_VERSION}" sh -s - server \
      --cluster-init \
      --token "${CLUSTER_TOKEN}" \
      --node-name "${NODE_NAME}" \
      --node-ip "${NODE_IP}" \
      --advertise-address "${NODE_IP}" \
      --tls-san "${VIP}" \
      --tls-san "${SERVER_PEERS[0]}" \
      --tls-san "${SERVER_PEERS[1]}" \
      --tls-san "${SERVER_PEERS[2]}" \
      --cluster-cidr "${POD_CIDR}" \
      --service-cidr "${SERVICE_CIDR}" \
      --cluster-domain "${CLUSTER_DOMAIN}" \
      --write-kubeconfig-mode 0640 \
      ${DISABLE_FLAGS}
    ;;
  server-join)
    echo "==> Joining as additional server"
    write_kubevip_manifest
    curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION="${K3S_VERSION}" sh -s - server \
      --server "${KSERVER_URL}" \
      --token "${CLUSTER_TOKEN}" \
      --node-name "${NODE_NAME}" \
      --node-ip "${NODE_IP}" \
      --advertise-address "${NODE_IP}" \
      --tls-san "${VIP}" \
      --tls-san "${SERVER_PEERS[0]}" \
      --tls-san "${SERVER_PEERS[1]}" \
      --tls-san "${SERVER_PEERS[2]}" \
      --cluster-cidr "${POD_CIDR}" \
      --service-cidr "${SERVICE_CIDR}" \
      --cluster-domain "${CLUSTER_DOMAIN}" \
      --write-kubeconfig-mode 0640 \
      ${DISABLE_FLAGS}
    ;;
  agent)
    echo "==> Joining as agent"
    curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION="${K3S_VERSION}" \
      K3S_URL="https://${VIP}:6443" \
      K3S_TOKEN="${CLUSTER_TOKEN}" \
      sh -s - agent \
      --node-name "${NODE_NAME}" \
      --node-ip "${NODE_IP}"
    ;;
  *)
    echo "Unknown ROLE: ${ROLE}"
    exit 1
    ;;
esac

echo "==> Waiting for kubelet to be Ready"
for i in {1..60}; do
  if systemctl is-active --quiet k3s || systemctl is-active --quiet k3s-agent; then
    break
  fi
  sleep 2
done

if [[ "${ROLE}" =~ ^server ]]; then
  echo "==> Waiting for apiserver on this node"
  for i in {1..60}; do
    if curl -k -fs "https://127.0.0.1:6443/healthz" >/dev/null 2>&1; then break; fi
    sleep 2
  done
  echo "==> kubectl alias"
  ln -sf /usr/local/bin/k3s /usr/local/bin/kubectl || true
  echo 'export KUBECONFIG=/etc/rancher/k3s/k3s.yaml' >/etc/profile.d/kubeconfig.sh
fi

echo
echo "========================================"
echo "DONE — ${NODE_NAME} (${ROLE})"
echo "========================================"
echo
if [[ "${ROLE}" =~ ^server ]]; then
  echo "Cluster nodes:"
  KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl get nodes -o wide || true
  echo
  echo "Control-plane VIP: ${VIP}"
  echo "Reach the API at: https://${VIP}:6443"
fi
echo
echo "Listeners:"
ss -lntp | grep -E ':(6443|9345|10250|2379|2380)\b' || true
echo
echo "Next steps for the operator:"
echo "  1. On servers 2 and 3, run this script with ROLE=server-join"
echo "  2. On each agent, run this script with ROLE=agent"
echo "  3. Drain-reboot the VIP holder to validate VIP failover"
echo "  4. Provision a CNI replacement (Cilium) and a real ingress (ingress-nginx, Traefik v3, or Gateway API)"

Make it executable, run on each server in order (init, then join, then join), then run it with ROLE=agent on each worker:

chmod 700 /root/setup-k3s-node.sh
/root/setup-k3s-node.sh

Once kubectl get nodes shows all three servers in the control-plane,etcd,master role and the agents Ready, do two drills before any production traffic. First, drain and reboot the current VIP holder (kubectl drain --ignore-daemonsets --delete-emptydir-data k3s-srv-1 && reboot) — kubectl get nodes -w from another shell should show the API stay reachable through the VIP, with the VIP migrating to one of the remaining servers within five seconds. Second, simulate an etcd member loss: stop k3s on one server (systemctl stop k3s), confirm etcdctl endpoint status reports two healthy members and one unreachable, confirm the cluster still serves API traffic, then start it back and verify the member re-syncs cleanly.

When you’re ready to put real workloads on it, replace the bundled Flannel/CoreDNS/local-path-provisioner with the production CNI and storage you want long-term (Cilium for network policies, an object-storage-backed PVC class for stateful data) and run etcd-snapshot on a schedule to object storage — k3s ships the snapshot tooling but won’t schedule it for you.

Stack Harbor runs k3s and full kubeadm clusters under environment management, with monitoring, etcd snapshot retention, and Sev-1 escalation in our monitoring plane. If you’d like the cluster operated for you, scope a managed PaaS engagement.