我现在尝试在Kubernetes集群上使用shell (/bin/bash)运行一个简单的容器。

我认为有一种方法可以通过使用伪tty和detach选项(Docker run命令上的-td选项)来保持容器在Docker容器上运行。

例如,

$ sudo docker run -td ubuntu:latest

Kubernetes中有这样的选项吗?

我尝试使用kubectl run-container命令运行一个容器,如下所示:

kubectl run-container test_container ubuntu:latest --replicas=1

但是容器会退出几秒钟(就像使用没有上面提到的选项的docker run命令启动一样)。ReplicationController会重复启动。

有没有办法让容器在Kubernetes上运行,比如docker run命令中的-td选项?


当前回答

有许多不同的方法来实现这一点,但最优雅的方法之一是:

kubectl run -i --tty --image ubuntu:latest ubuntu-test --restart=Never --rm /bin/sh

其他回答

我做了一个hack,把它放在后台:

[root@localhost ~]# kubectl run hello -it --image ubuntu -- bash &
[2] 128461

执行舱上,你好

[root@localhost ~]# kubectl exec -it hello -- whoami
root
[root@localhost ~]# kubectl exec -it hello -- hostname
hello

获得外壳

[root@localhost ~]# kubectl exec -it hello -- bash
root@hello:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

你可以在Dockerfile中使用这个CMD:

CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"

这将使您的容器保持活动状态,直到它被告知停止。使用trap和wait将使容器立即对停止请求做出反应。没有陷阱/等待停止需要几秒钟。

对于基于busybox的图像(用于基于alpine的图像),sleep不知道无穷大参数。这个解决方案给了你和上面例子中一样的对docker stop的即时响应:

CMD exec /bin/sh -c "trap : TERM INT; sleep 9999999999d & wait"

添加这个:在模板->在规格->在集装箱->在港口和之后的集装箱港口线

    command: ["/bin/sh", "-ec", "while :; do echo '.'; sleep 6 ; done"]

这个命令可能会有帮助

CMD exec /bin/bash -c "trap : TERM INT; sleep i infinity & wait"

容器意味着运行到完成。您需要为容器提供一个永远不会完成的任务。像这样的东西应该工作:

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
spec:
  containers:
  - name: ubuntu
    image: ubuntu:latest
    # Just spin & wait forever
    command: [ "/bin/bash", "-c", "--" ]
    args: [ "while true; do sleep 30; done;" ]