0

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lee
  • 29,398
  • 28
  • 117
  • 170
  • 1
    It's not deciding anything. `docker run node:18` will show you pretty quickly that it immediately exits (because out of the box it has nothing to do), whereas `docker run nginx` keeps running (because it's a web server). – jonrsharpe Feb 10 '23 at 12:06
  • 1
    https://stackoverflow.com/a/46898038 – Lee Feb 10 '23 at 12:16
  • https://stackoverflow.com/a/41968585 – Lee Feb 10 '23 at 12:19
  • 2
    I'm not sure what your point is. Yes a container has a default command and entrypoint (`node:18`'s is... `node`). Yes you can change either or both via configuration. That's still not Docker deciding anything, _the container stops running_ so Docker stops showing it in the list of running containers. There's usually very little point running a low-level container like `node:18` or `nginx` on its own, they're start points for the `Dockerfile` where you add the app to run or files to serve (e.g. https://github.com/textbook/salary-stats/blob/main/Dockerfile, which uses Node _and_ Nginx). – jonrsharpe Feb 10 '23 at 12:21
  • @jonrsharpe just collecting information atm, not making a point. Thanks for the comments/improvements; once I _get it_, I'll add an answer if there is not already one there... – Lee Feb 10 '23 at 12:25
  • ... and if it's still open! – Lee Feb 10 '23 at 12:27

1 Answers1

2

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.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35