Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 111 ยท Getting Started

Running Containers

Run containers in the background with -d, name them, publish ports with -p, pass environment variables, set restart policies, and understand stop versus kill and exit codes.

The containers you have run so far finished in a moment: print a line, exit. Real software runs for a long time: a web server, an API, a database, a worker. This lesson covers the options you need to run such long-lived containers properly: running in the background, naming, reaching them from your browser through published ports, configuring them with environment variables, restarting them when they crash, and stopping them cleanly.

We use the official nginx:alpine image as the running example, because it is a real web server in a small image. Port numbers are just examples; any free port works.

Detached mode: -d

Without -d, docker run is attached: it holds your terminal and prints the container's output until the container ends (and Ctrl+C stops it). For a server you want it to run in the background. -d (--detach) starts the container and returns immediately, printing the container's full ID:

CONSOLE
$ docker run -d --name web nginx:alpine
7f9adba84cbdbc4fb9d27d3e66534dbbb6f0c61fda85310e18aa942fdfe270f1
$ docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS     NAMES
7f9adba84cbd   nginx:alpine   "/docker-entrypoint.โ€ฆ"   4 seconds ago   Up 3 seconds   80/tcp    web

The container keeps running because nginx, its main process, runs in the foreground. docker ps shows only running containers; the STATUS column reads Up 3 seconds. The 80/tcp under PORTS means the image declares that it listens on port 80, but nothing is reachable from outside yet. Declaring is not publishing, as the next section shows.

A frequent mistake is a container that starts and immediately exits, so it never shows up in docker ps. Containers that run a command which finishes (like echo, or a shell with no input) stop right away. If -d seems not to work, check docker ps -a and read the logs (Logs and exec).

Do not use -d together with -it on a shell expecting to type into it. -d detaches, so the shell has nobody to talk to. If you want a shell in a running container, use docker exec -it, which is covered in the lesson on logs and exec.

Naming containers: --name

Without --name Docker picks a random name like quirky_dewdney. Names make commands readable and are how containers find each other on a network later. A name must be unique among all containers, running or stopped, on the host. The collision looks like this:

CONSOLE
$ docker run -d --name web nginx:alpine
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "7f9adba84cbd...". You have to remove (or rename) that container to be able to reuse that name.

Fix it by removing the old container (docker rm -f web), choosing another name or renaming (docker rename web web-old). This is also why --rm is so useful during experiments: the name is freed when the container exits.

Publishing ports: -p

Containers have their own network namespace, so a server listening on port 80 inside a container is not reachable from your computer by default. To expose it, publish a port with -p HOST_PORT:CONTAINER_PORT:

CONSOLE
$ docker run -d --name web -p 8080:80 nginx:alpine

Docker now forwards traffic arriving at port 8080 on your machine to port 80 in the container. Test it from the host:

CONSOLE
$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/
200
$ docker port web
80/tcp -> 0.0.0.0:8080
80/tcp -> [::]:8080

(The second line is the IPv6 mapping; whether it appears depends on your Docker setup.) docker port lists the active mappings of a container.

Choose the host address

-p 8080:80 binds to all network interfaces of the host (0.0.0.0), so other machines on your network can reach the container too. On a laptop on public Wi-Fi, or on a server, that is often not what you want. Add the host IP in front to restrict it:

CONSOLE
$ docker run -d --name web -p 127.0.0.1:8080:80 nginx:alpine
$ docker port web
80/tcp -> 127.0.0.1:8080

Now only your own machine can connect. For databases and admin tools, always publish on 127.0.0.1 unless you really want remote access. Publishing Ports examines this security point in detail.

Let Docker pick a port

-p 80 (container port only) or -P (publish every EXPOSEd port) lets Docker choose a free high port on the host:

CONSOLE
$ docker run -d -P --name web-random nginx:alpine
$ docker port web-random
80/tcp -> 0.0.0.0:32768

(The port number will differ.) That is useful in tests, where several copies of a service must run side by side. Only one container can use a given host port at a time. If you try to reuse one, the run fails:

CONSOLE
$ docker run -d --name web2 -p 127.0.0.1:8080:80 nginx:alpine
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint web2 (de26c104b391): Bind for 127.0.0.1:8080 failed: port is already allocated

