Dockerfile CMD instruction will exit the container just after running it

后端 未结 5 2301
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 17:46

I want to setup some configuration when my container starts, for this I am using shell scripts. But my container will exits as soon as my scripts ends, I have tried with -d

相关标签:
5条回答
  • 2020-12-13 17:50

    At your start shell append a line code: tail -f /dev/null or /bin/bash to make sure you shell done and suspend a process in system so that docker container not shutdown.Don't forget to give "chmod +x" access to start.sh. there is demo:

    #!/bin/bash
    cp /root/supervisor/${RUN_SERVICE}.ini /etc/supervisor/conf.d/
    sleep 1
    service supervisor start
    /bin/bash
    
    0 讨论(0)
  • 2020-12-13 17:59

    A docker container will run as long as the CMD from your Dockerfile takes.

    In your case your CMD consists of a shell script containing a single echo. So the container will exit after completing the echo.

    You can override CMD, for example:

    sudo docker run -it --entrypoint=/bin/bash <imagename>
    

    This will start an interactive shell in your container instead of executing your CMD. Your container will exit as soon as you exit that shell.

    If you want your container to remain active, you have to ensure that your CMD keeps running. For instance, by adding the line while true; do sleep 1; done to your shell.sh file, your container will print your hello message and then do nothing any more until you stop it (using docker stop in another terminal).

    You can open a shell in the running container using docker exec -it <containername> bash. If you then execute command ps ax, it will show you that your shell.sh is still running inside the container.

    0 讨论(0)
  • 2020-12-13 18:05

    Finally with some experiments I got my best result as below

    There is nothing wrong with my Dockerfile as below it's correct.

    FROM ubuntu:14.04
    
    ADD shell.sh /usr/local/bin/shell.sh
    
    RUN chmod 777 /usr/local/bin/shell.sh
    
    CMD /usr/local/bin/shell.sh
    

    What I do to get expected result is, I just add one more command(/bin/bash) in my shell script file as below and vola everything works in my best way.

    #!/bin/bash
    
    echo “Hello-docker” > /usr/hello.txt
    
    /bin/bash
    
    0 讨论(0)
  • 2020-12-13 18:06
    CMD bash -C '/path/to/start.sh';'bash'
    
    0 讨论(0)
  • 2020-12-13 18:10

    You can also modify your first Dockerfile, replacing

    CMD /usr/local/bin/shell.sh

    by

    CMD /usr/local/bin/shell.sh ; sleep infinity

    That way, your script does not terminate, and your container stays running.

    0 讨论(0)
提交回复
热议问题