在Linux上实现Laravel的自动化部署可以通过多种方式来完成,以下是一个基本的步骤指南,使用Git进行版本控制,并结合CI/CD工具(如Jenkins、GitLab CI或GitHub Actions)来实现自动化部署。

确保你的服务器已经安装了必要的软件:
sudo apt updatesudo 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=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=your_databaseDB_USERNAME=your_usernameDB_PASSWORD=your_password在你的项目目录中初始化Git仓库:
cd /var/www/laravel-appgit initgit add .git commit -m "Initial commit"这里以GitHub Actions为例:
.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 nginx确保你的GitHub Actions可以SSH访问你的服务器。生成SSH密钥并将其添加到GitHub仓库的SSH keys中:
ssh-keygen -t rsa -b 4096 -C "[email protected]"cat ~/.ssh/id_rsa.pub将公钥添加到GitHub仓库的SSH keys中。
在服务器上创建一个SSH密钥并添加到GitHub:
ssh-keygen -t rsa -b 4096 -C "[email protected]"cat ~/.ssh/id_rsa.pub将公钥添加到GitHub账户的SSH keys中。
推送代码到GitHub的main分支,触发CI/CD流程,检查部署是否成功。
通过以上步骤,你可以在Linux上实现Laravel的自动化部署。根据你的具体需求,你可以进一步自定义和优化这个流程。