Basic Docker Run Command
Learn the fundamentals of the docker run command. Understand how Docker creates and starts a container from an image, including the default behavior and essential flags.
Detailed Explanation
The Foundation of Docker Containers
The docker run command is the most fundamental Docker command. It creates a new container from a specified image and starts it. At its simplest, the command takes just an image name:
docker run ubuntu
This pulls the ubuntu image (if not already cached locally), creates a new container from it, and runs the default command specified in the image's CMD or ENTRYPOINT instruction.
What Happens Behind the Scenes
When you execute docker run, Docker performs several steps in sequence:
- Image lookup: Docker checks the local image cache. If the image is not found, it pulls from Docker Hub (or a configured registry).
- Container creation: A new read-write filesystem layer is created on top of the image's read-only layers.
- Network setup: Docker assigns the container a virtual network interface and an IP address on the default bridge network.
- Process execution: The container's main process (PID 1) starts. This is either the image's default
CMDor a command you specify.
Overriding the Default Command
You can append a custom command after the image name:
docker run ubuntu echo "Hello from container"
This replaces the image's default command with echo "Hello from container". The container runs the command, prints the output, and exits.
Interactive Mode
For an interactive shell session, combine the -i (interactive) and -t (pseudo-TTY) flags:
docker run -it ubuntu bash
This gives you a bash prompt inside the container. Without -it, the shell would exit immediately because it has no input stream attached.
Key Points for Beginners
- Each
docker runcreates a new container. It does not reuse existing containers. - When the main process exits, the container stops but is not removed (use
--rmto auto-remove). - Container names are auto-generated unless you specify one with
--name. - The container's filesystem is ephemeral by default; changes are lost when the container is removed.
Use Case
Running a quick one-off command in a clean Linux environment, such as testing a script or verifying package installations, without affecting your host system.