如何选择防火墙
一般来讲:
rhel7或以下,选择iptables;
rhel8或以上,可以采用firewalld,使用iptables也是可以的,但两者选其一即可。
如果有docker、k8s等紧密依赖iptables的环境,建议采用iptables,禁用firewalld,请把这个配置写入新系统初始配置中。
ubuntu22仍然可保持采用iptables。
禁用firewalld
#停止firewalld服务
systemctl stop firewalld
#禁用firewalld服务
systemctl mask firewalld
启用iptables
yum install -y iptables
yum install -y iptables-services
systemctl enable iptables.service
systemctl start iptables.service
保存经验
默认保存位置:/etc/sysconfig/iptables
两种常见保存方式:
- 方式一
service iptables save #安装了iptables套件后才有效,默认保存位置:/etc/sysconfig/iptables,iptables套件配置文件是/etc/sysconfig/iptables-config - 方式二
iptables-save -c > /etc/sysconfig/iptables #没有安装iptables套件也可执行,参数-c是保存计数
保存为不同版本的示例
iptables-save > ipt.v1.0 #版本保存
iptables-restore < ipt.v1.0 #恢复
datetime=$(date +%Y%m%d-%H%M%S)
iptables-save -c > /etc/sysconfig/iptables_${datetime} #以时间为版本保存
iptables-restore -c < /etc/sysconfig/iptables_${datetime}
在多人管理的工作环境中,采用同一脚本去管理iptables是非常推荐的做法,但如果确实混乱不堪,维护好/etc/sysconfig/iptables是最好的选择。参考常规简易配置综合脚本范例
在iptables和firewalld共存的系统,比如rhel7系列,但又没有安装iptables套件,或采用了firewalld和iptables共同管理防火墙,造成了iptables策略混乱,这时候可用iptables-save命令保存策略,不过这时可能更应该考虑采用firewalld去管理iptables
2024年实践中发现,k8s的网络插件calico管理的iptables策略可能造成iptables-save命令也无法完整保存策略,这需要根据生产场景来制定应对方案,以避免重启后策略丢失。
通过自定义链并写入开机启动的解决案例
#!/bin/bash
###################################
# function iptables防火墙因服务不正常而采用的临时处置
#
# 参考创建或使用示例: mkdir -p /root/sh/log; touch /root/sh/iptables\_for\_tmp.sh; chmod a+x /root/sh/iptables\_for\_tmp.sh
#
# if (! grep -q iptables\_for\_tmp /etc/rc.local); then echo '/root/sh/iptables\_for\_tmp.sh >> /root/sh/log/iptables\_for\_tmp.log 2>&1' >> /etc/rc.local; else echo "This script already exists in /etc/rc.local"