CentOS环境下Kubernetes(K8s)最佳实践案例
在CentOS上部署K8s前,需完成系统级别的安全与性能优化,确保集群稳定性:
firewalld(systemctl stop firewalld && systemctl disable firewalld),避免端口冲突;禁用SELinux(sed -i 's/enforcing/disabled/' /etc/selinux/config && setenforce 0),防止权限限制导致组件无法正常运行;关闭Swap分区(swapoff -a并注释/etc/fstab中的swap行),提升K8s性能。master、node1,使用hostnamectl set-hostname命令),并在所有节点的/etc/hosts文件中添加集群内部IP与主机名映射(如192.168.1.10 master),确保节点间通过主机名通信。chrony服务(yum install chrony -y && systemctl enable chrony && systemctl start chrony),同步所有节点时间,避免因时间不一致导致的组件异常(如etcd数据不一致)。为实现K8s集群的高可用,需重点配置多Master节点与负载均衡:
master1、master2、master3),每个节点执行kubeadm init初始化命令(指定--apiserver-advertise-address为当前节点IP、--pod-network-cidr为Pod网段,如10.244.0.0/16),生成集群配置。HAProxy+Keepalived搭建Master节点的高可用负载均衡: yum install haproxy -y),编辑/etc/haproxy/haproxy.cfg,添加前端监听端口(如16443)和后端Master节点列表(如server master1 192.168.1.10:6443 check、server master2 192.168.1.11:6443 check),实现流量分发。yum install keepalived -y),配置虚拟IP(VIP,如192.168.1.200),通过VRRP协议实现Master节点故障时的VIP漂移,确保API Server的高可用。K8s集群的网络通信依赖CNI插件,同时需通过网络策略限制Pod间流量:
kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml命令部署,实现Pod间、Pod与节点间的网络互通。NetworkPolicy资源限制Pod间通信(如仅允许同一Namespace下的frontend Pod访问backend Pod),提升集群安全性。示例策略:apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: frontend-to-backend namespace: default spec: podSelector: matchLabels: app: backend ingress: - from: - podSelector: matchLabels: app: frontend K8s集群的安全需覆盖系统层、集群层、应用层三个维度:
yum update更新系统,kubeadm upgrade更新K8s),修复已知漏洞。kubelet参数(修改/var/lib/kubelet/config.yaml),启用readOnlyRootFilesystem(容器根目录只读)、allowPrivilegeEscalation: false(禁止提权),限制容器权限。kubeadm init时自动配置),使用RBAC(基于角色的访问控制)限制用户权限(如开发人员仅能访问dev Namespace,管理员拥有集群管理权限)。/etc/kubernetes/manifests/etcd.yaml,添加--encryption-provider-config=/etc/kubernetes/encryption-config.yaml参数),保护Secret数据。Trivy扫描镜像漏洞(如trivy image centos:7),阻断高风险镜像入集群;镜像内避免存储敏感信息(如密码、密钥),使用ConfigMap或Secret管理配置。Secret存储敏感信息(如数据库密码),并通过Vault CSI驱动实现动态密钥注入(避免Secret硬编码在Pod中)。有效的监控与运维是K8s集群长期稳定运行的关键:
Prometheus+Grafana搭建集群监控体系(Prometheus采集节点、Pod、etcd等指标,Grafana可视化展示),配置告警规则(如节点宕机、Pod重启次数超过阈值),及时发现异常。EFK(Elasticsearch+Fluentd+Kibana)堆栈收集集群日志(Fluentd采集节点日志,Elasticsearch存储,Kibana可视化),方便排查应用故障(如容器崩溃日志、访问日志)。etcdctl snapshot save命令,如etcdctl snapshot save /backup/etcd-snapshot.db),并测试恢复流程(使用etcdctl snapshot restore恢复数据),确保数据安全。应用部署时需遵循标准化与高可用原则:
Deployment资源管理应用(而非直接创建Pod),设置replicas(副本数≥2,确保高可用)、resources.requests/limits(CPU/内存请求与限制,避免资源争抢)、livenessProbe(存活探针,检测应用是否健康,如curl -f http://localhost:8080/health)、readinessProbe(就绪探针,检测应用是否可接收流量,如curl -f http://localhost:8080/ready)。ConfigMap中(kubectl create configmap my-config --from-file=config.properties),通过volumeMount挂载到Pod;敏感信息(如数据库密码)存储在Secret中(kubectl create secret generic db-password --from-literal=password=123456),通过环境变量或volumeMount注入。replicas≥2,并通过affinity规则(如podAntiAffinity)将Pod分散到不同节点(避免单节点故障导致多个Pod不可用),提升应用可用性。