簡體   English   中英

使用 docker-compose 在入口點后運行多個命令

[英]Run multiple command after entrypoint with docker-compose

我一直在尋找 CMD 和 ENTRYPOINT 的交互矩陣,但我找不到讓容器運行入口點的方法,然后是帶有多個命令的 cmd

version: '3.8'

services:
  test:
    image: debian:buster-slim
    entrypoint: [ "/entrypoint.sh" ]
    volumes:
      - ./entrypoint.sh:/entrypoint.sh
    command: [ "echo" ,"toto","&&","echo","tutu" ]

其中 entrypoint.sh 是一個文件,其中包含:

#!/bin/bash
set -e
set -x
echo tata
exec "$@"

“應該”打印

tata
toto
tutu

但它正在打印

tata
toto && echo tutu

我通過將[ "echo" ,"toto","&&","echo","tutu" ]替換為"bash -c 'echo toto && echo tutu'"找到了一個解決方案,然后它就可以工作了。

但我不明白為什么第一種方法不起作用,因為文檔說它會起作用:

exec_entry p1_entry /bin/sh -c exec_cmd p1_cmd

問題是由exec命令產生的,其概要是:

exec [command [argument...]]

所以它只會接受一個帶有多個參數的命令。

解決方案:

解決方案是您指出的解決方案,使用sh -c ''

services:
  test:
    image: debian:buster-slim
    entrypoint: [ "/entrypoint.sh" ]
    volumes:
      - ./entrypoint.sh:/entrypoint.sh
    command: ["sh", "-c", "echo toto && echo tutu"]

因為最終結果將滿足 exec 命令一個命令和多個參數


在 docker 方面,官方文檔用這張表很好地解釋了ENTRYPOINT vs CMD

泊塢窗

資源

如果在數組上下文中組合 CMD 和 ENTRYPOINT,結果將是/entrypoint.sh "echo" "toto" "&&" "echo" "tutu" ,因為CMD的每個參數都是ENTRYPOINT的參數

這是直接在終端中執行的上述示例的輸出:

# ./entrypoint.sh "echo" "toto" "&&" "echo" "tutu"
+ echo tata
tata
+ exec echo toto '&&' echo tutu
toto && echo tutu

這是docker-compose up的結果

# docker-compose up
test_1  | + echo tata
test_1  | tata
test_1  | + exec echo toto '&&' echo tutu
test_1  | toto && echo tutu
root_test_1 exited with code 0

如您所見,每個參數都以數組形式傳遞,因此'&&'被解析為字符串(注意單引號)。

筆記:

您期望的結果是這樣的:

# ./entrypoint.sh echo toto && echo tutu
+ echo tata
tata
+ exec echo toto
toto
tutu

在這種情況下,如您所見,傳遞給 exec 的唯一參數是第一個echo toto

echo tutu./entrypoint.sh腳本退出后在 bash 終端中執行。

顯然,如果這將被 docker 解析為一個單獨的命令,它將永遠不會被執行,因為ENTRYPOINT將在echo tutu命令之前退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM