温馨提示×

如何配置LAMP服务器网络

小樊
60
2025-08-17 04:40:06
栏目: 云计算

以下是LAMP服务器网络配置的核心步骤,分系统说明:

一、基础网络配置

1. 配置IP地址

  • CentOS/RHEL
    编辑网络接口文件 /etc/sysconfig/network-scripts/ifcfg-<接口名>(如 ifcfg-eth0),设置静态IP或DHCP:

    BOOTPROTO=static  # 静态IP
    IPADDR=192.168.1.100  # IP地址
    NETMASK=255.255.255.0  # 子网掩码
    GATEWAY=192.168.1.1  # 网关
    DNS1=8.8.8.8  # DNS
    ONBOOT=yes  # 开机自启
    

    保存后重启网络:sudo systemctl restart network

  • Ubuntu/Debian
    编辑 /etc/netplan/01-netcfg.yaml(或对应文件):

    network:
      version: 2
      ethernets:
        eth0:
          addresses: [192.168.1.100/24]
          gateway4: 192.168.1.1
          nameservers:
            addresses: [8.8.8.8, 8.8.4.4]
    

    应用配置:sudo netplan apply

2. 配置防火墙

  • CentOS
    开放HTTP(80)、HTTPS(443)端口:

    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
    
  • Ubuntu
    使用UFW允许Apache流量:

    sudo ufw allow 'Apache Full'
    sudo ufw enable
    

二、LAMP组件网络配置

1. Apache(Web服务器)

  • 编辑主配置文件 /etc/httpd/conf/httpd.conf(CentOS)或 /etc/apache2/apache2.conf(Ubuntu):
    • 监听端口:修改 Listen 80 为所需端口(如8080)。
    • 虚拟主机:在 /etc/httpd/conf.d/(CentOS)或 /etc/apache2/sites-available/(Ubuntu)中创建配置文件,指定域名和文档根目录,例如:
      <VirtualHost *:80>
          ServerName example.com
          DocumentRoot /var/www/example.com
          <Directory /var/www/example.com>
              AllowOverride All
              Require all granted
          </Directory>
      </VirtualHost>
      
    重启Apache生效:sudo systemctl restart httpd(CentOS)或 sudo systemctl restart apache2(Ubuntu)。

2. MySQL(数据库服务器)

  • 编辑配置文件 /etc/mysql/my.cnf(CentOS)或 /etc/mysql/mysql.conf.d/mysqld.cnf(Ubuntu):
    • 监听地址:设置 bind-address = 0.0.0.0 允许远程连接(默认仅本地)。
    • 端口:修改 port = 3306 为自定义端口(需在防火墙中放行)。
      重启MySQL:sudo systemctl restart mysql

3. PHP(可选配置)

  • 若需远程访问PHP服务(如通过API),确保Apache已正确解析PHP文件,无需额外网络配置。

三、验证与优化

  • 测试网络连通性
    ping 8.8.8.8  # 测试互联网访问
    curl -I http://localhost  # 测试Web服务
    mysql -h 192.168.1.100 -u root -p  # 测试数据库远程连接(需配置正确权限)
    
  • 安全优化
    • 禁用MySQL远程root登录,仅允许特定用户从指定IP访问。
    • 为Apache启用SSL/TLS加密(需配置证书)。

注意事项

  • 生产环境中建议关闭防火墙测试后再逐步放行端口,避免误配置导致服务中断。
  • CentOS 8+默认使用 NetworkManager,可通过 nmcli 命令管理网络。
  • Ubuntu 22.04+可能使用 systemd-networkd,需通过 networkctl 配置。

参考来源:[1,2,3,6,8,9,10,11,12,14]

0