公网K8s集群使用Cilium网络插件开启VXLAN+WireGuard隧道加密模式
·
环境及组件版本说明:
- 操作系统:Ubuntu 22.04.5 LTS
- 网络环境:K8s公网集群,节点间通过公网IP互通
- Kubernetes:v1.33.4(Latest)
- Containerd:v2.1.4(Latest)
转载说明:
- 原创内容,请注明出处
1. 使用Helm安装
# 安装最新版Helm,超时可以多重试几次
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
# 添加Cilium Helm仓库
helm repo add cilium https://helm.cilium.io/
helm repo update
# 安装Cilium
helm install cilium cilium/cilium \
--version 1.18.1 \
--namespace kube-system \
--set kubeProxyReplacement=false \
--set k8sServiceHost=$(hostname -i) \ # 你的控制平面公网IP
--set k8sServicePort=6443 \
--set ipam.mode=kubernetes \
--set operator.replicas=1 \
--set tunnelProtocol=vxlan
2. 启用加密
相比IPsec,我们选择轻量,性能更好的WireGuard技术
2.1. 安装WireGuard内核模块
有关如何在 Linux 发行版上安装内核模块的详细信息,请参阅WireGuard 安装
# 安装内核
sudo apt install wireguard
# 加载wireguard模块
sudo modprobe wireguard
# 持久化配置wireguard模块
sudo tee -a /etc/modules-load.d/k8s.conf <<EOF
wireguard
EOF
# 应用 sysctl 参数而不重新启动
sudo sysctl --system
# 验证wireguard模块是否已经加载
cat /boot/config-$(uname -r) | grep CONFIG_WIREGUARD=m
2.2. 更新Cilium配置
# 启用Pod流量加密
helm upgrade cilium cilium/cilium \
--version 1.18.1 \
--namespace kube-system \
--reuse-values \
--set encryption.enabled=true \
--set encryption.type=wireguard
2.3. 查看WireGuard内核日志
# 启用动态调试(临时,重启后失效)
echo "module wireguard +p" | sudo tee /sys/kernel/debug/dynamic_debug/control
# 使用 dmesg 跟踪日志
sudo dmesg -wH
2.4. WireGuard通道异常问题
因为我搭建的是公网集群,cilium 的 allowed ips 是自动维护的,无法加载到我的内网IP, Cilium这块应该给出更好的方案(可以自己提个PR试试增加这个特性)。
目前的解决方案是,在 每个节点 用脚本定时更新WireGuard的allowed ips,定时执行可以屏蔽掉服务器重启造成的影响,最坏造成重启后2分钟网络瘫痪的影响(学习环境可接受),当然你也可以适时手动执行
2.4.1. 更新脚本
TIPs: 务必根据你的集群情况修改脚本的 NEW_ALLOWED_IPS 常量
$ cat wireguard_allowed_ips_updater.sh
--- 脚本内容如下
#!/bin/bash
# 声明常量
WG_INTERFACE="cilium_wg0" # WireGuard接口名称
NEW_ALLOWED_IPS=("10.1.94.3" "80.153.22.119") # 填入所有其他节点的内网IP和公网IP
# 获取当前时间
current_time=$(date +'%Y-%m-%d %H:%M:%S')
echo "[$current_time] 开始执行WireGuard allowed-ips更新脚本"
# 查询当前WireGuard接口的全部peer信息
sudo wg show $WG_INTERFACE
# 检查命令是否执行成功
if [ $? -ne 0 ]; then
echo "[$current_time] 错误:查询WireGuard接口失败"
exit 1
fi
# 获取peer的public key
PEER_PUBLIC_KEY=$(sudo wg show $WG_INTERFACE | grep -A 4 "peer:" | head -n 1 | awk '{print $2}')
echo "[$current_time] 成功获取peer的public key: $PEER_PUBLIC_KEY"
# 构建allowed-ips配置
allowed_ips_args=""
for ip in "${NEW_ALLOWED_IPS[@]}"; do
allowed_ips_args+=" allowed-ips $ip"
done
# 更新peer的allowed-ips配置
sudo wg set $WG_INTERFACE peer $PEER_PUBLIC_KEY $allowed_ips_args
# 检查更新是否成功
if [ $? -eq 0 ]; then
echo "[$current_time] 成功更新peer $PEER_PUBLIC_KEY 的allowed-ips为: ${NEW_ALLOWED_IPS[*]}"
else
echo "[$current_time] 错误:更新peer $PEER_PUBLIC_KEY 的allowed-ips失败"
exit 1
fi
2.4.2. crontab 任务
$ crontab -e
# 增加如下行,每两分钟执行一次
*/2 * * * * bash /home/ubuntu/wireguard_allowed_ips_updater.sh
创作不易,希望大家多多支持,文章持续更新,我们下期见.
程序员白话 | [原创]
点关注不迷路
可以抖音搜索「程序员白话」,大家有任何问题都可以私聊我,知无不言~
更多推荐


所有评论(0)