K8S 节点初始化一键脚本(禁用 SELinux + 关闭 swap + 开启 ipvs 亲测实用)
文章目录
- 1. 关闭SELinux命令解释
- 1. 1、修改后效果
- 1. 2、修改后需要重启
- 1. 3、立即临时关闭(无需重启)
- 2. 完整脚本
- 2. 1、k8s-init.sh
- 2. 2、使用方法
1. 关闭SELinux命令解释
sed -i 's/enforcing/disabled/' /etc/selinux/config#-i → 直接修改文件(in-place)
# s/enforcing/disabled/ → 查找第一个 enforcing 替换为 disabled
#/etc/selinux/config → SELinux 主配置文件
1. 1、修改后效果
修改前:
SELINUX=enforcing
SELINUXTYPE=targeted
修改后:
SELINUX=disabled
SELINUXTYPE=targeted
1. 2、修改后需要重启
改了这个文件 必须重启服务器 才能生效:
reboot
1. 3、立即临时关闭(无需重启)
如果你只是临时关闭 SELinux(重启后会恢复),可以用:
setenforce 0
检查状态:
getenforce
2. 完整脚本
一键禁用 SELinux + 关闭 swap + 开启 ipvs 的 K8S 前置环境准备脚本;下面是一个 K8S 节点初始化一键脚本,直接在 CentOS / RHEL / Rocky / AlmaLinux 系统上运行,就能完成如下功能:
-
永久禁用 SELinux
-
关闭 swap(并永久禁用)
-
开启 ipvs 转发(并开机自动加载)
2. 1、k8s-init.sh
#!/bin/bash
# ==========================================
# K8S 节点前置环境准备脚本
# 适用系统: CentOS / RHEL / Rocky / AlmaLinux
# ==========================================echo "[1/6] 关闭 SELinux..."
setenforce 0 2>/dev/null
sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
sed -i 's/^SELINUX=permissive/SELINUX=disabled/' /etc/selinux/config
echo " -> SELinux 已禁用,重启后生效"echo "[2/6] 关闭 swap..."
swapoff -a
sed -ri 's/(.*swap.*)/#\1/' /etc/fstab
echo " -> swap 已关闭并永久禁用"echo "[3/6] 开启 IPVS 转发模块..."
mkdir -p /etc/sysconfig/modules
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack
EOFchmod +x /etc/sysconfig/modules/ipvs.modules
bash /etc/sysconfig/modules/ipvs.modules
echo " -> IPVS 模块已加载"echo "[4/6] 检查 IPVS 模块是否生效..."
lsmod | grep -e ip_vs -e nf_conntrackecho "[5/6] 优化内核参数..."
cat > /etc/sysctl.d/k8s.conf <<EOF
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF
sysctl --systemecho "[6/6] 确保模块自动加载服务运行..."
systemctl enable --now systemd-modules-load.serviceecho "✅ 节点初始化完成,可以进行 K8S 安装了!"
2. 2、使用方法
保存脚本为:
vim k8s-init.sh
粘贴上面内容,保存退出。
赋予执行权限并运行:
chmod +x k8s-init.sh
运行脚本
./k8s-init.sh
最好重启一次(保证生效):
reboot
“人的一生会经历很多痛苦,但回头想想,都是传奇”。