0

Why does the container exit when the entry point specifies to run a command in the background? E.g. if I run docker run -d ubuntu bash -c "sleep 12000&" the container exits. If I run docker run -d ubuntu bash -c "sleep 12000" the container continues to run.
Isn't a process in the background sufficient to keep the container running?
Why does the sleep running in the background or foreground affect this?

Jim
  • 3,845
  • 3
  • 22
  • 47

3 Answers3

1

According to Docker's mans, container is supposed to be running while

the container’s primary process (PID 1) is running

In your case primary process bash and container "runs" until this process exits.

grapes
  • 8,185
  • 1
  • 19
  • 31
  • If I do `bash -c "sleep 12000&"` sleep should still be running no? In docker ps though it does not show up – Jim Jan 15 '19 at 13:48
  • No, `sleep` goes to background and caller's script terminates, thus container gets shutdown – grapes Jan 15 '19 at 13:49
  • Yes that is my question. Background process can not keep the container running? Why not? – Jim Jan 15 '19 at 13:54
  • Because of docker daemon's criteria of whether the container is running is that main process is active. If you want to keep container active, setup your main process to keep idle while background service is working – grapes Jan 15 '19 at 13:57
1

As suggested by grapes, the condition is that PID 1 is running.

The container is designed to be short-lived and specialized in one task (microservice) which runs as PID 1 in the foreground. Background is of course useful for things like ssh, but the container has to have a main job.

Most service can be run both on foreground or background (deamonized)

PS. if you have to keep a container alive, use tail -f /dev/null as CMD

Siyu
  • 11,187
  • 4
  • 43
  • 55
1

A simple criterion might be the following: if you run a command locally and it immediately returns and gives you a shell prompt back, then if you run that command as the main process in a container, the container will immediately exit.

Usual best practice is to have a container run some process, like a network server, as a foreground process, and when that server exits the container is done. In the ideal case the container is totally autonomous: once you docker run it, it does its thing without any user intervention. (In this model a plain Ubuntu container, with no software installed, that only sleeps, isn’t that interesting.)

David Maze
  • 130,717
  • 29
  • 175
  • 215