实现php自动部署
PHP自动部署的实现方法
使用Git钩子实现自动部署
在服务器上配置Git的post-receive钩子,当代码推送到远程仓库时自动触发部署脚本。在服务器的Git仓库中创建hooks/post-receive文件并添加执行权限:
#!/bin/sh
TARGET="/var/www/your_project"
GIT_DIR="/path/to/your/git/repo.git"
BRANCH="master"
while read oldrev newrev ref
do
if [[ $ref = refs/heads/$BRANCH ]];
then
echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
cd $TARGET
composer install --no-dev
php artisan migrate --force
else
echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed."
fi
done
使用Webhook实现自动部署
在代码托管平台(如GitHub、GitLab)设置Webhook,当有代码推送时触发服务器端的部署脚本。创建接收Webhook的PHP脚本:
<?php
$secret = 'your_secret_key';
$branch = 'refs/heads/master';
$target_dir = '/var/www/your_project';
$headers = getallheaders();
$hubSignature = $headers['X-Hub-Signature'];
list($algo, $hash) = explode('=', $hubSignature, 2);
$payload = file_get_contents('php://input');
$payloadHash = hash_hmac($algo, $payload, $secret);
if ($hash !== $payloadHash) {
die('Invalid secret');
}
$payload = json_decode($payload, true);
if ($payload['ref'] === $branch) {
exec("cd {$target_dir} && git pull origin master");
exec("cd {$target_dir} && composer install --no-dev");
exec("cd {$target_dir} && php artisan migrate --force");
echo "Deployment successful";
} else {
echo "Push received but not deploying";
}
使用部署工具实现自动部署
配置专业部署工具如Deployer、Capistrano或Envoyer,这些工具提供更完善的部署流程:
-
安装Deployer:
curl -LO https://deployer.org/deployer.phar mv deployer.phar /usr/local/bin/dep chmod +x /usr/local/bin/dep -
创建
deploy.php配置文件:<?php namespace Deployer;
require 'recipe/laravel.php';

set('application', 'Your Project'); set('repository', 'git@github.com:your/repo.git'); set('git_tty', true); set('keep_releases', 3);
host('your_server_ip') ->set('deploy_path', '/var/www/your_project') ->set('identityFile', '~/.ssh/id_rsa') ->set('user', 'deployer');
after('deploy:failed', 'deploy:unlock');

3. 执行部署命令:
```bash
dep deploy
使用CI/CD管道实现自动部署
配置持续集成服务如GitHub Actions、GitLab CI或Jenkins来自动化测试和部署流程。示例GitHub Actions工作流文件:
name: Deploy
on:
push:
branches: [ master ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install dependencies
run: composer install --no-dev
- name: Run tests
run: phpunit
- name: Deploy to production
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /var/www/your_project
git pull origin master
composer install --no-dev
php artisan migrate --force
部署后的常见操作
自动清除缓存和优化应用:
php artisan cache:clear
php artisan view:clear
php artisan route:cache
php artisan config:cache
设置正确的文件权限:
chown -R www-data:www-data /var/www/your_project
chmod -R 755 /var/www/your_project/storage
重启PHP-FPM服务:
systemctl restart php-fpm






