"docker exec" 命令的“-i”和“-t”选项的用途是什么?

What is the purpose of the "-i" and "-t" options for the "docker exec" command?

老实说,我一直对docker exec -it …docker exec -i …docker exec -t …感到困惑,所以我决定做一个测试:

  1. docker exec -it …:

    # docker exec -it 115c89122e72 bash
    root@115c89122e72:/# ls
    bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    

    正常工作

  2. docker exec -i …:

    # docker exec -i 115c89122e72 bash
    ^C
    

    命令挂起,我不得不使用Ctl + c 中断它。

  3. docker exec -t …:

    # docker exec -t 115c89122e72 bash
    root@115c89122e72:/# ls
    ^C
    

    进入容器成功,执行第一个命令就挂了

所以看起来 docker exec -i …docker exec -t … 命令没有意义。谁能详细说明为什么 docker exec 命令存在 -i-t 选项?

-i--interactive 即使未附加 STDIN 也保持打开状态,如果您想键入任何命令,则需要它。

-t,--tty分配一个伪TTY,一个pseudo terminal which connects a user's "terminal" with stdin and stdout. (See container/container.go)

如果你做回显,只需要 -t
但是对于输入输入的交互式会话,您需要 -i.

由于 -i 保持 stdin 打开,它也用于将输入通过管道传输到分离的 docker 容器。即使使用 -d(分离)也是如此。
参见“”:

$ echo hello | docker run -i busybox cat
  hello

-i keeps STDIN open even if not attached, what is the status of STDOUT in this case?

对于docker exec,是docker run设置的那个。

但是,关于docker exec, there is a current issue (issue 8755: Docker tty is not a tty with docker exec

unfortunately your discovery only amounts to a difference between the behaviour of tty in centos6 vs ubuntu:14.04. There is still not a functional tty inside the exec - just do ls -la /proc/self/fd/0 and see that it's a broken link pointing to a pts which doesn't exist.

the actual bug we're dealing with is that certain standard libraries assume that the symlinks in /proc/self/fds/ must be valid symlinks

The problem is that the tty is created outside on the host and there is no reference to it in the container like how /dev/console is setup in the primary container.
One options to fix this would be allocate and bind mount the devpts from the host in to the containers.

注意(2017 年第 4 季度):this should been fixed by now (docker 17.06-ce)
参见 PR 33007

该 PR 现在允许(自 17.06 起):

zacharys-pro:dev razic$ docker run --rm -t -d ubuntu bash
83c292c8e2d13d1b1a8b34680f3fb95c2b2b3fef71d4ce2b6e12c954ae50965a

zacharys-pro:dev razic$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
83c292c8e2d1        ubuntu              "bash"              2 seconds ago       Up 1 second                             xenodochial_bardeen

zacharys-pro:dev razic$ docker exec -ti xenodochial_bardeen tty
/dev/pts/1

(在 17.06 之前,tty 返回“not a tty”)