Docker Community Forums

Share and learn in the Docker community.

Docker run attached versus detached


(Berndbausch) #1

This is obviously a newbie question. The docker run man page is not clear about this. This is what it says about foreground mode, which I understand to be the same as attached mode:

In foreground mode (the default when -d is not specified), docker run can start the process in the container and attach the console to the process’s standard input, output, and standard error. It can even pretend to be a TTY (this is what most command line executables expect) and pass along signals.

My question: In foreground mode, it can do various things, but options like -i and -t are required. What if I start a container without providing a TTY (-t) and without keeping stdin open (-i)?

In other words: When I start a container started like this, without any option:

docker run MY-IMAGE

I get the host’s login prompt, as expected. But how does this differ from:

docker run -d MY-IMAGE


(David Maze) #2

If that’s what happened, then the container started, ran to completion, and exited.

Most containers run some sort of server process, and when that server process exits, the container exits. For instance, you could launch

docker run -p6379:6379 redis

and it will print out a bunch of log messages; in another window you can run something like

echo 'KEYS *' | nc localhost 6379

to talk to it. You can press ^C to stop the server.

Alternatively, you can use docker run -d to run the service “in the background”:

$ docker run -d -p6379:6379 redis
bc7b2b9e22c9919266fc06e3b7f9cc9b1122bda3349aaa32d78236137598fe03
$ echo 'KEYS *' | nc localhost 6379
*0
$ docker stop bc7b2b9e22c9919266fc06e3b7f9cc9b1122bda3349aaa32d78236137598fe03
bc7b2b9e22c9919266fc06e3b7f9cc9b1122bda3349aaa32d78236137598fe03
$ docker rm -v bc7b2b9e22c9919266fc06e3b7f9cc9b1122bda3349aaa32d78236137598fe03
bc7b2b9e22c9919266fc06e3b7f9cc9b1122bda3349aaa32d78236137598fe03

I think the key point from the documentation you quote is that -it is “what most command line executables expect”, but IME the typical container isn’t a command-line executable, it’s a server process.


(Berndbausch) #3

Thanks David, I am slowly getting there. So my container ran in the foreground, but its main process, a shell (it was a Ubuntu container), didn’t find a terminal and exited.

I do have a follow-up question to the same topic:

-t allocates a terminal. Yes, I can see the prompt. But when I enter something, I don’t get anything back from the shell, and ^C kills the shell and thus the container. This behaviour surprises me.

To talk to the bash in the container, I also need -i, although the doc says that this option means “Keep STDIN open even if not attached”. Well, it is attached, so why do I need -i?