在Linux上实现Laravel项目的自动化部署,可以使用多种工具和方法。以下是一个常见的使用Git、SSH、PHP和Shell脚本的自动化部署流程:
确保你的Linux服务器上已经安装了以下软件:
为了安全地从本地机器部署到服务器,你需要配置SSH密钥。
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
cat ~/.ssh/id_rsa.pub
将公钥添加到服务器的~/.ssh/authorized_keys文件中。
server {
listen 80;
server_name example.com;
root /path/to/your/laravel/project/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
<VirtualHost *:80>
ServerName example.com
DocumentRoot /path/to/your/laravel/project/public
<Directory /path/to/your/laravel/project/public>
AllowOverride All
Require all granted
</Directory>
<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>
创建一个Shell脚本来自动化部署过程。
#!/bin/bash
# 配置变量
REPO_URL="git@example.com:username/laravel-project.git"
BRANCH="main"
DEPLOY_DIR="/path/to/your/laravel/project"
BACKUP_DIR="/path/to/backup"
# 进入项目目录
cd $DEPLOY_DIR
# 拉取最新代码
git pull origin $BRANCH
# 安装依赖
composer install --no-interaction --prefer-dist --optimize-autoloader
# 备份旧版本
TIMESTAMP=$(date +%Y%m%d%H%M%S)
BACKUP_FILE="$BACKUP_DIR/backup-$TIMESTAMP.tar.gz"
tar -czf $BACKUP_FILE -C $DEPLOY_DIR .
# 清理缓存
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
# 运行迁移
php artisan migrate --force
# 重启Web服务器
systemctl restart nginx # 或 systemctl restart apache2
# 删除旧备份
find $BACKUP_DIR -type f -name "*.tar.gz" -mtime +7 -exec rm {} \;
使用cron来定期运行部署脚本。
crontab -e
添加以下行来每天凌晨2点运行部署脚本:
0 2 * * * /path/to/deploy.sh
确保你的部署脚本和Web服务器配置文件具有适当的权限。
chmod +x /path/to/deploy.sh
chown www-data:www-data /path/to/deploy.sh
手动运行部署脚本以确保一切正常:
/path/to/deploy.sh
通过以上步骤,你可以在Linux上实现Laravel项目的自动化部署。根据你的具体需求和环境,可能需要调整配置和脚本。