在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流程。