Docker: Prevent Container From Exiting Immediately After Creation

Posted July 25, 2020 by Yaroslav Grebnov ‐ 2 min read

For some projects, it is useful to create one or several Docker images serving as parts of the environment, containing all software which is required to run the application project your team is working on.

In case such image is built with the container entry point like: CMD [“bin/sh”], the container may exit immediately after creation.

If the container is created using docker run -it, like in this example:

docker run -it ygrebnov/node-angularcli:latest ash

you can access it and work with it. As soon as you exit the container, it is stopped.

docker ps -a

You can see the Exited (0) About a minute ago status displayed for your container.

If the container is created using docker-compose with basic configuration, the container status is Exited(0) after:

docker-compose up -d

If there is a restart policy defined for the service in the docker-compose.yml, the container will be constantly restarting. In case of Exited(0) container status, most likely that docker logs <container_id> command will show nothing.

Such behavior is explained by the fact that the created docker container process with PID 1 is started and successfully finished with the return code 0. Docker container is exited as soon as the process with PID 1 finishes. In our case, the process with PID 1 is /bin/sh.

In order to prevent the docker container from exiting immediately after creation, tty should be set to true in the docker-compose.yml file. tty: true in docker-compose corresponds to the docker run -it.

With tty: true for the service, the created by docker-compose up -d container status is Up.

An example of the docker image with CMD [“bin/sh”]: ygrebnov/node-angularcli. Docker Hub: https://hub.docker.com/repository/docker/ygrebnov/node-angularcli

An example of the docker-compose.yml using ygrebnov/node-angularcli image: https://github.com/ygrebnov/mean-setup.