【问题标题】:Trying to call an url of service in docker with bitbucket pipelines尝试使用 bitbucket 管道在 docker 中调用服务的 url
【发布时间】:2018-11-30 13:34:25
【问题描述】:

我正在尝试测试我的服务是否在 docker 容器中运行良好,所以我想调用 url 'http://localhost:3000/test' 并检查它是否为 200。在所有其他情况下,我想让我的 bitbucket 管道失败。

所以一开始我试图卷曲它,但我没有得到任何输出或错误。

curl -f "http://localhost:3000/test" || exit 1

但无论如何它都会通过它,即使 url 错误或容器根本没有运行。

然后我尝试在容器中调用wget,但我也没有成功。

docker exec -ti -t -i mycontainer sh -c "wget http://localhost:3000/test || exit 1" || exit 1

the input device is not a TTY 上失败

感谢您的帮助。

【问题讨论】:

  • 请同时提供您的管道配置
  • @SvenHakvoort 不幸的是我做不到。在这一步中,我只是在我的网络中运行一些容器,然后尝试获取我的 url。

标签: docker curl wget bitbucket-pipelines


【解决方案1】:

这是我在另一个答案的 cmets 中建议的一个更简单的解决方案。如果您只想在出错时退出脚本,您可以简单地测试退出状态:

$ wget -q --spider http://localhost:3000/ || exit 1

哎呀,如果您想要更多控制和错误报告,您甚至可以使用$? 测试退出状态。 Wget 返回相当多的信息退出状态。在此引用手册:

退出状态 如果 Wget 遇到问题,它可能会返回几个错误代码之一。

   0   No problems occurred.

   1   Generic error code.

   2   Parse error---for instance, when parsing command-line options, the .wgetrc or .netrc...

   3   File I/O error.

   4   Network failure.

   5   SSL verification failure.

   6   Username/password authentication failure.

   7   Protocol errors.

   8   Server issued an error response.

   With the exceptions of 0 and 1, the lower-numbered exit codes take precedence
   over higher-numbered ones, when multiple types of errors are encountered.

【讨论】:

    【解决方案2】:

    首先删除-ti -t -i,因为在管道中没有tty 设备(终端)。 (-ti-t -i 相同)

    现在您的脚本可以检查 url 是否可访问,要检查 200 响应代码,请使用

    wget -q --spider --server-response 'http://localhost:3000/' "${url}" 2>&1 | diff -q <(echo 200) <(awk 'NR==1{print $2}')
    

    第一部分解释清楚here,然后diff看响应码是不是200。

    你的最终命令看起来像

    docker exec mycontainer sh -c "wget -q --spider --server-response 'http://localhost:3000/' "${url}" 2>&1 | diff -q "echo 200" <(awk 'NR==1{print $2}') || exit 1"
    

    编辑

    这里的diff有点过头了,所以试试这个

    wget -q --spider --server-response 'http://localhost:3000/' "${url}" 2>&1 | [ code`awk 'NR==1{print $2}'` == code200 ] || exit 1
    

    前缀“code”用于在 wget 无法连接时抑制警告,awk 不会返回任何内容,导致[ ] 抱怨。

    【讨论】:

    • 所以它失败了Usage: diff [-abBdiNqrTstw] [-L LABEL] [-S FILE] [-U LINES] FILE1 FILE2 Compare files line by line and output the differences between them. This implementation supports unified diffs only. 我的图像基于节点:10.12,可能是它没有这个功能。
    • 在 --spider 模式下使用 wget 时可以简单地检查返回码,为什么还要使用 diff?如果文件存在,它将返回 0,如果是 404 或任何其他服务器错误,则返回 8。
    • @darnir 我试过了,但它返回了很多东西,即使是wget -nv --spider 'http://localhost:3000/' 我得到了2018-11-30 17:42:05 URL: http://localhost:3000/ 200 OK `
    • 不,你只需要做wget --spider http://localhost:3000/ || exit 1。您可以使用$? 检查退出代码,看看您是否只想在服务器错误或其他错误时退出。
    • 你完全正确!更干净,我想我的唯一优点是它不会打印任何东西。
    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 2021-06-16
    • 2017-02-09
    • 2021-08-15
    • 2020-07-20
    • 2023-01-05
    • 2017-03-03
    • 2017-11-06
    相关资源
    最近更新 更多