Search code examples
dockerdocker-composedockerfiledocker-swarmdocker-machine

What does the Docker sleep command do?


I can't find a clear explanation as to what the Docker sleep command does so can someone explain please? For example:

docker container run -d alpine sleep 1d

I have had a look online but I can't find a simple explanation.


Solution

  • docker container run -d --name mycontainer myimage:mytag sleep infinity
    

    The last part after the image name (i.e. sleep infinity) is not a docker command but a command sent to the container to override its default command (set in the Dockerfile).

    An extract from the documentation (you can get it typing man sleep in your terminal, it may vary depending on the implementation)

    Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days

    To my surprise, the parameter infinity is not documented in my implementation but is still accepted. It's quite easy to understand: it pauses indefinitely (i.e. until the command is stopped/killed). In your own example above, it will pause for one day.

    What is the usual reason to use sleep as a command to run a docker container?

    A docker container will live until the command it runs finishes. This command is normally set in the Dockerfile used to build the image (in a CMD stanza) and can be overridden on the command line (as in the above examples).

    A number of base images (like base OS for debian, ubuntu, centos....) will run a shell as the default command (bash or sh in general). If you try to spawn a container from that image using its default command, it will live until the shell exits.

    When running such an image interactively (i.e. with docker container run -it .....), it will run until you end your shell session. But if you want to launch it in the background (i.e. with docker container run -d ...) it will exit immediately leaving you with a stopped container.

    In this case, you can "fake" a long running service by overriding the default command with a long running command that basically does nothing but wait for the container to stop. Two widely used commands for this are sleep infinity (or whatever period suiting your needs) and tail -f /dev/null

    After you launched a container like this you can use it to test whatever you need. The most common way is to run an interactive shell against it:

    # command will depend on shells available in your image
    docker exec -it mycontainer [bash|sh|zsh|ash|...]
    

    Once you are done with your experimentation/test, you can stop and recycle your container

    docker container stop mycontainer
    docker container rm mycontainer