IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> PHP知识库 -> php deployer 从入门到精通 -> 正文阅读

[PHP知识库]php deployer 从入门到精通

安装lnmp 环境 (centos 7)

安装 nginx

yum -y install gcc gcc-c++ autoconf automake make yum install pcre-devel -y yum install zlib -y
yum install openssl openssl-devel
wget  http://nginx.org/download/nginx-1.20.2.tar.gz
tar -zxvf nginx-1.20.2.tar.gz && cd nginx-1.20.2 && ./configure --prefix=/usr/local/nginx


安装 mysql5.7

wget http://repo.mysql.com/mysql57-community-release-el7-9.noarch.rpm
sudo rpm -ivh mysql57-community-release-el7-9.noarch.rpm
yum -y install mysql-community-server --nogpgcheck
systemctl start mysqld
grep 'temporary password' /var/log/mysqld.log
ALTER USER 'root'@'localhost' IDENTIFIED BY '@abcd123456';
systemctl enable mysqld

安装php7.4

yum install libxml2-devel bzip2 bzip2-devel curl-devel libjpeg-devel libpng libpng-devel freetype-devel libxslt-devel libzip-devel -y
yum install libtool sqlite-devel epel-release -y 
rpm -ivh http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum install -y oniguruma oniguruma-devel
yum clean all && yum makecache
wget https://www.php.net/distributions/php-7.4.26.tar.gz && tar -zxvf php-7.4.26.tar.gz && cd php-7.4.26
./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --with-fpm-user=mysql --with-fpm-group=mysql --with-curl  --with-gettext --with-iconv-dir --with-kerberos --with-libdir=lib64  --with-mysqli=mysqlnd --with-openssl  --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd --with-pdo-sqlite --with-pear  --with-xmlrpc --with-xsl --with-zlib --with-bz2 --with-mhash --enable-fpm --enable-bcmath  --enable-inline-optimization --enable-mbregex --enable-mbstring --enable-opcache --enable-pcntl --enable-shmop --enable-soap --enable-sockets --enable-sysvsem --enable-sysvshm --enable-xml --enable-fpm
cp php.ini-production /usr/local/php/etc/php.ini
cp /usr/local/php/etc/php-fpm.d/www.conf.default  /usr/local/php/etc/php-fpm.d/www.conf
cp /root/software/php7.4/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod 755 /etc/init.d/php-fpm

ln -s /usr/local/php/bin/php /usr/local/bin/php

# 查看php.ini位置
php -i | grep php.ini

安装composer

curl -sS https://getcomposer.org/installer | php
mv composer.phar  /usr/local/bin/composer
composer config -g repo.packagist composer https://packagist.phpcomposer.com

安装deployer (我们安装的是最新的版本7.x,部分函数与6.x不一样)

mkdir /root/dep && cd dep
#第一种:通过 Phar 存档,只需运行一下命令即可
curl -LO https://deployer.org/deployer.phar
mv deployer.phar /usr/local/bin/dep
#第二种:通过 composer 安装
chmod +x /usr/local/bin/dep
composer require --dev deployer/deployer
#将别名添加到.bashrc文件中
alias dep='/root/dep/vendor/bin/dep'
source .bash_profile
#第三种:通过 Github 源代码安装:clone 最新的代码
1. git clone https://github.com/deployphp/deployer.git  
2. 在源代码目录下运行:
php ./build

?开始使用deployer

?dep init

?我们选择0,1是以配置的形式,我没有使用过(配置完成后用Import 导入即可)自己可以实验一下

这里有各种框架使用的模板,只需要在deployer.php 引用即可。不过使用的时候要注意跟自己的业务逻辑有没有冲突,尤其是清除缓存,有些redis 缓存不能删除,所以我本人一般不使用模板(直接选择2 common),另外很多框架和php系统也没有,私人定制似乎更好一些,在这里需要注意一点,必须设置php全局变量,因为deployer 默认命令是在/usr/lcoal/bin/php中 (现在以thinkphp 为例子)

<?php

namespace Deployer;
require 'recipe/common.php';
use Deployer\Exception\GracefulShutdownException;
add('recipes', ['thinkphp']);
set('writable_dirs', [
    'runtime',
]);
set('thinkphp_version', function () {
    $result = run('{{bin/php}} {{release_or_current_path}}/think --version');
    preg_match_all('/(\d+\.?)+/', $result, $matches);
    return $matches[0][0] ?? 6.0;
});

/**
 * Run an artisan command.
 *
 * Supported options:
 * - 'min' => #.#: The minimum think version required (included).
 * - 'max' => #.#: The maximum think version required (included).
 * - 'skipIfNoEnv': Skip and warn the user if `.env` file is inexistant or empty.
 * - 'failIfNoEnv': Fail the command if `.env` file is inexistant or empty.
 * - 'showOutput': Show the output of the command if given.
 *
 * @param string $command The artisan command (with cli options if any).
 * @param array $options The options that define the behaviour of the command.
 * @return callable A function that can be used as a task.
 */
function think($command, $options = [])
{
    return function () use ($command, $options) {

        // Ensure the think command is available on the current version.
        $versionTooEarly = array_key_exists('min', $options)
            && thinkphp_version_compare($options['min'], '<');

        $versionTooLate = array_key_exists('max', $options)
            && thinkphp_version_compare($options['max'], '>');

        if ($versionTooEarly || $versionTooLate) {
            return;
        }

        // Ensure we warn or fail when a command relies on the ".env" file.
        if (in_array('failIfNoEnv', $options) && !test('[ -s {{release_or_current_path}}/.env ]')) {
            throw new \Exception('Your .env file is empty! Cannot proceed.');
        }

        if (in_array('skipIfNoEnv', $options) && !test('[ -s {{release_or_current_path}}/.env ]')) {
            warning("Your .env file is empty! Skipping...</>");
            return;
        }

        $think = '{{release_or_current_path}}/think';

        // Run the artisan command.
        $output = run("{{bin/php}} $think $command");

        // Output the results when appropriate.
        if (in_array('showOutput', $options)) {
            writeln("<info>$output</info>");
        }
    };
}

