Why does 'docker run -t' redirect stderr to stdout?

Viewed 900

From docker run --help:

  -t, --tty                            Allocate a pseudo-TTY

Very nice. I use that to get color output automatically. The problem is, it also redirects stderr to stdout.

Without -t, stderr isn't redirected, which is what I want:

$ docker run ubuntu ls /aaaaaa
ls: cannot access '/aaaaaa': No such file or directory

$ docker run ubuntu ls /aaaaaa 2> /dev/null

With -t, the error messages are redirected to stdout:

$ docker run -t ubuntu ls /aaaaaa
ls: cannot access '/aaaaaa': No such file or directory

$ docker run -t ubuntu ls /aaaaaa 2> /dev/null
ls: cannot access '/aaaaaa': No such file or directory

$ docker run -t ubuntu ls /aaaaaa > /dev/null

Why is that? Is there a way to still allocate a pseudo-TTY and keep stderr separate?

e.g. I want to run something like this in CI:

docker run ... my-command > out.json

while the logger shows warnings and error messages in color.

1 Answers

You need to give your command a shell session so your container can have its own output redirection and not rely on what docker runtime has setup.

This will print error message as usual:

docker run -t --rm busybox sh -c "ls /aaa"

This will not print error message to your allocated tty:

docker run -t --rm busybox sh -c "ls /aaa 2>/dev/null"

This will print the directory listing of /etc:

docker run -t --rm busybox sh -c "ls /etc 2>/dev/null"

Related