Linux 防火墙配置详解
时间:2026-10-7 07:16 作者:emer 分类: 无
Linux 防火墙配置详解
服务器安全第一关就是防火墙,配置错了就远程连不上了,这篇讲常用配置。
1. firewalld(CentOS7 默认)
查看状态:
# 查看防火墙状态
firewall-cmd --state
# 查看开放的端口
firewall-cmd --list-ports
# 查看开放的服务
firewall-cmd --list-services
开放端口:
# 开放 80 端口
firewall-cmd --permanent --add-port=80/tcp
# 开放 443 端口
firewall-cmd --permanent --add-port=443/tcp
# 开放多个端口范围
firewall-cmd --permanent --add-port=8000-9000/tcp
# 重载生效
firewall-cmd --reload
关闭端口:
# 关闭 80 端口
firewall-cmd --permanent --remove-port=80/tcp
# 重载
firewall-cmd --reload
开放服务:
# 开放 nginx 服务
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
# 重载
firewall-cmd --reload
2. iptables(老系统常用)
查看规则:
iptables -L -n
开放端口:
# 开放 22 端口
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# 开放 80 端口
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# 保存规则
service iptables save
3. 常用安全配置
只允许指定 IP 访问 SSH:
# 只允许 192.168.1.100 访问 22 端口
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.100' port protocol='tcp' port='22' accept"
# 拒绝其他所有 IP
firewall-cmd --permanent --remove-service=ssh
firewall-cmd --reload
4. 常用端口说明
| 端口 | 服务 |
|---|---|
| 22 | SSH 远程连接 |
| 80 | HTTP 网站 |
| 443 | HTTPS 网站 |
| 3306 | MySQL 数据库 |
| 6379 | Redis 缓存 |
| 8080 | 应用服务 |
5. 常见问题
1)SSH 连不上了:
- 检查防火墙是不是把 22 端口关了
- 用控制台登录服务器重新开放
2)网站打不开:
- 检查 80/443 端口开了没
- 重载防火墙生效
3)数据库连不上:
- 3306 端口别对公网开放
- 只允许本地或指定 IP 访问
总结
防火墙配置记住三点:
- 先开 22 端口,不然自己都连不上
- 网站开 80 和 443
- 数据库别对外网开放
安全第一,别图省事直接关防火墙。