【问题标题】:Kubernetes - Passing multiple commands to the containerKubernetes - 将多个命令传递给容器
【发布时间】:2016-03-02 23:04:23
【问题描述】:

我想在 kubernetes 配置文件的 command 标记中向 Docker 容器发送多个入口点命令。

apiVersion: v1
kind: Pod
metadata:
  name: hello-world
spec:  # specification of the pod’s contents
  restartPolicy: Never
  containers:
  - name: hello
    image: "ubuntu:14.04"
    command: ["command1 arg1 arg2 && command2 arg3 && command3 arg 4"]

但它似乎不起作用。在命令标签中发送多条命令的正确格式是什么?

【问题讨论】:

标签: kubernetes


【解决方案1】:

另一个带有多个 bash 命令的示例,用于处理busybox 图像。 这将通过一个while循环连续运行,否则通常带有简单脚本的busybox图像会完成任务,然后pod将被关闭。 此 yaml 将持续运行 pod。

apiVersion: v1
kind: Pod
metadata:
labels:
  run: busybox
  name: busybox
spec:
  containers:
  - command:
    - /bin/sh
    - -c
    - |
      echo "running below scripts"
      i=0; 
      while true; 
      do 
        echo "$i: $(date)"; 
        i=$((i+1)); 
        sleep 1; 
      done
  name: busybox
  image: busybox

【讨论】:

  • 示例有语法错误,无法运行。
  • 现在应该可以工作了,为此解决方案已编辑语法错误。
【解决方案2】:

您可以像通常处理 yaml 数组/列表一样简单地列出命令。看看 this question 的 yaml 数组语法。

以下是如何将参数列表传递给命令的示例。请注意命令末尾的分号,否则会出错。

  containers:
  - name: my-container
    image: my-image:latest
    imagePullPolicy: Always
    ports:
    - containerPort: 80
    command: [ "/bin/bash", "-c" ]
    args:
     - 
        echo "check if my service is running and run commands";
        while true; do
            service my-service status > /dev/null || service my-service start;
            if condition; then
                    echo "run commands";
            else
                    echo "run another command";
            fi;
        done
        echo "command completed, proceed ....";

【讨论】:

    【解决方案3】:

    乔丹的回答是正确的。

    但为了提高可读性,我更喜欢:

    apiVersion: v1
    kind: Pod
    metadata:
      name: hello-world
    spec:  # specification of the pod’s contents
      restartPolicy: Never
      containers:
      - name: hello
        image: "ubuntu:14.04"
        command: ["/bin/sh"]
        args:
          - -c
          - >-
              command1 arg1 arg2 &&
              command2 arg3 &&
              command3 arg4
    

    阅读this以了解YAML块标量(上述>-格式)。

    【讨论】:

      【解决方案4】:

      使用这个命令

      command: ["/bin/sh","-c"]
      args: ["command one; command two && command three"]
      

      【讨论】:

      【解决方案5】:

      容器中只能有一个入口点...如果您想运行多个类似的命令,请将 bash 作为入口点,并将所有其他命令作为 bash 运行的参数:

      command: ["/bin/bash","-c","touch /foo && echo 'here' && ls /"]

      【讨论】:

      猜你喜欢
      • 2020-09-16
      • 2020-11-02
      • 2021-08-03
      • 2020-03-24
      • 2018-02-09
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多