在Debian系統中進行Laravel項目的持續集成(CI)可以通過多種方式實現,其中最常用的是使用Git作為版本控制系統,并結合CI工具如Jenkins、GitLab CI/CD、GitHub Actions等。以下是一個基本的步驟指南,使用GitLab CI/CD作為示例:
首先,確保你的Debian系統上安裝了以下軟件:
你可以使用以下命令來安裝這些軟件:
sudo apt update
sudo apt install git php php-cli php-fpm mysql-server nginx composer
創建一個新的數據庫并配置Laravel項目使用它:
sudo mysql -u root -p
在MySQL shell中:
CREATE DATABASE laravel_ci;
CREATE USER 'laravel_ci_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON laravel_ci.* TO 'laravel_ci_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
在Laravel項目的根目錄下,編輯.env
文件以匹配你的數據庫配置:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ci
DB_USERNAME=laravel_ci_user
DB_PASSWORD=password
在項目根目錄下創建一個.gitlab-ci.yml
文件,定義CI/CD流程:
stages:
- test
- deploy
variables:
DEPLOY_ENV: production
test:
stage: test
script:
- composer install --no-interaction --prefer-dist
- php artisan migrate
- php artisan test
deploy:
stage: deploy
script:
- ssh -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_SERVER "bash -s" < deploy_script.sh
only:
- master
在項目根目錄下創建一個deploy_script.sh
文件,用于自動化部署:
#!/bin/bash
# 停止Nginx
sudo systemctl stop nginx
# 備份舊代碼
sudo cp -r /var/www/laravel_ci /var/www/laravel_ci_backup_$(date +%F)
# 拉取最新代碼
sudo git pull origin master
# 安裝依賴
cd /var/www/laravel_ci
composer install --no-interaction --prefer-dist
# 運行遷移
php artisan migrate
# 重啟Nginx
sudo systemctl start nginx
確保deploy_script.sh
有執行權限:
chmod +x deploy_script.sh
在GitLab CI/CD設置中添加SSH密鑰,以便CI/CD可以安全地連接到你的服務器:
SSH_PRIVATE_KEY
的變量,值為你的SSH私鑰。在.gitlab-ci.yml
中配置SSH訪問:
deploy:
stage: deploy
before_script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
script:
- ssh -o StrictHostKeyChecking=no $DEPLOY_USER@$DEPLOY_SERVER "bash -s" < deploy_script.sh
only:
- master
確保你的Nginx配置文件正確指向Laravel項目的public目錄。例如:
server {
listen 80;
server_name your_domain.com;
root /var/www/laravel_ci/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;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
確保你的GitLab Runner已經注冊并配置好,然后在項目根目錄下運行:
gitlab-ci run --config .gitlab-ci.yml
這樣,你的Laravel項目就會在每次提交到master分支時自動進行測試和部署。
通過以上步驟,你可以在Debian系統中實現Laravel項目的持續集成。根據具體需求,你可以進一步優化和擴展CI/CD流程。