yogarine / wait-for-it.php
Giles Hall 的 wait-for-it.sh 脚本的 PHP 实现。
Requires
- php: >=7.0
- ext-pcntl: *
README
wait-for-it.php 是 Gilles Hall 的 wait-for-it.sh 脚本的 PHP 实现,可以通过 wait-for-it.sh。
它既可以作为一个独立的可执行文件运行,也可以包含在 PHP 中,通过调用 wait_for_it() 函数来使用。作为独立脚本,它可以作为 wait-for-it.sh 的直接替代品。
使用方法
从命令行
wait-for-it.php <host>[:<port> | -p <port>] [options] [--] [command [args]]
wait-for-it.php -h <host> -p <port> [options] [--] [command [args]]
-h <host>, --host=<host> Host or IP under test
-p <port>, --port=<port> TCP port under test. Alternatively, you specify the
host and port as host:port
-s, --strict Only execute subcommand if the test succeeds
-q, --quiet Don't output any status messages
-t <timeout>, --timeout=<timeout>
Timeout in seconds, zero for no timeout
-- command args Execute command with args after the test finishes
从 PHP
function wait_for_it(string $address, int $timeout = 15, float &$time_waited = null): bool {}
安装
作为 Composer 包
您可以将它全局安装,用作独立命令
composer global require yogarine/wait-for-it
您也可以将 wait-for-it.php 作为您项目的依赖项安装
composer require yogarine/wait-for-it
这将允许您使用 wait_for_it()
函数。
Docker
wait-for-it.php 也可以作为 Docker 镜像使用
docker run yogarine/wait-for-it www.google.com:80 -- echo "google is up"
您也可以轻松地将脚本复制到自己的 Dockerfile 中
# Copy wait-for-it.php from it's official Docker image. COPY --from=yogarine/wait-for-it /usr/local/bin/wait-for-it /usr/local/bin/
只需记住,您需要安装 pcntl 扩展。
PHP 代码中的使用
当作为 Composer 包安装时,wait-for-it.php
会自动作为辅助文件包含,并声明 wait_for_it()
函数。
它将等待并返回 host 是否启动,如果是则返回 true
,否则返回 false
。
示例
例如,让我们测试是否能访问 www.google.com
的 80 端口,如果可用,则输出消息 google is up
。
$ vendor/bin/wait-for-it -t 0 www.google.com:80 -- echo "google is up" www.google.com:80 -- echo "google is up" wait-for-it: waiting 15 seconds for www.google.com:80 wait-for-it: www.google.com:80 is available after 0 seconds google is up
您可以使用 -t
或 --timeout=
选项设置自己的超时时间。将超时值设置为 0 将禁用超时
$ vendor/bin/wait-for-it -t 0 www.google.com:80 -- echo "google is up" wait-for-it: waiting for www.google.com:80 without a timeout wait-for-it: www.google.com:80 is available after 0 seconds google is up
子命令将在服务是否启动的情况下都会执行。如果您只想在服务启动时执行子命令,请添加 --strict
参数。在这个例子中,我们将测试 www.google.com
上的 81 端口,这将失败
$ vendor/bin/wait-for-it www.google.com:81 --timeout=1 --strict -- echo "google is up" wait-for-it: waiting 1 seconds for www.google.com:81 wait-for-it: timeout occurred after waiting 1 seconds for www.google.com:81 wait-for-it: strict mode, refusing to execute subprocess
如果您不想执行子命令,请省略 --
参数。这样,您可以在自己的脚本中测试 wait-for-it.php
的退出条件,并确定如何进行下一步
$ vendor/bin/wait-for-it www.google.com:80 wait-for-it: waiting 15 seconds for www.google.com:80 wait-for-it: www.google.com:80 is available after 0 seconds $ echo $? 0 $ vendor/bin/wait-for-it www.google.com:81 wait-for-it: waiting 15 seconds for www.google.com:81 wait-for-it: timeout occurred after waiting 15 seconds for www.google.com:81 $ echo $? 124