Robin Green
Robin Green

Reputation: 33063

Detach from docker run from script without killing container

I have a script which contains this line:

fgrep -m 1 'PostgreSQL init process complete' <( docker run --name test-postgres-migration \
                                                            -a STDOUT -p 5432:5432 postgres:9.4 )

However, even if I change it to:

fgrep -m 1 'PostgreSQL init process complete' <( docker run --name test-postgres-migration \
                                                            -a STDOUT -p 5432:5432 postgres:9.4 </dev/null )

or:

fgrep -m 1 'PostgreSQL init process complete' <( docker run --name test-postgres-migration \
                                                            -a STDOUT -p 5432:5432 postgres:9.4 </dev/null ) </dev/null

or even when I put the entire line in a separate shell script and wrap it in nohup:

nohup ./boot-container.sh

the docker container still dies if the script is killed (by emacs) when it is on a later line. This happens because the docker client command is still running, and even though it has PID 1 as its parent, for some mysterious reason (maybe due to a shared stdin file handle or tty) it gets killed too when the script gets killed, which in turn causes the docker container it has started to die. How can I prevent this?

Upvotes: 1

Views: 946

Answers (1)

Robin Green
Robin Green

Reputation: 33063

In this situation, even nohup isn't sufficient - it's necessary to use setsid:

fgrep -m 1 'PostgreSQL init process complete' <( setsid docker run --name test-postgres-migration \
                                                                   -a STDOUT -p 5432:5432 postgres:9.4 )

This solves my problem on Linux - I haven't verified whether the problem occurs on Mac or Unixes, or if this unofficial port of setsid to Mac and other Unixes fixes it.

Upvotes: 1

Related Questions