Bash – nohup … & doesn’t work as expected in docker script

bashdockernohup

I have a simple Dockerfile like this

FROM ubuntu:latest
ADD run.sh /run.sh
CMD /run.sh

In run.sh, I have this (also deadly simple)

#!/bin/bash
nohup awk 'BEGIN { while (c++<50) print "y" }' &
sleep 10

When I run the script in docker from bash (that is, run bash command in interactive mode and there run the script), it works correctly – it goes into "nohup mode" and the output is, correctly, in nohup.out.

However, if I run the docker container with the /run.sh as the default command, the output is still in STDOUT.

What am I doing wrong? Why is it working in docker, in bash, but only when it's run from interactive mode?

Best Answer

nohup only redirects the command's output if it's going to a terminal. If the output is already going to another type of file (e.g. regular file or a pipe), nohup assumes that this is desired and does not redirect to nohup.out.

By default, docker run runs the command via a socket (connecting the host with the virtual environment — that's how they communicate). A socket isn't a terminal so nohup doesn't perform any redirection.

If you run docker run -t then Docker will emulate a terminal in the container and so nohup will redirect to nohup.out. If you don't pass a command name then docker acts as if you'd used docker run -t bash.

The best solution is to explicitly redirect the output of the command to your choice of log file. Don't forget to redirect stderr as well. That way you'll know where they're going.

nohup awk 'BEGIN { while (c++<50) print "y" }' >myscript.log 2>&1 &
Related Question