0
0
DockerHow-ToBeginner · 3 min read

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 -d to 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 -v to 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:

OptionDescriptionExample
-dRun container in background (detached mode)docker run -d nginx
-pMap container port to host portdocker run -p 8080:80 nginx
-vMount host directory as volumedocker run -v /host/data:/data alpine
--nameAssign a name to the containerdocker run --name mycontainer nginx
-eSet environment variablesdocker 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.