linux

Linux系统中如何设置LNMP防火墙

小樊
32
2025-06-04 16:49:38
栏目: 智能运维

在Linux系统中设置LNMP(Linux, Nginx, MySQL, PHP)防火墙,通常涉及配置iptables或使用更现代的firewalld服务。以下是使用这两种方法的步骤:

使用iptables

  1. 查看现有规则

    sudo iptables -L -n
    
  2. 允许SSH连接(如果需要远程管理服务器):

    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    
  3. 允许HTTP和HTTPS流量

    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    
  4. 允许MySQL/MariaDB连接(默认端口3306):

    sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
    
  5. 拒绝所有其他输入

    sudo iptables -P INPUT DROP
    
  6. 保存规则

    • 对于Debian/Ubuntu系统:
      sudo sh -c "iptables-save > /etc/iptables/rules.v4"
      
    • 对于CentOS/RHEL系统:
      sudo service iptables save
      
  7. 重启iptables服务(如果需要):

    sudo systemctl restart iptables
    

使用firewalld

  1. 安装firewalld(如果尚未安装):

    sudo yum install firewalld
    
  2. 启动并启用firewalld服务

    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  3. 允许SSH连接

    sudo firewall-cmd --permanent --add-service=ssh
    
  4. 允许HTTP和HTTPS流量

    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    
  5. 允许MySQL/MariaDB连接

    sudo firewall-cmd --permanent --add-port=3306/tcp
    
  6. 重新加载firewalld配置

    sudo firewall-cmd --reload
    
  7. 查看当前防火墙状态和规则

    sudo firewall-cmd --list-all
    

注意事项

通过以上步骤,您可以在Linux系统中为LNMP环境设置防火墙,确保系统的安全性和稳定性。

0
看了该问题的人还看了