TencentOS Server 3.1 如何配置iptables防火墙规则?

在 TencentOS Server 3.1 (TencentOS Server 3, TOS3) 中,配置 iptables 防火墙规则需要特别注意其与系统默认安全机制的交互。TOS3 默认启用了 firewalld(基于 netfilter)作为主要的动态防火墙管理工具,并且底层内核可能加载了 eBPF 或 CNI 网络插件(特别是在容器化环境中)。

因此,直接操作 iptables 是可行的,但必须遵循正确的步骤以避免冲突或被覆盖。以下是真实、准确且合规的操作指南:


⚠️ 重要前提:确认当前防火墙状态

TOS3 默认使用 firewalld。如果你直接使用 iptables 命令添加规则,这些规则会写入 netfilter 内核模块,但 firewalld 重启后会覆盖你的 iptables 规则。

✅ 推荐做法:

  1. 禁用 firewalld(如果你坚持使用原生 iptables)
  2. 或者更优方案:通过 firewalld 开放端口,而非直接操作 iptables

但若你因特定需求(如旧脚本兼容、精细控制)必须使用 iptables,请按以下步骤操作:


一、禁用 firewalld(如需独占使用 iptables)

# 停止 firewalld 服务
sudo systemctl stop firewalld

# 禁止 firewalld 开机自启
sudo systemctl disable firewalld

# 可选:屏蔽 firewalld,防止被其他服务自动拉起
sudo systemctl mask firewalld

📌 注意:在某些云环境(如腾讯云 CVM),如果使用了 VPC 安全组,iptables 仅作用于主机层过滤,VPC 安全组仍是第一道防线。


二、安装并启用 iptables 服务

TOS3 通常已预装 iptables-services 包,若未安装:

sudo yum install iptables-services -y

然后启动并设置开机自启:

sudo systemctl start iptables
sudo systemctl enable iptables

验证状态:

systemctl status iptables

三、配置 iptables 规则

1. 查看当前规则

sudo iptables -L -n -v

2. 常用规则示例

(1)允许 SSH(端口 22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
(2)允许 HTTP/HTTPS(80/443)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
(3)允许 ICMP(ping)
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
(4)允许已建立连接的相关数据包(关键!)
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
(5)拒绝其他所有入站流量(谨慎使用)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT  # 通常出站不限制

🔥 警告:在执行 DROP 前,请确保已允许 SSH,否则你会被锁在外面!

3. 保存规则

iptables 规则重启后失效,必须保存:

sudo service iptables save
# 或
sudo iptables-save > /etc/sysconfig/iptables

四、验证规则生效

sudo iptables -L -n -v

检查是否包含你添加的规则,特别是 ACCEPT 和 DROP 策略。


五、恢复 firewalld(如后续想切换回 firewalld)

sudo systemctl unmask firewalld
sudo systemctl start firewalld
sudo systemctl enable firewalld

此时 iptables 规则将被 firewalld 重置,需重新通过 firewalld 配置。


六、腾讯云特殊注意事项

  1. VPC 安全组优先于主机 iptables
    腾讯云 CVM 的网络访问首先由 VPC 安全组控制。即使 iptables 允许某端口,若安全组未放行,外部仍无法访问。请同时在腾讯云控制台配置安全组规则。

  2. 弹性网卡与多 IP
    如果实例绑定多个弹性网卡或辅助 IP,iptables 规则默认作用于主网卡 eth0。如需针对特定网卡或 IP 做规则,可使用 -i 或 -d 参数指定。

  3. 容器环境(Docker/K8s)
    如果运行 Docker 或 Kubernetes,它们会自动修改 iptables 规则(尤其是 DOCKER-USER 链)。手动添加规则时,建议放在 DOCKER-USER 链之前,或使用 --insert 插入到正确位置。


七、最佳实践建议

场景 推荐方式
简单端口开放 使用 firewalld 或腾讯云安全组
复杂过滤逻辑 使用 iptables + ipset 提升性能
长期稳定运行 编写 /etc/sysconfig/iptables 脚本并保存
自动化运维 使用 Ansible/Terraform 管理规则

八、常见问题排查

  • 规则不生效?
    检查是否被 firewalld 覆盖,或规则顺序错误(iptables 按顺序匹配)。

  • SSH 断开?
    立即通过腾讯云控制台“远程登录”修复,或临时用 netsh advfirewall(Windows)类比思维紧急开放端口。

  • 性能问题?
    大量规则时考虑使用 nftables(TOS3 支持)或升级硬件。


总结

在 TencentOS Server 3.1 中使用 iptables:

  1. 先停 firewalld
  2. 安装 iptables-services
  3. 配置规则并保存
  4. 配合 VPC 安全组使用
  5. 定期备份规则文件

这样可确保防火墙行为可控、可预测,符合生产环境稳定性要求。

未经允许不得转载:CLOUD云枢 » TencentOS Server 3.1 如何配置iptables防火墙规则?