Why docker container exits immediately

后端 未结 15 2234
温柔的废话
温柔的废话 2020-11-22 13:42

I run a container in the background using

 docker run -d --name hadoop h_Service

it exits quickly. But if I run in the foreground, it works

相关标签:
15条回答
  • 2020-11-22 14:42

    A docker container exits when its main process finishes.

    In this case it will exit when your start-all.sh script ends. I don't know enough about hadoop to tell you how to do it in this case, but you need to either leave something running in the foreground or use a process manager such as runit or supervisord to run the processes.

    I think you must be mistaken about it working if you don't specify -d; it should have exactly the same effect. I suspect you launched it with a slightly different command or using -it which will change things.

    A simple solution may be to add something like:

    while true; do sleep 1000; done

    to the end of the script. I don't like this however, as the script should really be monitoring the processes it kicked off.

    (I should say I stole that code from https://github.com/sequenceiq/hadoop-docker/blob/master/bootstrap.sh)

    0 讨论(0)
  • 2020-11-22 14:42

    Coming from duplicates, I don't see any answer here which addresses the very common antipattern of running your main workload as a background job, and then wondering why Docker exits.

    In simple terms, if you have

    my-main-thing &
    

    then either take out the & to run the job in the foreground, or add

    wait
    

    at the end of the script to make it wait for all background jobs.

    It will then still exit if the main workload exits, so maybe run this in a while true loop to force it to restart forever:

    while true; do
        my-main-thing &
        other things which need to happen while the main workload runs in the background
        maybe if you have such things
        wait
    done
    

    (Notice also how to write while true. It's common to see silly things like while [ true ] or while [ 1 ] which coincidentally happen to work, but don't mean what the author probably imagined they ought to mean.)

    0 讨论(0)
  • 2020-11-22 14:43

    whenever I want a container to stay up after finish the script execution I add

    && tail -f /dev/null
    

    at the end of command. So it should be:

    /usr/local/start-all.sh && tail -f /dev/null
    
    0 讨论(0)
提交回复
热议问题