Servers run until you stop them. Run them detached with -d so the terminal stays free, and name them with --name so every later command can refer to them.
Foreground vs detached
| Command | Terminal | Use for |
|---|---|---|
docker run alpine:3.20 echo hi | prints hi, returns when the process ends | one-off commands |
docker run nginx:1.27 | attached to nginx's output until Ctrl+C | watching a server start |
docker run -d nginx:1.27 | prints the ID and returns at once | servers, workers, databases |
sh
docker run -d --name web nginx:1.27text
e1dd94dc29ef1a321f7709d199f32885061b9882187edc1bdae10321dd0fa25aThat is the full 64-character ID. docker ps shows its first 12 characters. Any unique prefix works in commands, but a name is easier.
Generated names
Without --name, Docker generates an adjective_surname name:
sh
docker run -d redis:7.4
docker pstext
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99fddfcd7640 redis:7.4 "docker-entrypoint.s…" 2 seconds ago Up 2 seconds 6379/tcp eager_keller
e1dd94dc29ef nginx:1.27 "/docker-entrypoint.…" 4 seconds ago Up 4 seconds 80/tcp webThese three refer to the same container:
text
docker stop eager_keller
docker stop 99fddfcd7640
docker stop 99fName rules
- Unique on the host, across running and stopped containers.
- At least two characters: letters, digits,
_,.,-, starting with a letter or digit.
Reusing a name fails:
text
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "e1dd94dc29ef...". You have to remove (or rename) that container to be able to reuse that name.Rename a container
sh
docker rename eager_keller cacherename prints nothing on success. The container keeps its ID, its state and its data.
What you pass to docker run
text
docker run -d --name web nginx:1.27 [command]
│ │ │ └─ optional: replaces the image's default command
│ │ └───────────── image
│ └───────────────────────── name for later commands
└───────────────────────────── detach: print the ID and returnOptions go before the image. Anything after the image is the command run inside the container.