function think_version_compare($version, $comparator)
{
    return version_compare(get('thinkphp_version'), $version, $comparator);
}

/*
 * Maintenance mode.
 */
set('keep_releases', 5);
host('hostA')
    ->setRemoteUser('root')
    ->setPort(22)
    ->setDeployPath("/home/service/{{application}}")
    ->set('branch', 'master') // 最新的主分支部署到生产机
    ->setConfigFile("/root/.ssh/config")
    ->setForwardAgent(true)
    ->setSshMultiplexing(true)
    ->set('http_user', 'www') // 这个与 nginx 里的配置一致
    ->setSshArguments(['-o StrictHostKeyChecking=no', '-o UserKnownHostsFile=/dev/null']);
desc("清除runtime,模板缓存,路由缓存");
task("thinkphp:clear",think("clear",['showOutput']));
desc("生成路由缓存");
task("optimize:route",think("optimize:route",['showOutput']));
desc("重启php");
task('php-fpm:restart', function () {
    run('systemctl restart php-fpm');
});
desc("部署成功,自定义通知");
task("send_message",function(){
    echo "部署成功!";
});
desc("生成数据表缓存");
task("optimize:schema",think("optimize:schem",['showOutput']));
/**
 * Main deploy task.
 */
after('deploy:symlink', 'php-fpm:restart');
after('deploy:success', 'send_message');
after('deploy:failed', 'deploy:unlock');;
// Config
set('application', 'thinkphp');
set('repository', 'git@gitee.com:afgadfas/think.git');
set('git_tty', true);

// Hosts
task("deploy:over", function () {
    run("chmod -R 755 {{deploy_path}} && chown www.www -R {{deploy_path}}");
});
desc('部署项目');
// Hooks
task('deploy', [
    'deploy:prepare', // 登录服务器
    'deploy:release', // 创建发布目录
    'deploy:update_code', // 下载源代码
    'deploy:vendors', // 更新composer
    'deploy:publish',
    'thinkphp:clear',
    'optimize:route',
    'optimize:schema',
    'deploy:over',
]);
after('deploy:failed', 'deploy:unlock');

?接下来我们将详细讲解一下各个命令的作用

set(string $name, $value): void?设置配置选项

task(string $name, $body = null): Task?定义新任务并保存到任务列表

add(string $name, array $array): void??将新的配置参数合并到现有的配置数组。

run(string $command, ?array $options = [], ?int $timeout = null, ?int $idle_timeout = null, ?string $secret = null, ?array $env = null, ?bool $real_time_output = false, ?bool $no_throw = false): string??在远程主机上执行给定的命令

这几个命令比较常用,自己随便练习一下就能很快知道使用规则 更多命令

脚本最主要的是配置公钥和私钥,主要是ssh远程登陆,和github(我们这里以gitee作为说明)

1.ssh登陆的公钥和私钥,在本地生成(也就是php客户端,不是服务器)我本地用的是虚拟机(linux)环境,因为我在windows 环境下使用deployer无法连接ssh,如果你能连接请告诉我。

ssh-keygen 输入文件名称,然后一路回车,如果你不输入名称,gitee生成公钥和私钥就会覆盖ssh的公钥私钥。因为默认名称都是id_rsa。生成文件的位置是在当前用户.ssh目录下(/root/.ssh)

?把公钥id_rsa.pub 复制到服务器/root/.ssh下的authorized_keys 多个公钥只需要在后面追加即可

编辑config 文件 配置ssh信息,我的是

hostA 即是ssh 配置信息,host gitee.com 是gitee的配置

同理配置gitee ,然后把laravel-admin.pub 复制到gitee.com ssh keys中

常见的部署命令

#清理旧的发布版本 (只保留最近两个)
dep deploy:cleanup
#覆盖回滚候选 如果没有-o 选项直接回滚到上一个版本 (回滚后会生成一个新版本)
dep rollback -o rollback_candidate=123
#删除文件锁
dep deploy:unlock
#发布 host是要发布的环境,也即是config文件对应的
dep deploy hostA 

#如果要查看发布日志dep deploy hostA -vvv

遇见的问题,deploy:cleanup不起作用

我在开启了deploy:cleanup 后发现每次都把所有的旧版本都清理了,经过多次测试,并且查看了相关源码,release_log

?这个release_log 记录了所有部署过程中 的日志,只要是成功的,就有两个一样的日记录,是部署开始和部署结束,部署失败只有一条记录。而cleanup这个命令的代码

?releases_list 获取的是所有成功的日志,这样每个版本就会有两个一样的版本,假如总共有3个版本,release_list 获取的是6条记录的日志,这样array_slice 切割就会出现错误。正确的做法是用array_unique 过滤一下重复的,正确的做法是这样的

?所以cleanup 需要重写,或者重新定义。

现在自定义一个thinkphp的发布

  PHP知识库 最新文章
Laravel 下实现 Google 2fa 验证
UUCTF WP
DASCTF10月 web
XAMPP任意命令执行提升权限漏洞(CVE-2020-
[GYCTF2020]Easyphp
iwebsec靶场 代码执行关卡通关笔记
多个线程同步执行,多个线程依次执行,多个
php 没事记录下常用方法 (TP5.1)
php之jwt
2021-09-18
上一篇文章      下一篇文章      查看所有文章
加:2022-09-04 00:50:49  更:2022-09-04 00:50:57 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/5 8:35:54-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码