How to prevent docker container from exiting

A docker containing not running anything particular in the foreground will exit immediately after start.

Specifying /bin/sh as the startup command does not help. Some Internet sources suggest tail -f /dev/null, and it works, but such container cannot be stopped gracefully. The best solution I could find was a shell script running a wait loop:

# Dockerfile
FROM alpine
CMD while true; do sleep 1000; done

This takes a few seconds to stop gracefully, but it does go down eventually.

2 Comments


  1. Create a named pipe file and read from it. The read will get stuck until a text line gets written to the pipe. Write a line of text to the pipe to stop.

    Reply

    1. > “Write a line of text to the pipe to stop”

      This would work if I write special code to stop the container. However, “docker stop” command would not know anything about my pipes, so it would not have any other choice, but to terminate the container in a not-so-graceful way.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *