循环 docker 输出,直到我在 bash 中找到一个字符串

Loop trough docker output until I find a String in bash

我对 bash 很陌生(几乎没有任何经验),我需要一些关于 bash 脚本的帮助。

我正在使用 docker-compose 来创建多个容器 - 对于此示例,假设有 2 个容器。第二个容器将执行 bash 命令,但在此之前,我需要检查第一个容器是否可运行且已完全配置。我不想使用睡眠命令,而是想创建一个 bash 脚本,该脚本将位于第二个容器中,一旦执行,请执行以下操作:

  1. 执行命令并将控制台输出记录在文件中
  2. 读取该文件并检查是否存在字符串。我将在上一步中执行的命令需要几秒 (5 - 10) 秒才能完成,我需要在文件执行完毕后读取文件。我想我可以添加睡眠以确保命令已完成执行或者是否有更好的方法来执行此操作?
  3. 如果字符串不存在,我想再次执行相同的命令,直到找到我要查找的字符串
  4. 找到要查找的字符串后,我想退出循环并执行不同的命令

我在 Java 中找到了如何执行此操作,但如果我需要在 bash 脚本中执行此操作。

docker-容器将 alpine 作为操作系统,但我更新了 Dockerfile 以安装 bash。

我试过这个解决方案,但它不起作用。

#!/bin/bash

[command to be executed] > allout.txt 2>&1

until 
  tail -n 0 -F /path/to/file | \
  while read LINE
  do
    if echo "$LINE" | grep -q $string
    then
      echo -e "$string found in the console output"
  fi
  done
do
    echo "String is not present. Executing command again"
    sleep 5
    [command to be executed] > allout.txt 2>&1
done

echo -e "String is found"

在您的 docker-compose 文件中使用 depends_on 选项。

depends_on 将负责多个容器的启动和关闭顺序。

但它不会在移动到另一个容器启动之前检查容器是否准备就绪。要处理这种情况,请检查 this

如本文所述link

  • 您可以使用 wait-for-it, dockerize, or sh-compatible wait-for 等工具。这些是小型包装器脚本,您可以将其包含在应用程序的图像中以轮询给定的主机和端口,直到它接受 TCP 连接。

  • 或者,编写您自己的包装器脚本来执行更特定于应用程序的健康检查。

如果您不想使用上述工具,请检查 this out. Here they use a combination of HEALTHCHECK and service_healthy condition as shown here. For complete example check this

刚刚:

while :; do
   # 1. Execute a command and log the console output in a file
   command > output.log
   # TODO: handle errors, etc.
   # 2. Read that file and check if a String is present.
   if grep -q "searched_string" output.log; then
       # Once I find the string I am looking for I want to exit the loop
       break;
   fi
   # 3. If the string is not present I want to execute the same command again until I find the String I am looking for
   # add ex. sleep 0.1 for the loop to delay a little bit, not to use 100% cpu
done
# ...and execute a different command
different_command

您可以使用 timeout 使命令超时。

备注:

  • colon is a utility that returns a zero exit status, much like true,我更喜欢while :而不是while true,他们的意思是一样的
  • 提供的代码应该适用于任何 posix shell.