Linux服务器防火墙设置是保障服务器安全的重要环节,合理的防火墙策略能有效阻止未经授权的访问,降低安全风险,在Linux系统中,常用的防火墙工具包括iptables(传统工具)和firewalld(CentOS 7及以上版本默认使用),以下将分别介绍两者的配置方法及注意事项。

iptables防火墙设置
iptables是基于Linux内核的防火墙工具,通过规则链(Chain)和规则(Rule)控制数据流,主要包含三个默认链:INPUT(入站)、OUTPUT(出站)、FORWARD(转发),以及自定义链。
基本操作
-
启动/停止/重启服务
systemctl start iptables # 启动服务 systemctl stop iptables # 停止服务 systemctl restart iptables # 重启服务 systemctl enable iptables # 设置开机自启
-
查看当前规则
iptables -L -n -v # 查看所有规则,显示IP和端口,附带详细信息 iptables -L INPUT -n # 查看INPUT链规则
-
清空规则(谨慎操作)
iptables -F # 清空所有规则 iptables -X # 删除自定义链 iptables -Z # 清空计数器
常用规则配置
-
允许本地回环(必须保留,否则服务异常)
iptables -A INPUT -i lo -j ACCEPT
-
允许已建立的连接(避免断开现有会话)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-
开放特定端口(如SSH 22、HTTP 80、HTTPS 443)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT # 允许SSH iptables -A INPUT -p tcp --dport 80 -j ACCEPT # 允许HTTP iptables -A INPUT -p tcp --dport 443 -j ACCEPT # 允许HTTPS
-
禁止其他所有入站(放在规则最后)
iptables -A INPUT -j DROP
-
删除规则
通过规则序号删除:iptables -D INPUT 5(删除INPUT链第5条规则)
通过精确匹配删除:iptables -D INPUT -p tcp --dport 22 -j ACCEPT
保存规则
不同系统保存方式不同:
- CentOS 6/7:
service iptables save(保存至/etc/sysconfig/iptables) - Ubuntu/Debian:
iptables-save > /etc/iptables/rules.v4
firewalld防火墙设置
firewalld支持区域(Zone)管理,可根据网络环境(如公网、内网)应用不同策略,动态修改规则无需重启服务。
基本操作
-
启动/停止/重启服务
systemctl start firewalld # 启动服务 systemctl stop firewalld # 停止服务 systemctl restart firewalld # 重启服务 systemctl enable firewalld # 开机自启
-
查看状态与区域
firewall-cmd --state # 查看服务状态 firewall-cmd --get-active-zones # 查看活跃区域 firewall-cmd --get-default-zone # 查看默认区域
区域与端口管理
-
设置默认区域
firewall-cmd --set-default-zone=public
-
开放端口(永久生效需添加
--permanent)firewall-cmd --add-port=22/tcp --permanent # 永久开放SSH firewall-cmd --add-port=80/tcp # 临时开放,重启后失效 firewall-cmd --reload # 重新加载规则使永久生效
-
查看已开放端口
firewall-cmd --list-ports # 查看端口列表 firewall-cmd --list-services # 查看已开放服务
-
允许/禁止IP地址
firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept' --permanent firewall-cmd --remove-rich-rule='rule family="ipv4" source address="192.168.1.100"' --permanent
服务管理
firewalld支持预定义服务(如ssh、http),可通过服务名开放端口:
firewall-cmd --add-service=ssh --permanent # 开放SSH服务(默认端口22) firewall-cmd --add-service=http --permanent # 开放HTTP服务(默认端口80)
防火墙配置最佳实践
- 最小权限原则:仅开放业务必需的端口,禁止所有其他入站请求。
- 规则顺序:默认规则(DROP)应放在最后,避免误拦截合法连接。
- 日志记录:对拒绝的连接启用日志,便于分析攻击行为(如
iptables -A INPUT -j LOG --log-prefix "iptables denied: ")。 - 测试环境验证:生产环境修改规则前,建议在测试机验证,避免远程锁死服务器。
- 定期审计:定期检查防火墙规则,清理过期或冗余规则。
相关问答FAQs
Q1: 修改防火墙规则后如何立即生效且永久保存?
- iptables:临时规则通过命令直接添加,永久保存需执行
service iptables save(CentOS)或iptables-save > /etc/iptables/rules.v4(Ubuntu)。 - firewalld:临时规则不加
--permanent参数,永久规则需添加--permanent后执行firewalld --reload重新加载。
Q2: 防火墙规则误导致SSH无法连接,如何远程恢复?
若因规则错误无法SSH登录,可通过控制台进入服务器,清空所有规则恢复默认:
- iptables:
iptables -F && iptables -X && iptables -Z,然后添加允许SSH的规则。 - firewalld:
firewall-cmd --set-default-zone=public && firewall-cmd --add-service=ssh --permanent && firewall-cmd --reload。
若无法登录服务器,需联系机房人员通过控制台操作。
