How to Use Docker Run: Basic Syntax and Examples
Use the
docker run command to start a new container from an image by specifying the image name and optional flags. It creates and runs the container in one step, for example, docker run hello-world runs a simple test container.Syntax
The basic syntax of docker run is:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Here:
- OPTIONS are optional flags to control container behavior (like ports, environment variables, or detach mode).
- IMAGE is the name of the Docker image to run.
- COMMAND and ARG are optional commands and arguments to override the default container command.
bash
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Example
This example runs the official hello-world image, which prints a welcome message and then exits. It shows how docker run creates and starts a container from an image.
bash
docker run hello-world
Output
Hello from Docker!\nThis message shows that your installation appears to be working correctly.\n...
Common Pitfalls
Common mistakes when using docker run include:
- Forgetting to use
-dto run containers in the background (detached mode) when needed. - Not mapping ports with
-p, so services inside the container are not accessible from your machine. - Not mounting volumes with
-vto persist data outside the container. - Trying to run an image that does not exist locally without internet access to pull it.
bash
Wrong: docker run nginx Right: docker run -d -p 8080:80 nginx
Quick Reference
Here is a quick cheat sheet for common docker run options:
| Option | Description | Example |
|---|---|---|
| -d | Run container in background (detached mode) | docker run -d nginx |
| -p | Map container port to host port | docker run -p 8080:80 nginx |
| -v | Mount host directory as volume | docker run -v /host/data:/data alpine |
| --name | Assign a name to the container | docker run --name mycontainer nginx |
| -e | Set environment variables | docker run -e VAR=value alpine |
Key Takeaways
Use
docker run to create and start a container from an image in one step.Add
-d to run containers in the background and -p to expose ports.Mount volumes with
-v to keep data outside the container.Specify container names with
--name for easier management.Always check if the image exists locally or Docker can pull it from a registry.