Ensure The Command Does Not Exit
Had the same issue, container kept restarting but both docker logs
and docker-compose logs
just showed me clean logs in a loop, with no clue about the restarts.
Then I realized that indeed there was no error, it was simply exiting because of the command
I added to the YML configuration. To verify it, I appended tail -f /dev/null
to the last command, e.g.:
command: bash -c "nginx -t && tail -f /dev/null"
And this time, it stayed up!
Use The Proper Command
With the theory confirmed, I looked up the proper CMD
with docker inspect $image_id
and used a proper command, e.g.:
command: bash -c "nginx -t && nginx -g 'daemon off;'"
Why Does it Restart
Two possible causes are, there's an error, or the command exits early. In my case, it was the latter. I was previously using an image which already had the correct CMD
above. But I wanted to add some extra commands without having to use a separate dockerfile.
So I ditched the dockerfile and used command since the compose file does not have a RUN
equivalent (correct me otherwise). However, it "overrides the default command declared by the container image", which was the one preventing the container from exiting early.
How To Identify The Restart Cause
Look at the output of docker ps
, I believe that the number in brackets in e.g. "Restarting (1)", is the exit code. You can also run docker-compose
in the foreground (not detached, i.e. without -d
) so you can see the logs and potential exit codes in real time.
Or run this command:
docker inspect $your_container_name | grep -i state -C 12
Look for the State object:
"State": {
"Status": "restarting",
"Running": true,
"Paused": false,
"Restarting": true,
"Dead": false,
"Pid": 0,
"ExitCode": 0,
"Error": "",
...
},
The main thing to look for here is the ExitCode
. If it's 0, and there's no Error
, chances are that the command finishes early, i.e. it's not running as a service. If the code is not 0, there's an actual execution error and you should be able to see it with docker-compose logs
or docker logs
.