Consider the following Dockerfile:
FROM ubuntu:16.04
RUN apt-get update && \
apt-get install -y apache2 && \
apt-get clean
ENTRYPOINT ["apache2ctl", "-D", "FOREGROUND"]
When running the container with the command docker run -p 8080:80 <image-id>
, then the container starts and remains running, allowing the default Apache web page to be accessed on https://localhost:8080
from the host as expected. With this run command however, I am not able to quit the container using Ctrl+C
, also as expected, since the container was not launched with the -it
option. Now, if the -it
option is added to the run command, then the container exits immediately after startup. Why is that? Is there an elegant way to have apache run in the foreground while exiting on Ctrl+C
?
If you run a container using docker run and it immediately exits and every time you press the Start button in Docker Desktop it exits again, there is a problem. The way to figure out what is wrong is to run docker logs, adding the name of the container at the end:
Exit Code 0 1 Exit code 0 indicates that the specific container does not have a foreground process attached. 2 This exit code is the exception to all the other exit codes to follow. It does not necessarily mean something bad happened. 3 Developers use this exit code if they want to automatically stop their container once it has completed its job.
When detached, your container will keep on running even if you exit the container. Your interactive docker session is now in daemon mode. You can verify it using docker ps command to see it in the running containers list. When you want to use it again, you can attach the container again. This way the container starts and run in the background.
So, the docker run is a command to launch Docker containers. Why containers exit on docker run? Containers exit on docker run due to many reasons. And mostly this can happen due to improper setup of Dockerfile.
All that you need to do is pass the -d
option to the run command:
docker run -d -p 8080:80 my-container
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With