Skip to content
Lesson: docker runSwitch
← DevOps Operations

Delivery and containers

docker run

Start containers with docker run and learn its most useful options.

docker run creates a new container from an image and starts it. The general shape is:

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Options go before the image name. Anything after the image is passed into the container.

Run one command

$ docker run --rm alpine echo "hi from a container"
hi from a container

Here echo ... replaces the image's default command. If the image defines an entrypoint, your words are given to it as arguments. --rm removes the container when it exits.

Interactive shell

$ docker run -it --rm alpine sh
/ #

-i keeps standard input open and -t gives you a terminal. Type exit to leave. Small images may have sh but no bash.

Run in the background

$ docker run -d --name web -p 8080:80 nginx
3f2b9c0d8e7a...

-d detaches and prints the container ID. --name gives it a name you can use later; without it Docker invents one. -p 8080:80 publishes port 80 of the container on port 8080 of the host.

Each docker run makes a new container. Running this command again fails because the name web is taken. To restart the existing one, use docker start web.

Settings and files

Pass environment variables with -e:

$ docker run --rm -e GREETING=hello alpine printenv GREETING
hello

Mount a host folder with -v:

$ docker run --rm -v "$PWD":/work -w /work alpine ls

-w sets the working directory. A bind mount gives the container access to those real files, and it can change them. Add :ro after the target path for read-only access.

Restart policy

For a service that should come back after a crash or when Docker restarts:

$ docker run -d --restart unless-stopped nginx

A restart policy like this cannot be combined with --rm.

The official docker run reference lists every option.

Try it

Start a detached nginx container named demo, check it with docker ps, then stop and remove it. Run a new one with docker run and the same name to confirm the name is free.

Check your understanding

docker run

All 4 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.