Ubuntu 上搭建与配置 Kubernetes 网络的实用指南
一 环境准备与内核网络
示例命令(在所有节点执行基础网络与内核设置):
# 关闭 Swap
sudo swapoff -a
sudo sed -i '/swap/s/^/#/' /etc/fstab
# 主机名与 hosts(示例)
echo "192.168.65.128 master" | sudo tee -a /etc/hosts
echo "192.168.65.129 node1" | sudo tee -a /etc/hosts
echo "192.168.65.130 node2" | sudo tee -a /etc/hosts
# 内核模块与 sysctl
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF
sudo modprobe overlay
sudo modprobe br_netfilter
cat <<EOF | sudo 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
sudo sysctl --system
# Docker 与 cgroup 驱动
sudo apt-get update && sudo apt-get install -y docker.io
sudo mkdir -p /etc/docker
cat <<EOF | sudo tee /etc/docker/daemon.json
{
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "json-file",
"log-opts": { "max-size": "100m" },
"storage-driver": "overlay2"
}
EOF
sudo systemctl enable --now docker
# 安装并固定 kubeadm/kubelet/kubectl(示例版本)
sudo apt-get update
sudo apt-get install -y kubelet=1.28.2-00 kubeadm=1.28.2-00 kubectl=1.28.2-00
sudo apt-mark hold kubelet kubeadm kubectl
说明:以上为 Ubuntu 20.04/22.04 常见做法,生产环境请结合内核安全策略与合规要求调整防火墙与日志策略。
二 选择并部署网络插件
示例命令(任选其一)
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
kubectl apply -f https://docs.projectcalico.org/manifests/tigera-operator.yaml
kubectl apply -f https://docs.projectcalico.org/manifests/custom-resources.yaml
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium --namespace kube-system
提示:若使用 Flannel,其默认后端为 VXLAN;如需自定义 Pod CIDR,请修改清单中的 Network 字段后再部署。
三 验证与连通性测试
示例命令
# 等待节点就绪
kubectl get nodes
# 等待网络插件就绪(示例标签)
kubectl get pods -n kube-system -l app=flannel
# 部署测试应用
kubectl run nginx --image=nginx:1.25 --port=80 --restart=Never
kubectl expose pod nginx --port=80 --type=NodePort
# 验证访问
kubectl get pod nginx -o wide
kubectl get svc nginx
curl -I http://<任一节点IP>:<NodePort>
说明:若测试失败,优先检查节点 Ready 状态、插件 Pod 状态与 Pod CIDR 是否与插件配置一致。
四 常见问题与排查清单