CentOS PHP项目部署与优化实操指南
一 基础环境与安全加固
yum update -y && yum install -y wget curl vim net-toolshostnamectl set-hostname lamp-serversystemctl start firewalld && systemctl enable firewalldfirewall-cmd --permanent --add-service={http,https,ssh} && firewall-cmd --reloadadduser deployer && passwd deployerusermod -aG wheel deployer/etc/ssh/sshd_config:PermitRootLogin no,重启sshdsemanage fcontext/restorecon修正自定义目录上下文mysql_secure_installation、虚拟主机配置错误二 部署架构与组件安装
yum install -y httpd && systemctl start httpd && systemctl enable httpdyum install -y mariadb-server mariadb && systemctl start mariadb && systemctl enable mariadbyum install -y php php-mysqlnd php-fpm php-opcache php-gd php-xml php-mbstringmysql_secure_installation,设置强密码、删除匿名用户、禁止root远程、移除测试库/var/www/myapp,配置/etc/httpd/conf.d/myapp.conf的DocumentRoot与<Directory>,设置AllowOverride All以支持.htaccesschown -R apache:apache /var/www/myappyum install -y certbot python3-certbot-apachecertbot --apache -d myapp.example.comecho "0 3 * * * /usr/bin/certbot renew --quiet" | crontab -<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
</IfModule>
三 PHP与PHP-FPM性能优化
/etc/php.ini或/etc/php.d/opcache.ini:opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
memory_limit=256Mupload_max_filesize=32Mpost_max_size=64M(需≥上传大小)max_execution_time=300display_errors=Off,log_errors=Onpm=dynamicpm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
request_terminate_timeout = 30s
slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 10s
listen = /run/php/php-fpm.sock
listen.owner = apache
listen.group = apache
listen.mode = 0660
user = apache
group = apache
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
max_children ≈ 1536 / 40 ≈ 38,可先设为32–40并压测微调四 Web服务器与网络层优化
listen 443 ssl http2;gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;sendfile on; tcp_nopush on; tcp_nodelay on;Cache-Control/Expires与ETag/Last-Modifiedworker_processes、worker_connections,对异常来源限流/限速KeepAlive Onmod_deflatemod_cache、mod_expiresStartServers 5、MinSpareServers 5、MaxSpareServers 10、MaxRequestWorkers 150(按内存与并发压测调整)五 数据库与缓存及运维监控
innodb_buffer_pool_size为可用内存的50%–70%(专用数据库场景)htop、nmon、sartail -f /var/log/httpd/error_log、/var/log/php-fpm/error.log、/var/log/php-fpm/slow.log/etc/logrotate.d/httpd与PHP-FPM日志轮转,避免磁盘撑满mysqldump定期备份(含时间点恢复方案)