以下是在 WSL2 (Ubuntu 24.04 LTS) 上搭建 PHP + Nginx + MySQL + Redis 环境的完整步骤:
1. 准备工作
确保已安装 WSL2 并运行 Ubuntu 24.04(若未安装,参考上一教程)。
打开 Ubuntu 终端,更新系统:
sudo apt update && sudo apt upgrade -y
2. 安装 Nginx
sudo apt install nginx -y
启动 Nginx 并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
验证 Nginx 是否运行:
curl http://localhost
(如果返回 Welcome to nginx!
说明安装成功)
3. 安装 MySQL (MariaDB)
Ubuntu 24.04 默认使用 MariaDB(MySQL 兼容):
sudo apt install mariadb-server mariadb-client -y
初始化 MySQL 安全设置:
sudo mysql_secure_installation
(按提示设置 root 密码,并选择安全选项)
登录 MySQL:
sudo mysql -u root -p
(输入密码后进入 MySQL Shell)
4. 安装 PHP 8.3(Ubuntu 24.04 默认版本)
sudo apt install php-fpm php-mysql php-redis php-cli php-curl php-gd php-mbstring php-xml php-zip -y
检查 PHP 版本:
php -v
启动 PHP-FPM:
sudo systemctl start php8.3-fpm
sudo systemctl enable php8.3-fpm
5. 安装 Redis
sudo apt install redis-server -y
启动 Redis:
sudo systemctl start redis-server
sudo systemctl enable redis-server
测试 Redis:
redis-cli ping
(返回 PONG
说明 Redis 正常运行)
6. 配置 Nginx + PHP-FPM
编辑 Nginx 默认站点配置:
sudo nano /etc/nginx/sites-available/default
修改 server
部分(确保 PHP-FPM 处理 .php
文件):
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
测试 Nginx 配置:
sudo nginx -t
重启 Nginx:
sudo systemctl restart nginx
7. 测试 PHP
创建测试文件:
sudo nano /var/www/html/info.php
写入:
<?php phpinfo(); ?>
访问 http://localhost/info.php
,应显示 PHP 信息页。
8. 可选优化
(1)调整 PHP-FPM 进程管理
编辑 /etc/php/8.3/fpm/pool.d/www.conf
:
pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 8
重启 PHP-FPM:
sudo systemctl restart php8.3-fpm
(2)启用 Redis 扩展
确保 php-redis
已安装,在 PHP 脚本中测试:
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo $redis->ping(); // 应返回 "+PONG"
?>
(3)MySQL 远程访问(可选)
如果需要从 Windows 访问 WSL2 的 MySQL:
sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
修改 bind-address
:
bind-address = 0.0.0.0
然后重启 MySQL:
sudo systemctl restart mariadb
9. 访问服务
- Nginx:
http://localhost
(Windows 浏览器直接访问) - MySQL:
- WSL2 内:
mysql -u root -p
- Windows 可用 MySQL Workbench 连接
127.0.0.1:3306
- WSL2 内:
- Redis:
- WSL2 内:
redis-cli
- Windows 可用 Redis Desktop Manager 连接
127.0.0.1:6379
- WSL2 内:
10. 总结
✅ 环境搭建完成:
- Nginx 运行在
80
端口 - PHP 8.3-FPM 处理动态请求
- MySQL (MariaDB) 提供数据库支持
- Redis 作为缓存/会话存储
🚀 下一步:
- 部署 Laravel、WordPress 等 PHP 项目
- 使用
supervisor
管理进程 - 配置 HTTPS(
certbot
申请 SSL 证书)
如果有问题,可以检查日志:
# Nginx 错误日志
sudo tail -f /var/log/nginx/error.log
# PHP-FPM 日志
sudo tail -f /var/log/php8.3-fpm.log
# MySQL 日志
sudo tail -f /var/log/mysql/error.log