将heredoc嵌入到docker-compose yaml文件中

ter*_*ywb 6 yaml heredoc docker-compose

我想在 docker-compose yaml 文件中嵌入 HEREDOC。

version: "3.7"

services:
  test-cli:
    image: ubuntu
    entrypoint: |
      /bin/sh << HERE
      echo hello
      echo goodbye
      HERE
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此程序时,出现以下错误。

 docker-compose -f heredoc.yml run --rm test-cli
Creating network "dspace-compose-v2_default" with the default driver
/bin/sh: 0: Can't open <<
Run Code Online (Sandbox Code Playgroud)

Gel*_*ler 10

与文档相反,赋予入口点的参数似乎没有传递给“/bin/sh -c”,而是被解析并转换为参数数组(argv)。

事实上,如果您运行docker inspect您提供的示例,您可以看到您的命令行已转换为数组:

         "Entrypoint": [
            "/bin/sh",
            "<<",
            "HERE",
            "echo",
            "hello",
            "echo",
            "goodbye",
            "HERE"
        ],
Run Code Online (Sandbox Code Playgroud)

由于参数数组不是由 shell 解释的,因此您不能使用管道和 HEREDOC 之类的东西。

相反,您可以使用 YAML 为您提供的功能来处理多行输入并提供参数数组:

version: "3.7"

services:
  test-cli:
    image: ubuntu
    entrypoint:
      - /bin/bash
      - '-c'
      - |
          echo hello
          echo goodbye
Run Code Online (Sandbox Code Playgroud)

如果你真的需要 HEREDOC 你可以这样做:

version: "3.7"

services:
  test-cli:
    image: ubuntu
    entrypoint:
      - /bin/bash
      - '-c'
      - |
        /bin/sh << HERE
        echo hello
        echo goodbye
        HERE
Run Code Online (Sandbox Code Playgroud)