一、LAMP架构概述
1. 什么是LAMP
LAMP 是一种经典的Web服务架构组合,由以下组件构成:
text
L - Linux 操作系统
A - Apache Web服务器
M - MySQL 数据库系统
P - PHP 动态内容处理语言
2. LAMP架构工作原理
text
客户端请求
↓
┌─────────────────────────────────────┐
│ Apache (端口80/443) │
│ └── 静态请求(html, css, js, 图片) │
│ └── 动态请求(通过模块或FCGI) │
└─────────────────────────────────────┘
↓
┌───────────────────┐
│ PHP模块/libphp │
│ 或 PHP-FPM │
└───────────────────┘
↓
┌───────────────────┐
│ MySQL │
│ (端口3306) │
└───────────────────┘
请求处理流程:
text
1. 客户端发起HTTP请求
2. Apache接收请求
3. Apache根据配置处理请求
├── 静态文件 → 直接返回
└── PHP文件 → 通过PHP模块处理
4. PHP执行脚本,如需数据库则连接MySQL
5. 返回结果给Apache
6. Apache将结果返回给客户端
3. LAMP与LNMP对比
| 特性 | LAMP | LNMP |
|---|---|---|
| Web服务器 | Apache | Nginx |
| 处理方式 | 同步阻塞/多进程 | 异步非阻塞 |
| 配置复杂度 | 简单(.htaccess) | 中等 |
| 模块支持 | 丰富(动态/静态加载) | 有限 |
| 并发处理 | 中等 | 高 |
| 内存占用 | 较高 | 较低 |
| 兼容性 | 极好 | 良好 |
| 适用场景 | 兼容性要求高的应用 | 高并发场景 |
二、环境准备
1. 系统要求
bash
# 操作系统
CentOS 7/8/9
Ubuntu 18.04/20.04/22.04
Debian 10/11
# 检查系统版本
cat /etc/os-release
uname -a
# 检查系统架构
arch
# x86_64 或 aarch64
# 检查内存
free -h
# 检查磁盘
df -h
2. 关闭防火墙和SELinux(CentOS)
bash
# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
# 或者开放必要端口
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-port=3306/tcp # MySQL
firewall-cmd --reload
# 关闭SELinux
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
getenforce
3. 更新系统
bash
# CentOS/RHEL
yum update -y
# Ubuntu/Debian
apt update && apt upgrade -y
# 安装常用工具
# CentOS
yum install -y wget curl vim net-tools telnet lsof
# Ubuntu/Debian
apt install -y wget curl vim net-tools telnet lsof
三、Apache安装与配置
1. 安装Apache
bash
# CentOS/RHEL
yum install -y httpd
# Ubuntu/Debian
apt install -y apache2
# 编译安装Apache(自定义需求)
# 安装依赖
yum groupinstall -y "Development Tools"
yum install -y pcre-devel openssl-devel expat-devel libtool
# 下载源码
wget https://dlcdn.apache.org/httpd/httpd-2.4.57.tar.gz
wget https://dlcdn.apache.org/apr/apr-1.7.4.tar.gz
wget https://dlcdn.apache.org/apr/apr-util-1.6.3.tar.gz
# 解压
tar -xzf httpd-2.4.57.tar.gz
tar -xzf apr-1.7.4.tar.gz
tar -xzf apr-util-1.6.3.tar.gz
# 移动APR到Apache源码目录
mv apr-1.7.4 httpd-2.4.57/srclib/apr
mv apr-util-1.6.3 httpd-2.4.57/srclib/apr-util
# 编译配置
cd httpd-2.4.57
./configure \
--prefix=/usr/local/apache2 \
--enable-so \
--enable-ssl \
--enable-cgi \
--enable-rewrite \
--enable-modules=most \
--enable-mpms-shared=all \
--with-mpm=event \
--enable-proxy \
--enable-proxy-http
# 编译安装
make -j$(nproc)
make install
# 创建软链接
ln -s /usr/local/apache2/bin/apachectl /usr/local/bin/
2. 启动Apache
bash
# CentOS
systemctl start httpd
systemctl enable httpd
# Ubuntu
systemctl start apache2
systemctl enable apache2
# 编译安装启动
/usr/local/apache2/bin/apachectl start
# 创建systemd服务(编译安装)
cat > /etc/systemd/system/apache2.service << 'EOF'
[Unit]
Description=Apache HTTP Server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/apache2/logs/httpd.pid
ExecStart=/usr/local/apache2/bin/apachectl start
ExecReload=/usr/local/apache2/bin/apachectl graceful
ExecStop=/usr/local/apache2/bin/apachectl stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start apache2
systemctl enable apache2
# 查看状态
systemctl status httpd
# 或
systemctl status apache2
# 查看端口
netstat -tlnp | grep 80
ss -tlnp | grep 80
3. 验证Apache安装
bash
# 检查版本
httpd -v
# 或
apache2 -v
# 检查配置文件语法
httpd -t
# 或
apache2ctl configtest
# 测试访问
curl -I http://localhost
# 或通过浏览器访问 http://服务器IP
4. Apache基础配置
apache
# CentOS: /etc/httpd/conf/httpd.conf
# Ubuntu: /etc/apache2/apache2.conf
# 全局配置
ServerRoot "/etc/httpd"
Listen 80
User apache
Group apache
# 模块加载
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule proxy_module modules/mod_proxy.so
# 服务器名称
ServerName www.example.com:80
# 文档根目录
DocumentRoot "/var/www/html"
# 目录配置
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 目录索引
DirectoryIndex index.html index.php
# 日志配置
ErrorLog "logs/error_log"
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog "logs/access_log" common
# 包含其他配置文件
IncludeOptional conf.d/*.conf
IncludeOptional sites-enabled/*.conf
5. 虚拟主机配置
apache
# /etc/httpd/conf.d/example.com.conf 或 /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com
<Directory /var/www/example.com>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/example.com_error.log
CustomLog /var/log/httpd/example.com_access.log combined
# 别名
Alias /docs "/var/www/docs"
<Directory "/var/www/docs">
Require all granted
</Directory>
# 错误页面
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
</VirtualHost>
# Ubuntu启用站点
a2ensite example.com.conf
systemctl reload apache2
6. HTTPS配置
apache
# 启用SSL模块
# CentOS: yum install mod_ssl
# Ubuntu: a2enmod ssl
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com
# SSL证书配置
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/example.com.crt
SSLCertificateKeyFile /etc/pki/tls/private/example.com.key
SSLCertificateChainFile /etc/pki/tls/certs/chain.crt
# SSL协议和加密套件
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite HIGH:!aNULL:!MD5
# HSTS
Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
<Directory /var/www/example.com>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/example.com_ssl_error.log
CustomLog /var/log/httpd/example.com_ssl_access.log combined
</VirtualHost>
# HTTP重定向到HTTPS
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
7. Apache性能优化
apache
# MPM配置(多进程处理模块)
# CentOS: /etc/httpd/conf.modules.d/00-mpm.conf
# Ubuntu: /etc/apache2/mods-available/mpm_*.conf
# 1. prefork MPM(每个进程处理一个请求)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 3000
</IfModule>
# 2. worker MPM(多线程)
<IfModule mpm_worker_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 1000
</IfModule>
# 3. event MPM(基于事件的MPM,推荐)
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 1000
</IfModule>
# 启用KeepAlive
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# 压缩配置
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
AddOutputFilterByType DEFLATE application/javascript application/x-javascript
AddOutputFilterByType DEFLATE application/json application/xml
DeflateCompressionLevel 6
</IfModule>
# 缓存配置
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
四、MySQL安装与配置
1. 安装MySQL
bash
# CentOS/RHEL 7/8/9
# 添加MySQL官方仓库
yum install -y https://dev.mysql.com/get/mysql80-community-release-el7-5.noarch.rpm
# CentOS 8
# yum install -y https://dev.mysql.com/get/mysql80-community-release-el8-4.noarch.rpm
# 安装MySQL 8.0
yum install -y mysql-community-server
# Ubuntu/Debian
# 下载MySQL APT仓库
wget https://dev.mysql.com/get/mysql-apt-config_0.8.24-1_all.deb
dpkg -i mysql-apt-config_0.8.24-1_all.deb
apt update
apt install -y mysql-server
# 安装MariaDB(MySQL替代品)
# CentOS
yum install -y mariadb-server
# Ubuntu
apt install -y mariadb-server
2. 启动MySQL
bash
# 启动MySQL
systemctl start mysqld
# 或 systemctl start mariadb
# 设置开机自启
systemctl enable mysqld
# 查看状态
systemctl status mysqld
# 查看默认密码(MySQL 8.0)
grep 'temporary password' /var/log/mysqld.log
# 安全配置向导
mysql_secure_installation
# 对于MariaDB
mysql_secure_installation
3. MySQL安全配置
sql
-- 手动执行安全配置
-- 1. 修改root密码
ALTER USER 'root'@'localhost' IDENTIFIED BY 'StrongPassword123!';
-- 2. 删除匿名用户
DELETE FROM mysql.user WHERE User='';
-- 3. 禁止root远程登录
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- 4. 删除测试数据库
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
-- 5. 刷新权限
FLUSH PRIVILEGES;
4. 创建数据库和用户
sql
-- 登录MySQL
mysql -u root -p
-- 创建数据库
CREATE DATABASE example_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建用户
CREATE USER 'example_user'@'localhost' IDENTIFIED BY 'Password123!';
CREATE USER 'example_user'@'%' IDENTIFIED BY 'Password123!';
-- 授权
GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'localhost';
GRANT ALL PRIVILEGES ON example_db.* TO 'example_user'@'%';
-- 刷新权限
FLUSH PRIVILEGES;
-- 查看用户
SELECT User, Host FROM mysql.user;
-- 测试连接
mysql -u example_user -p -h localhost example_db
5. MySQL优化配置
ini
# /etc/my.cnf 或 /etc/mysql/my.cnf
[mysqld]
# 基本设置
port = 3306
bind-address = 0.0.0.0
datadir = /var/lib/mysql
socket = /var/lib/mysql/mysql.sock
pid-file = /var/run/mysqld/mysqld.pid
# 字符集
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
init-connect = 'SET NAMES utf8mb4'
# 存储引擎
default-storage-engine = InnoDB
# 连接设置
max_connections = 500
max_connect_errors = 100
connect_timeout = 10
wait_timeout = 600
interactive_timeout = 28800
# 缓冲区
key_buffer_size = 256M
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 4M
join_buffer_size = 2M
# 临时表
tmp_table_size = 64M
max_heap_table_size = 64M
# InnoDB设置
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_file_per_table = 1
innodb_flush_method = O_DIRECT
# 日志
log_error = /var/log/mysql/error.log
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
五、PHP安装与配置
1. 安装PHP
bash
# CentOS/RHEL
# 添加EPEL和REMI仓库
yum install -y epel-release
yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
# CentOS 8
# yum install -y https://rpms.remirepo.net/enterprise/remi-release-8.rpm
# 启用PHP 8.2仓库
yum module enable php:remi-8.2 -y
# 安装PHP和Apache模块
yum install -y php php-cli php-common php-devel \
php-mysqlnd php-pdo php-gd php-mbstring php-xml \
php-zip php-curl php-json php-opcache php-bcmath \
php-redis php-memcached php-intl php-soap php-pear
# Ubuntu/Debian
# 添加PPA(Ubuntu)
apt install -y software-properties-common
add-apt-repository ppa:ondrej/php
apt update
# 安装PHP 8.2和Apache模块
apt install -y php8.2 php8.2-cli php8.2-common \
php8.2-mysql php8.2-pdo php8.2-gd php8.2-mbstring \
php8.2-xml php8.2-zip php8.2-curl php8.2-bcmath \
php8.2-redis php8.2-memcached php8.2-intl \
libapache2-mod-php8.2
# 编译安装PHP(自定义需求)
# 安装依赖
yum groupinstall -y "Development Tools"
yum install -y gcc gcc-c++ make automake autoconf libtool \
libxml2-devel openssl-devel curl-devel libjpeg-devel \
libpng-devel freetype-devel libmcrypt-devel mhash-devel \
libxslt-devel libc-client-devel libicu-devel \
apr-devel apr-util-devel
# 下载源码
wget https://www.php.net/distributions/php-8.2.10.tar.gz
tar -xzf php-8.2.10.tar.gz
cd php-8.2.10
# 编译配置
./configure \
--prefix=/usr/local/php \
--with-config-file-path=/usr/local/php/etc \
--with-config-file-scan-dir=/usr/local/php/etc/php.d \
--with-apxs2=/usr/local/apache2/bin/apxs \
--enable-mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-gd \
--with-zlib \
--with-curl \
--with-openssl \
--with-xsl \
--with-gettext \
--enable-mbstring \
--enable-xml \
--enable-bcmath \
--enable-sockets \
--enable-zip \
--enable-opcache
# 编译安装
make -j$(nproc)
make install
# 复制配置文件
cp php.ini-production /usr/local/php/etc/php.ini
2. 配置php.ini
ini
# /etc/php.ini 或 /etc/php/8.2/cli/php.ini
[PHP]
; 基本设置
engine = On
short_open_tag = Off
asp_tags = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
; 安全设置
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
expose_php = Off
max_execution_time = 30
max_input_time = 60
memory_limit = 256M
; 错误设置
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
track_errors = Off
html_errors = Off
; 文件上传
file_uploads = On
upload_max_filesize = 20M
max_file_uploads = 20
post_max_size = 20M
max_input_vars = 3000
; 日期时间
date.timezone = Asia/Shanghai
; 会话设置
session.save_handler = files
session.use_strict_mode = 1
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly = 1
session.cookie_samesite = Lax
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.sid_length = 32
; OPcache
[opcache]
opcache.enable = 1
opcache.memory_consumption = 128
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 10000
opcache.revalidate_freq = 2
opcache.fast_shutdown = 1
opcache.validate_timestamps = 1
3. 配置Apache与PHP
apache
# CentOS: /etc/httpd/conf.d/php.conf
# Ubuntu: /etc/apache2/mods-available/php8.2.conf
# 加载PHP模块
LoadModule php_module modules/libphp.so
# 添加PHP处理
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
# 目录索引
DirectoryIndex index.php index.html
# PHP配置
php_value session.save_handler files
php_value session.save_path /var/lib/php/session
php_value max_execution_time 30
# 添加PHP类型
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
# 安全配置
<FilesMatch "\.phps$">
Require all denied
</FilesMatch>
4. 创建PHP测试页面
php
<?php
// /var/www/example.com/index.php
phpinfo();
?>
<?php
// /var/www/example.com/info.php
$output = '';
$output .= '<h1>LAMP Environment Test</h1>';
// PHP版本
$output .= '<h2>PHP Information</h2>';
$output .= '<p>PHP Version: ' . phpversion() . '</p>';
// 加载的扩展
$output .= '<h2>Loaded Extensions</h2><ul>';
$extensions = get_loaded_extensions();
sort($extensions);
foreach ($extensions as $ext) {
$output .= '<li>' . $ext . '</li>';
}
$output .= '</ul>';
// Apache信息
$output .= '<h2>Apache Information</h2>';
$output .= '<p>Server Software: ' . $_SERVER['SERVER_SOFTWARE'] . '</p>';
$output .= '<p>Server Name: ' . $_SERVER['SERVER_NAME'] . '</p>';
$output .= '<p>Server Port: ' . $_SERVER['SERVER_PORT'] . '</p>';
$output .= '<p>Document Root: ' . $_SERVER['DOCUMENT_ROOT'] . '</p>';
// MySQL连接测试
$output .= '<h2>MySQL Connection Test</h2>';
try {
$db = new PDO('mysql:host=localhost;dbname=example_db;charset=utf8mb4', 'example_user', 'Password123!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$output .= '<p style="color:green">✓ MySQL connection successful</p>';
} catch (PDOException $e) {
$output .= '<p style="color:red">✗ MySQL connection failed: ' . $e->getMessage() . '</p>';
}
echo $output;
?>
5. 测试PHP处理
bash
# 重启Apache
systemctl restart httpd
# 或
systemctl restart apache2
# 创建测试文件
cat > /var/www/html/test.php << 'EOF'
<?php
echo "PHP is working correctly!";
phpinfo();
?>
EOF
# 测试访问
curl http://localhost/test.php
# 或通过浏览器访问 http://服务器IP/test.php
六、部署Web应用
1. 部署phpMyAdmin
bash
# 下载phpMyAdmin
cd /tmp
wget https://files.phpmyadmin.net/phpMyAdmin/5.2.1/phpMyAdmin-5.2.1-all-languages.zip
unzip phpMyAdmin-5.2.1-all-languages.zip
mv phpMyAdmin-5.2.1-all-languages /var/www/html/phpmyadmin
# 创建配置
cd /var/www/html/phpmyadmin
cp config.sample.inc.php config.inc.php
# 生成blowfish_secret
cat > /tmp/secret.php << 'EOF'
<?php
echo bin2hex(random_bytes(32));
?>
EOF
php /tmp/secret.php
# 编辑配置文件
vim config.inc.php
# 添加/修改
$cfg['blowfish_secret'] = '生成的32位密钥';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
# 设置权限
chown -R apache:apache /var/www/html/phpmyadmin
# Ubuntu使用www-data
# chown -R www-data:www-data /var/www/html/phpmyadmin
# Apache配置别名(可选)
cat >> /etc/httpd/conf.d/phpmyadmin.conf << 'EOF'
Alias /phpmyadmin /var/www/html/phpmyadmin
<Directory /var/www/html/phpmyadmin>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
EOF
systemctl restart httpd
2. 部署WordPress
bash
# 下载WordPress
cd /tmp
wget https://wordpress.org/latest.tar.gz
tar -xzf latest.tar.gz
mv wordpress /var/www/html/
# 设置权限
chown -R apache:apache /var/www/html/wordpress
# Ubuntu
# chown -R www-data:www-data /var/www/html/wordpress
chmod -R 755 /var/www/html/wordpress
# 创建WordPress数据库
mysql -u root -p -e "CREATE DATABASE wordpress CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -u root -p -e "CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'WpPassword123!';"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wpuser'@'localhost';"
mysql -u root -p -e "FLUSH PRIVILEGES;"
# 复制配置文件
cd /var/www/html/wordpress
cp wp-config-sample.php wp-config.php
# 编辑配置
sed -i "s/database_name_here/wordpress/" wp-config.php
sed -i "s/username_here/wpuser/" wp-config.php
sed -i "s/password_here/WpPassword123!/" wp-config.php
# 生成安全密钥
curl -s https://api.wordpress.org/secret-key/1.1/salt/ >> wp-config.php
# 创建Apache虚拟主机
cat > /etc/httpd/conf.d/wordpress.conf << 'EOF'
<VirtualHost *:80>
ServerName blog.example.com
DocumentRoot /var/www/html/wordpress
<Directory /var/www/html/wordpress>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/wordpress_error.log
CustomLog /var/log/httpd/wordpress_access.log combined
</VirtualHost>
EOF
# 创建.htaccess文件
cat > /var/www/html/wordpress/.htaccess << 'EOF'
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
EOF
# 启用mod_rewrite
# CentOS默认已启用,Ubuntu需要
# a2enmod rewrite
systemctl restart httpd
3. 部署Laravel应用
bash
# 安装Composer
cd /tmp
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
# 创建Laravel项目
cd /var/www/html
composer create-project --prefer-dist laravel/laravel laravel
# 设置权限
chown -R apache:apache laravel
# Ubuntu
# chown -R www-data:www-data laravel
chmod -R 755 laravel/storage
chmod -R 755 laravel/bootstrap/cache
# 配置.env文件
cd laravel
cp .env.example .env
php artisan key:generate
# 编辑.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel_user
DB_PASSWORD=LaravelPassword123!
# 创建数据库
mysql -u root -p -e "CREATE DATABASE laravel CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -u root -p -e "CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'LaravelPassword123!';"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON laravel.* TO 'laravel_user'@'localhost';"
mysql -u root -p -e "FLUSH PRIVILEGES;"
# 运行迁移
php artisan migrate
# 创建Apache虚拟主机
cat > /etc/httpd/conf.d/laravel.conf << 'EOF'
<VirtualHost *:80>
ServerName app.example.com
DocumentRoot /var/www/html/laravel/public
<Directory /var/www/html/laravel/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/laravel_error.log
CustomLog /var/log/httpd/laravel_access.log combined
</VirtualHost>
EOF
# 创建.htaccess
cat > /var/www/html/laravel/public/.htaccess << 'EOF'
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
EOF
systemctl restart httpd
七、性能优化
1. Apache优化
apache
# /etc/httpd/conf/httpd.conf 或 /etc/apache2/apache2.conf
# 启用KeepAlive
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# MPM配置(选择适合的MPM)
# prefork MPM(适合兼容性要求高的应用)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 256
MaxConnectionsPerChild 3000
</IfModule>
# event MPM(适合高并发)
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 1000
</IfModule>
# 压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
AddOutputFilterByType DEFLATE application/javascript application/x-javascript
AddOutputFilterByType DEFLATE application/json application/xml
DeflateCompressionLevel 6
</IfModule>
# 缓存
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
# 文件缓存
<IfModule mod_file_cache.c>
CacheFile /var/www/html/index.html
</IfModule>
2. PHP优化
ini
# /etc/php.ini
[PHP]
memory_limit = 256M
max_execution_time = 30
max_input_time = 60
post_max_size = 20M
upload_max_filesize = 20M
date.timezone = Asia/Shanghai
[opcache]
opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
opcache.revalidate_freq = 60
opcache.fast_shutdown = 1
opcache.enable_cli = 0
[Session]
session.save_handler = files
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
3. MySQL优化
ini
# /etc/my.cnf
[mysqld]
# 连接设置
max_connections = 500
max_user_connections = 100
wait_timeout = 600
interactive_timeout = 28800
# 缓冲区
key_buffer_size = 256M
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 4M
join_buffer_size = 2M
# InnoDB
innodb_buffer_pool_size = 2G
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
innodb_open_files = 2048
# 表缓存
table_open_cache = 2048
table_definition_cache = 2048
# 临时表
tmp_table_size = 64M
max_heap_table_size = 64M
# 慢查询日志
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
4. 系统优化
bash
# 调整系统限制
cat >> /etc/security/limits.conf << 'EOF'
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
EOF
# 调整内核参数
cat >> /etc/sysctl.conf << 'EOF'
# 网络优化
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_syncookies = 1
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 5000
# 文件系统
fs.file-max = 65535
fs.inotify.max_user_watches = 524288
# 内存
vm.swappiness = 10
vm.dirty_ratio = 30
vm.dirty_background_ratio = 5
EOF
# 应用参数
sysctl -p
八、监控和维护
1. 日志管理
bash
# Apache日志轮转
cat > /etc/logrotate.d/httpd << 'EOF'
/var/log/httpd/*log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 root root
sharedscripts
postrotate
/bin/systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
EOF
# MySQL日志轮转
cat > /etc/logrotate.d/mysql << 'EOF'
/var/log/mysql/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 mysql mysql
sharedscripts
postrotate
test -x /usr/bin/mysqladmin || exit 0
mysqladmin flush-logs
endscript
}
EOF
# 手动执行日志切割
logrotate -vf /etc/logrotate.d/httpd
2. 监控脚本
bash
#!/bin/bash
# lamp_monitor.sh - LAMP监控脚本
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# 检查服务状态
check_service() {
local service=$1
if systemctl is-active --quiet $service; then
echo -e "${GREEN}✓ $service 运行中${NC}"
return 0
else
echo -e "${RED}✗ $service 未运行${NC}"
return 1
fi
}
# 检查端口
check_port() {
local port=$1
local service=$2
if netstat -tlnp | grep -q ":$port "; then
echo -e "${GREEN}✓ $service 端口 $port 正常${NC}"
return 0
else
echo -e "${RED}✗ $service 端口 $port 未监听${NC}"
return 1
fi
}
# 检查Apache
check_apache() {
echo -e "\n${YELLOW}=== Apache 状态 ===${NC}"
check_service httpd
check_port 80 "Apache"
check_port 443 "Apache"
# Apache进程数
APACHE_PROCESSES=$(ps aux | grep httpd | grep -v grep | wc -l)
echo "Apache进程数: $APACHE_PROCESSES"
# 测试访问
if curl -s -o /dev/null -w "%{http_code}" http://localhost | grep -q "200"; then
echo -e "${GREEN}✓ Apache 响应正常${NC}"
else
echo -e "${RED}✗ Apache 响应异常${NC}"
fi
}
# 检查PHP
check_php() {
echo -e "\n${YELLOW}=== PHP 状态 ===${NC}"
# PHP版本
PHP_VERSION=$(php -v | head -1 | awk '{print $2}')
echo "PHP版本: $PHP_VERSION"
# 测试PHP处理
echo "<?php echo 'PHP is working'; ?>" > /tmp/test.php
if curl -s http://localhost/test.php | grep -q "PHP is working"; then
echo -e "${GREEN}✓ PHP 处理正常${NC}"
else
echo -e "${RED}✗ PHP 处理异常${NC}"
fi
rm -f /tmp/test.php
}
# 检查MySQL
check_mysql() {
echo -e "\n${YELLOW}=== MySQL 状态 ===${NC}"
check_service mysqld
check_port 3306 "MySQL"
# 测试连接
if mysqladmin -u root -p"$MYSQL_PASS" ping 2>/dev/null | grep -q "alive"; then
echo -e "${GREEN}✓ MySQL 连接正常${NC}"
else
echo -e "${RED}✗ MySQL 连接失败${NC}"
fi
# 查看MySQL状态
mysql -e "SHOW STATUS LIKE 'Threads_connected';" 2>/dev/null
}
# 检查系统资源
check_system() {
echo -e "\n${YELLOW}=== 系统资源 ===${NC}"
# CPU负载
LOAD=$(uptime | awk -F'load average:' '{print $2}')
echo "CPU负载: $LOAD"
# 内存使用
MEM=$(free -h | grep Mem | awk '{print "已用: " $3 " / 总计: " $2}')
echo "内存使用: $MEM"
# 磁盘使用
DISK=$(df -h / | awk 'NR==2 {print "已用: " $3 " / 总计: " $2 " (" $5 ")"}')
echo "磁盘使用: $DISK"
}
# 主函数
main() {
echo "LAMP 状态监控 - $(date)"
echo "========================"
MYSQL_PASS="your_mysql_password"
check_system
check_apache
check_php
check_mysql
}
main
3. 备份脚本
bash
#!/bin/bash
# lamp_backup.sh - LAMP备份脚本
# 配置
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
MYSQL_USER="root"
MYSQL_PASS="your_mysql_password"
WEB_ROOT="/var/www/html"
APACHE_CONF="/etc/httpd /etc/apache2"
PHP_CONF="/etc/php.ini /etc/php.d"
MYSQL_CONF="/etc/my.cnf /etc/mysql"
RETENTION_DAYS=7
# 创建备份目录
mkdir -p $BACKUP_DIR/{mysql,web,conf,logs}
# 备份MySQL
echo "备份MySQL数据库..."
mysql -u$MYSQL_USER -p$MYSQL_PASS -e "SHOW DATABASES;" | grep -Ev "Database|information_schema|performance_schema|mysql|sys" | while read db; do
mysqldump -u$MYSQL_USER -p$MYSQL_PASS --opt --routines --triggers --events $db | gzip > $BACKUP_DIR/mysql/${db}_$DATE.sql.gz
echo " ✓ 备份数据库: $db"
done
# 备份网站文件
echo "备份网站文件..."
tar -czf $BACKUP_DIR/web/web_files_$DATE.tar.gz $WEB_ROOT
echo " ✓ 网站文件备份完成"
# 备份配置文件
echo "备份配置文件..."
tar -czf $BACKUP_DIR/conf/apache_conf_$DATE.tar.gz $APACHE_CONF 2>/dev/null
tar -czf $BACKUP_DIR/conf/php_conf_$DATE.tar.gz $PHP_CONF 2>/dev/null
tar -czf $BACKUP_DIR/conf/mysql_conf_$DATE.tar.gz $MYSQL_CONF 2>/dev/null
echo " ✓ 配置文件备份完成"
# 删除旧备份
find $BACKUP_DIR -type f -mtime +$RETENTION_DAYS -delete
echo "备份完成!"
九、常见问题排查
1. Apache常见问题
bash
# 检查Apache配置
httpd -t
apache2ctl configtest
# 查看错误日志
tail -f /var/log/httpd/error_log
tail -f /var/log/apache2/error.log
# 检查端口冲突
netstat -tlnp | grep :80
# 权限问题
chown -R apache:apache /var/www/html
chmod -R 755 /var/www/html
# 重载配置
systemctl reload httpd
apachectl graceful
# 查看加载的模块
httpd -M
2. PHP常见问题
bash
# 检查PHP配置
php -v
php -m
php -i | grep memory_limit
# 查看PHP错误日志
tail -f /var/log/php-fpm/error.log
tail -f /var/log/apache2/error.log | grep PHP
# 测试PHP文件
echo "<?php phpinfo(); ?>" > /var/www/html/test.php
# 检查PHP模块
php -m | grep mysql
php -m | grep gd
# 修改PHP配置后重启
systemctl restart httpd
3. MySQL常见问题
bash
# 检查MySQL状态
systemctl status mysqld
# 查看错误日志
tail -f /var/log/mysql/error.log
# 测试连接
mysql -u root -p -e "SELECT 1"
# 查看进程
mysql -e "SHOW PROCESSLIST;"
# 修复表
mysqlcheck -u root -p --auto-repair --all-databases
# 查看数据库大小
mysql -e "SELECT table_schema,
ROUND(SUM(data_length+index_length)/1024/1024,2) AS 'Size(MB)'
FROM information_schema.tables
GROUP BY table_schema;"
4. 性能问题排查
bash
# 检查Apache访问统计
cat /var/log/httpd/access_log | awk '{print $1}' | sort | uniq -c | sort -nr | head
# 查看Apache状态
curl http://localhost/server-status
# 分析慢查询
mysqldumpslow /var/log/mysql/slow.log
# 查看PHP-FPM状态(如果使用)
curl http://localhost/status
# 系统负载
top
htop
vmstat 1
iostat -x