$ echo $?
125

Exit code 125 is Docker's own failure code. Note that the failed container was still created (docker ps -a shows it with status Created), so remove it with docker rm web2 before trying again. The same error appears when a program outside Docker already uses the port. Common fixes: choose another host port, or stop whichever process holds it.

Environment variables: -e

Programs in containers are usually configured through environment variables. Pass one with -e NAME=value, repeatable, or --env-file for many at once:

CONSOLE
$ docker run --rm -e A=1 -e B=two alpine:3.22 env | grep -E '^(A|B)='
A=1
B=two

If you give -e NAME without a value, Docker copies the variable's value from your current shell. That avoids typing secrets into the command line (they would otherwise appear in your shell history and in docker inspect):

CONSOLE
$ export B=fromhost
$ docker run --rm -e B alpine:3.22 env | grep '^B='
B=fromhost

A file with one NAME=value per line works with --env-file .env. Variables are covered fully in Configuring Containers; the important point here is that you set them when you create the container. You cannot add or change them on an existing container without recreating it.

Two related options you will use often: -w DIR sets the working directory (docker run --rm -w /tmp alpine:3.22 pwd prints /tmp), and -u USER runs as a different user.

Restart policies: --restart

By default a container that crashes stays stopped, and a reboot of the host also leaves containers stopped. The --restart option tells the daemon to bring a container back:

Policy Behavior
no (default) Never restart.
on-failure[:N] Restart only if the exit code is non-zero, at most N times.
always Always restart, including after the daemon starts again; a manually stopped container is restarted when the daemon restarts.
unless-stopped Like always, but a container you stopped yourself stays stopped, even after a daemon restart.

A container that always fails shows the policy at work. This one prints a word and exits with an error; Docker retries it three times:

CONSOLE
$ docker run -d --name flaky --restart on-failure:3 alpine:3.22 sh -c 'echo run; exit 1'
44eb9d187da0...
$ sleep 6
$ docker inspect -f '{{.RestartCount}} {{.State.Status}} {{.State.ExitCode}}' flaky
3 exited 1
$ docker logs flaky
run
run
run
run

The program ran four times in total: once at the start and three restarts. After the third restart failed Docker gave up, and the container stayed in the exited state with exit code 1. Between restarts Docker waits a growing delay (starting at 100 ms and doubling) so a crash loop does not consume the machine.

unless-stopped is the usual choice for services on a single server; always can surprise you because a container you stopped by hand comes back when Docker restarts. Restart policies react to the container's main process ending. They do not notice a process that is alive but broken; that needs a health check. Policies are also revisited in The Container Lifecycle.

CONSOLE
$ docker run -d --name api --restart unless-stopped alpine:3.22 sleep 300
$ docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' api
unless-stopped

Stopping: stop versus kill

Two commands end a running container, and the difference matters.

docker stop is the polite way. It sends the container's main process the SIGTERM signal (a request to shut down), waits a grace period (10 seconds by default), and if the process is still running, sends SIGKILL, which cannot be caught or ignored. docker kill skips the politeness and sends SIGKILL immediately (or any signal you choose with -s).

TEXT
 docker stop:   SIGTERM โ”€โ”€โ”€โ”€ wait up to 10 s โ”€โ”€โ”€โ–ถ SIGKILL (if still running)
 docker kill:   SIGKILL right away

A program that handles SIGTERM, saves its state and exits stops quickly with exit code 0. This shell script does exactly that:

CONSOLE
$ docker run -d --name tidy alpine:3.22 sh -c 'trap "echo bye; exit 0" TERM; while true; do sleep 1; done'
$ docker stop tidy
tidy
$ docker logs tidy
bye
$ docker inspect -f '{{.State.ExitCode}}' tidy
0

A program that ignores SIGTERM costs you the whole grace period and is then killed. Here a plain sleep runs as the container's main process. (Linux gives PID 1 special treatment: signals with no handler installed are ignored, so sleep never reacts to SIGTERM.) We shorten the wait with -t:

CONSOLE
$ docker run -d --name stubborn alpine:3.22 sleep 300
$ docker stop -t 3 stubborn
stubborn
$ docker inspect -f '{{.State.ExitCode}}' stubborn
137

