How to Use Docker Run -it: Interactive Container Sessions
Use
docker run -it to start a Docker container in interactive mode with a terminal attached. The -i flag keeps the input open, and -t allocates a terminal, letting you interact with the container directly.Syntax
The basic syntax of docker run -it is:
docker run: Command to create and start a container.-i: Keeps STDIN open so you can send input to the container.-t: Allocates a pseudo-TTY (terminal) for interactive shell.[image]: The Docker image to run.[command]: Optional command to run inside the container.
bash
docker run -it [image] [command]
Example
This example runs an Ubuntu container interactively and opens a bash shell inside it. You can type commands directly inside the container.
bash
docker run -it ubuntu bash
Output
root@<container-id>:/#
Common Pitfalls
Common mistakes when using docker run -it include:
- Omitting
-ior-t, which prevents interactive input or terminal allocation. - Running a container without a shell command, which may cause the container to exit immediately.
- Not using an image that supports interactive shells.
bash
docker run ubuntu # Container exits immediately because no interactive shell is started docker run -it ubuntu bash # Correct: starts interactive bash shell
Quick Reference
| Flag | Description |
|---|---|
| -i | Keep STDIN open for interactive input |
| -t | Allocate a pseudo-TTY (terminal) |
| -d | Run container in detached mode (background) |
| --rm | Automatically remove container when it exits |
Key Takeaways
Use
docker run -it to start containers with interactive terminal access.The
-i flag keeps input open; -t creates a terminal interface.Always specify a shell command like
bash to keep the container running interactively.Without
-it, you cannot interact with the container's shell.Use
--rm with -it to clean up containers after exit.