在Linux上实现Laravel的自动化部署可以通过多种方式来完成,以下是一个基本的步骤指南,使用Git进行版本控制,并结合CI/CD工具(如Jenkins、GitLab CI或GitHub Actions)来实现自动化部署。
确保你的服务器已经安装了必要的软件:
sudo apt update
sudo apt install nginx php-fpm mysql-server git
配置Nginx以指向你的Laravel项目目录。假设你的项目目录是/var/www/laravel-app:
server {
listen 80;
server_name yourdomain.com;
root /var/www/laravel-app;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
创建一个新的数据库并配置Laravel使用它。编辑.env文件:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
在你的项目目录中初始化Git仓库:
cd /var/www/laravel-app
git init
git add .
git commit -m "Initial commit"
这里以GitHub Actions为例:
.github/workflows/deploy.yml:name: Deploy Laravel
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Install dependencies
run: |
sudo apt update
sudo apt install -y php-curl php-mysql php-zip unzip
cd /var/www/laravel-app
composer install --no-interaction --prefer-dist
- name: Configure environment variables
run: |
echo "DB_DATABASE=your_database" >> $GITHUB_ENV
echo "DB_USERNAME=your_username" >> $GITHUB_ENV
echo "DB_PASSWORD=your_password" >> $GITHUB_ENV
- name: Run migrations
run: |
cd /var/www/laravel-app
php artisan migrate --force
- name: Optimize
run: |
cd /var/www/laravel-app
php artisan optimize
- name: Restart Nginx
run: sudo systemctl restart nginx
确保你的GitHub Actions可以SSH访问你的服务器。生成SSH密钥并将其添加到GitHub仓库的SSH keys中:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
cat ~/.ssh/id_rsa.pub
将公钥添加到GitHub仓库的SSH keys中。
在服务器上创建一个SSH密钥并添加到GitHub:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
cat ~/.ssh/id_rsa.pub
将公钥添加到GitHub账户的SSH keys中。
推送代码到GitHub的main分支,触发CI/CD流程,检查部署是否成功。
通过以上步骤,你可以在Linux上实现Laravel的自动化部署。根据你的具体需求,你可以进一步自定义和优化这个流程。