Docker: Prevent container from exiting immediately after creation
An example of how to prevent a Docker container from exiting with return code 0 immediately after creation.
In case a Docker image is built with the container entry point like: CMD [“bin/sh”]
, a container created from such image 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 a docker-compose.yml
using ygrebnov/node-angularcli
image:
version: '3.5'
services:
mongo:
image: mongo
container_name: mean-mongo
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: admin
volumes:
- mongo-volume:/data/db
networks:
- mean-network
node:
image: ygrebnov/node-angularcli:latest
container_name: mean-node
tty: true
restart: unless-stopped
ports:
- "44120:8080"
volumes:
- node-volume:/usr/src/app
networks:
- mean-network
volumes:
mongo-volume:
node-volume:
networks:
mean-network:
driver: bridge