A container's main process gets a stdin and a stdout like any program. Two flags decide how they connect to your terminal.
| Flag | Long form | Effect |
|---|---|---|
-i | --interactive | Keep the container's stdin open and connected to yours |
-t | --tty | Give the container a terminal (prompt, line editing) |
The combinations
| Command | Use for |
|---|---|
docker run IMAGE CMD | Programs that need no input: echo, cat FILE, servers with -d |
docker run -i IMAGE CMD | Piping data in: ... < file, cmd | docker run -i ... |
docker run -it IMAGE sh | An interactive shell in a new container |
docker run -dit IMAGE sh | A shell kept running in the background, to exec into later |
Without -i, a shell exits
docker run --name quick alpine:3.20 sh
docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e1dd94dc29ef alpine:3.20 "sh" 2 seconds ago Exited (0) 2 seconds ago quicksh waits for commands on stdin. Its stdin is closed, so it reads end-of-file and exits 0.
-it: a shell in a new container
docker run -it --name shell alpine:3.20 sh/ # cat /etc/alpine-release
3.20.3
/ # exitThe prompt / # is the shell inside the container: / is its working directory and # means root. Debian and Ubuntu images use bash with root@<container-id>:/# .
Leaving the shell ends PID 1, so the container stops:
docker run -it ... sh sh is PID 1 ──exit──► container Exited (0)
docker exec -it C sh sh is extra ──exit──► container keeps running-i alone: pipes
-i without -t passes data through unchanged, which is what pipes need:
docker run -i --rm alpine:3.20 sort < ~/servers.txtapi-01
db-02
web-03Without -i, sort reads nothing and prints nothing.
-dit: a shell to come back to
docker run -dit --name toolbox alpine:3.20 sh
docker exec -it toolbox sh-d starts it in the background. -it keeps the shell's stdin and terminal open, so sh waits instead of exiting. Each docker exec -it toolbox sh opens a second shell; exit leaves it and toolbox stays Up.
docker attach toolbox connects to the original shell (PID 1). Typing exit there stops the container.