Exit code 137 is 128 + 9, the signal number of SIGKILL. If you see 137 regularly on docker stop, your application is not handling SIGTERM, and in-flight requests or unsaved data may be lost. The cure is in your application or in using an init process, discussed in Signals, PID 1 and --init and CMD and ENTRYPOINT. Some images change the stop signal with STOPSIGNAL.

Stopping does not delete anything. The stopped container remains and can be started again with docker start, or restarted in one step with docker restart:

CONSOLE
$ docker stop web && docker start web
web
web
$ docker restart web
web

Remove it for good with docker rm, or remove a running one with docker rm -f (which kills it first).

Exit codes and docker wait

The exit code tells you how a container ended. You can read it afterwards in docker ps -a (Exited (3) ...) or with docker inspect. To block until a container stops and print its exit code, use docker wait, which is handy in scripts:

CONSOLE
$ docker run --name job -d alpine:3.22 sh -c 'sleep 1; exit 4'
$ docker wait job
4
$ docker rm job
job

Quick reference for the codes you will meet most often:

Code Usually means
0 Success; the program finished normally
1 A generic application error
125 Docker could not run the container (port taken, bad option, name conflict)
126 The command exists but is not executable (for example a file without the execute bit)
127 The command was not found in the image
137 SIGKILL: docker kill, a stop that timed out, or an out-of-memory kill
143 SIGTERM: the process was terminated by that signal without handling it

A container whose command is a file that is not executable shows 126:

CONSOLE
$ docker run --rm alpine:3.22 sh -c '/etc/passwd'
sh: /etc/passwd: Permission denied
$ echo $?
126

A well-formed long-running container

Putting the options together, this is a typical way to run a small service on one machine:

CONSOLE
$ docker run -d \
    --name web \
    --restart unless-stopped \
    -p 127.0.0.1:8080:80 \
    -e APP_ENV=production \
    nginx:alpine

Each line has a reason: detached, a stable name, auto-restart on crashes and reboots, reachable only from the local machine, and configured through the environment. When the command line grows longer than that, move it into a Compose file. Introduction to Docker Compose shows how.

When a container misbehaves, the order of checks is almost always the same: docker ps -a (is it running, and with what exit code?), docker logs NAME (what did it say?), then docker inspect NAME (how was it configured?). The next lessons teach each of those.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does docker run -d do?

    -d (--detach) returns control of the terminal immediately. The container keeps running in the background and docker run prints its full ID.
  2. 2. You run docker run -d -p 127.0.0.1:8080:80 nginx:alpine. Who can reach the server on port 8080?

    Prefixing the host port with 127.0.0.1 binds the published port to the loopback interface only. Without it, the port is bound on all interfaces.
  3. 3. A container started with --restart on-failure:3 keeps exiting with code 1. What happens?

    on-failure:3 limits the number of restarts. After the third failed restart the container stays in the exited state.
  4. 4. docker stop on a container whose main process ignores SIGTERM finishes with exit code 137. What does that tell you?

    137 = 128 + 9 (SIGKILL). docker stop sends SIGTERM first and SIGKILL after the grace period. The fix is to make the application handle SIGTERM, or to use an init process.
  5. 5. What is the difference between --restart always and --restart unless-stopped?

    Both restart on crashes. They differ after a daemon or host restart: always brings back a container you stopped by hand, unless-stopped does not.

Summary

  • -d runs a container in the background; --name gives it a unique, memorable name.
  • -p HOST:CONTAINER publishes a port; prefix the host side with 127.0.0.1 to keep it local. Port clashes fail with exit code 125.
  • -e NAME=value (or -e NAME to copy from your shell) and --env-file pass configuration; set them when you create the container.
  • --restart (no, on-failure[:N], always, unless-stopped) controls automatic restarts.
  • docker stop sends SIGTERM, waits 10 seconds by default, then SIGKILL; docker kill sends SIGKILL at once. Exit code 137 means SIGKILL.
  • docker wait prints a container's exit code; 125, 126 and 127 point to Docker, permission and "command not found" problems.

Next: Listing and Inspecting