最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
如何在Linux上实现Laravel的自动化部署
时间:2026-08-03 12:14:48 编辑:袖梨 来源:一聚教程网
在Linux上实现Laravel的自动化部署可以通过多种方式来完成,以下是一个基本的步骤指南,使用Git进行版本控制,并结合CI/CD工具(如Jenkins、GitLab CI或GitHub Actions)来实现自动化部署。

前提条件
- Linux服务器:确保你有一个运行Linux的服务器。
- Web服务器:如Nginx或Apache。
- PHP环境:确保服务器上安装了PHP及其必要的扩展。
- 数据库:如MySQL或PostgreSQL。
- Git:用于版本控制。
- CI/CD工具:如Jenkins、GitLab CI或GitHub Actions。
步骤指南
1. 设置服务器环境
确保你的服务器已经安装了必要的软件:
sudo apt updatesudo apt install nginx php-fpm mysql-server git2. 配置Web服务器
配置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;}}3. 配置数据库
创建一个新的数据库并配置Laravel使用它。编辑.env文件:
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=your_databaseDB_USERNAME=your_usernameDB_PASSWORD=your_password4. 初始化Git仓库
在你的项目目录中初始化Git仓库:
cd /var/www/laravel-appgit initgit add .git commit -m "Initial commit"5. 设置CI/CD工具
这里以GitHub Actions为例:
- 在你的GitHub仓库中,创建一个新的工作流文件
.github/workflows/deploy.yml:
name: Deploy Laravelon:push:branches:- mainjobs:deploy:runs-on: ubuntu-lateststeps:- name: Checkout codeuses: actions/checkout@v2- name: Install dependenciesrun: |sudo apt updatesudo apt install -y php-curl php-mysql php-zip unzipcd /var/www/laravel-appcomposer install --no-interaction --prefer-dist- name: Configure environment variablesrun: |echo "DB_DATABASE=your_database" >> $GITHUB_ENVecho "DB_USERNAME=your_username" >> $GITHUB_ENVecho "DB_PASSWORD=your_password" >> $GITHUB_ENV- name: Run migrationsrun: |cd /var/www/laravel-appphp artisan migrate --force- name: Optimizerun: |cd /var/www/laravel-appphp artisan optimize- name: Restart Nginxrun: sudo systemctl restart nginx6. 配置SSH访问
确保你的GitHub Actions可以SSH访问你的服务器。生成SSH密钥并将其添加到GitHub仓库的SSH keys中:
ssh-keygen -t rsa -b 4096 -C "[email protected]"cat ~/.ssh/id_rsa.pub将公钥添加到GitHub仓库的SSH keys中。
7. 配置服务器上的SSH密钥
在服务器上创建一个SSH密钥并添加到GitHub:
ssh-keygen -t rsa -b 4096 -C "[email protected]"cat ~/.ssh/id_rsa.pub将公钥添加到GitHub账户的SSH keys中。
8. 测试部署
推送代码到GitHub的main分支,触发CI/CD流程,检查部署是否成功。
通过以上步骤,你可以在Linux上实现Laravel的自动化部署。根据你的具体需求,你可以进一步自定义和优化这个流程。