在Linux上实现Laravel项目的自动化部署可以通过多种方式来完成,以下是一个基本的步骤指南,使用Git进行版本控制,并结合SSH和Shell脚本来实现自动化部署。
配置Nginx或Apache以指向你的Laravel项目的public
目录。
Nginx示例配置:
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;
}
}
在本地机器上生成SSH密钥对,并将公钥添加到服务器的~/.ssh/authorized_keys
文件中。
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
cat ~/.ssh/id_rsa.pub | ssh user@your_server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
在项目根目录下创建一个部署脚本,例如deploy.sh
。
#!/bin/bash
# 设置变量
REPO_URL="git@github.com:your_username/your_laravel_project.git"
DEPLOY_DIR="/path/to/your/laravel/project"
BRANCH="main"
# 进入项目目录
cd $DEPLOY_DIR
# 拉取最新代码
git pull origin $BRANCH
# 安装依赖
composer install --no-interaction --prefer-dist --optimize-autoloader
# 运行迁移
php artisan migrate --force
# 清理缓存
php artisan config:clear
php artisan cache:clear
php artisan view:clear
# 重启Web服务器
sudo systemctl restart nginx
echo "Deployment completed successfully!"
确保脚本有执行权限:
chmod +x deploy.sh
你可以使用Jenkins、GitLab CI、GitHub Actions等工具来自动化部署过程。
GitHub Actions示例:
在项目根目录下创建.github/workflows/deploy.yml
文件:
name: Deploy to Production
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '7.4'
- name: Install dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader
- name: Run migrations
run: php artisan migrate --force
- name: Clear cache
run: |
php artisan config:clear
php artisan cache:clear
php artisan view:clear
- name: Restart Nginx
run: sudo systemctl restart nginx
通过上述步骤,你可以在Linux上实现Laravel项目的自动化部署。你可以选择手动运行部署脚本,或者使用CI/CD工具来自动化整个过程。根据你的需求和项目规模,选择最适合的方法。