插件窝 干货文章 如何优化Linux LAMP性能

如何优化Linux LAMP性能

优化 使用 配置 opcache 335    来源:    2025-05-06

Linux LAMP 性能优化指南

LAMP (Linux, Apache, MySQL, PHP) 是常见的Web服务堆栈,以下是全面的性能优化建议:

1. Linux 系统优化

系统层面

  • 内核参数调优

    # /etc/sysctl.conf 添加或修改
    net.ipv4.tcp_fin_timeout = 30
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_max_syn_backlog = 8192
    net.core.somaxconn = 65535
    vm.swappiness = 10
    

    执行 sysctl -p 使生效

  • 文件描述符限制

    # /etc/security/limits.conf
    * soft nofile 65535
    * hard nofile 65535
    

资源管理

  • 使用 niceionice 调整进程优先级
  • 考虑使用 cgroups 限制资源使用

2. Apache 优化

基础配置

  • MPM模块选择

    • 高流量:eventworker
    • 低流量:prefork

    示例 event 配置:

    <IfModule mpm_event_module>
    StartServers            2
    MinSpareThreads        25
    MaxSpareThreads        75
    ThreadLimit            64
    ThreadsPerChild        25
    MaxRequestWorkers     150
    MaxConnectionsPerChild 10000
    </IfModule>
    

性能模块

  • 启用 mod_deflate 压缩:

    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
    
  • 启用 mod_expires 缓存控制:

    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    

其他优化

  • 禁用不需要的模块
  • 使用 KeepAlive 但合理设置超时: apache KeepAlive On KeepAliveTimeout 2 MaxKeepAliveRequests 100

3. MySQL 优化

配置优化

# /etc/my.cnf 或 /etc/mysql/my.cnf
[mysqld]
innodb_buffer_pool_size = 4G  # 总内存的50-70%
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2  # 非关键数据可设为2
innodb_flush_method = O_DIRECT
query_cache_size = 0  # MySQL 8.0已移除
max_connections = 200
thread_cache_size = 50
table_open_cache = 4000

维护建议

  • 定期执行 OPTIMIZE TABLE 或使用 pt-online-schema-change
  • 设置适当的索引
  • 考虑使用主从复制分散读负载

4. PHP 优化

配置优化

; /etc/php.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

realpath_cache_size=4096K
realpath_cache_ttl=600

; 根据应用调整
memory_limit = 128M
max_execution_time = 30

其他优化

  • 使用 PHP-FPM 替代 mod_php
  • 配置 PHP-FPM 进程池: ini pm = dynamic pm.max_children = 50 pm.start_servers = 5 pm.min_spare_servers = 5 pm.max_spare_servers = 10

5. 整体架构优化

  1. 缓存策略

    • 前端:Varnish/Redis
    • 应用层:Memcached/Redis
    • 数据库:查询缓存
  2. 内容分发

    • 静态资源使用CDN
    • 启用HTTP/2
  3. 监控工具

    • top, htop, vmstat, iostat
    • apachetop, mytop
    • New Relic, Datadog 等专业工具
  4. 替代方案考虑

    • Web服务器:Nginx
    • 数据库:MariaDB/PostgreSQL
    • PHP替代:HHVM (已不推荐), PHP 8.x JIT

6. 安全优化

  • 定期更新所有组件
  • 配置适当的防火墙规则
  • 使用 mod_securitymod_evasive
  • 数据库最小权限原则

实施这些优化后,建议使用工具如 ab, siegejmeter 进行压力测试,验证优化效果并根据实际负载进一步调整。