Debian LAMP高效服务器搭建与优化指南
sudo apt update && sudo apt upgrade -y
,确保所有软件包为最新版本,修复已知漏洞。bind9
、nscd
),减少系统资源占用。sudo apt install apache2 -y
,启动服务并设置开机自启:sudo systemctl enable --now apache2
。sudo apt install mariadb-server -y
,运行sudo mysql_secure_installation
强化安全(设置root密码、移除匿名用户、禁止root远程登录)。sudo apt install php libapache2-mod-php php-mysql php-curl php-gd php-mbstring php-xml php-zip -y
,重启Apache加载PHP:sudo systemctl restart apache2
。sudo a2enmod rewrite expires
(支持URL重写和静态内容缓存),提升动态内容处理效率。prefork
(多进程模型,资源消耗大),启用worker
(多线程模型,适合高并发):sudo a2dismod prefork && sudo a2enmod worker && sudo systemctl restart apache2
。/etc/apache2/mods-enabled/mpm_worker.conf
,调整以下参数(根据服务器内存调整,如4GB内存):StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
/etc/apache2/mods-enabled/http2.conf
,添加Protocols h2 http/1.1
,提升传输效率。/etc/mysql/mariadb.conf.d/50-server.cnf
,设置innodb_buffer_pool_size
为系统内存的50%-80%(如4GB内存设为2G),提升InnoDB表性能。query_cache_size=64M
(启用查询缓存,但注意高并发下可能成为瓶颈),query_cache_type=1
。max_connections=150
(避免过多连接导致资源耗尽),wait_timeout=300
(关闭闲置连接,释放资源)。sudo mysqlcheck -u root -p --all-databases --auto-repair
,优化表结构和索引。sudo apt install php-opcache && sudo phpenmod opcache && sudo systemctl restart apache2
,编辑/etc/php/8.2/apache2/php.ini
(版本根据实际调整),配置:opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
sudo apt install php-fpm
,编辑/etc/php/8.2/fpm/pool.d/www.conf
,调整进程参数:pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
修改Apache配置(/etc/apache2/mods-enabled/php8.2.conf
),将PHP处理交给PHP-FPM:<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php/php8.2-fpm.sock|fcgi://localhost"
</FilesMatch>
重启服务:sudo systemctl restart php8.2-fpm apache2
。/etc/apache2/sites-available/000-default.conf
),添加:<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
sudo apt install redis-server php-redis
,配置应用使用Redis缓存数据库查询结果(如WordPress的Redis Object Cache插件),减少数据库负载。sudo apt install ufw
,允许HTTP/HTTPS和SSH:sudo ufw allow 'Apache Full' && sudo ufw allow OpenSSH
,启用防火墙:sudo ufw enable
。Options -Indexes
,防止未经授权的目录浏览。sudo apt install unattended-upgrades
),及时修复安全漏洞。htop
(实时进程监控)、glances
(综合系统监控)查看CPU、内存、磁盘使用情况。/var/log/apache2/access.log
、error.log
)和MySQL(/var/log/mysql/error.log
)日志,识别异常请求(如大量404错误)或慢查询。rsync
或BorgBackup
定期备份网站文件和数据库,存储到异地(如云存储)。