Given this simple Docker compose.yaml
file:
services:
test:
image: node:18
website:
image: nginx
After running:
docker compose up
docker ps
I expected to see two running containers/images. Instead I got just the one:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c970ef47fb93 nginx "/docker-entrypoint.…" 51 seconds ago Up 48 seconds 80/tcp myid-website-1
What is happening here? Does Docker expect that a persistent process is kept running within the container image? How does it decide which services persist?
I also noticed that adding restart: always
caused the Node image to perpetually restart. What would be a good way to get the Node image to start via Docker Compose, such that I could log into it via docker exec
?
My instinct is that this has to do with the distinction between services and images/containers.
>Solution :
For a container to persist, it needs to run a program. When the program ends, the container is stopped.
The Nginx image runs the command nginx -g daemon off;
which starts Nginx and then waits for requests to come in. It doesn’t end.
The Node image runs the command node
. When there’s no arguments passed to it, it runs in interactive mode. But when you run it like you do, there’s no TTY attached to the container, so node sees that there’s no way to get any input. So node exits and the container is stopped.
If you run the command docker ps -a
, you’ll also see stopped containers. You’ll then see that your node container has exited.