Running in the background
- Docker & Kubernetes course
- Beginner
- Lesson 14/82
- 4 min
Learn to run containers in the background with -d.
Running in the background
By default docker run stays attached to the terminal; Ctrl+C stops the container. -d (detached) starts the container in the background and prints only the container ID:
$ docker run -d --name web nginx
7c2f4a9e1b3d8f6a0e5c2b1d4f7a9c3e5b8d0f2a4c6e8b1d3f5a7c9e1b3d5f7aYou later manage the background container with docker logs, docker exec and docker stop.
A command in a running container
docker exec starts an extra process inside a running container. An interactive shell can be opened with -it:
docker exec web nginx -v # nginx version: nginx/1.27.2
docker exec -it web sh # a shell inside the container
# leave with exit; the container keeps runningLeaving a shell opened with exec doesn't stop the container, since the main process is still nginx.
Practice Background and exec
Start a container named web from the nginx image in the background, then run the nginx -v command inside it.
Starter code
# buraya yazSample solution
docker run -d --name web nginx
docker exec web nginx -vExpected output
7c2f4a9e1b3d nginx version: nginx/1.27.2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does docker run -d print as output?
- The container ID Correct answer
- The application logs
- The image size
- Nothing
Explanation: The ID is 64 characters; for most commands the first few characters are enough.
2 Run a command in a running container.
docker ____ web nginx -v
docker exec web nginx -v
Explanation: exec starts a new process in an existing container; run creates a new container.
3 Match.
| Term | Meaning |
|---|---|
-d |
In the background |
docker exec |
A process in an existing container |
-it |
Interactive terminal |
exit (in the exec shell) |
The container keeps running |