Alternate Title : Solve the container problem that it stops immediately after running.
When developing with docker you may feel like you want to use certain container like a virtual machine, and keep it running the background when you are not using it.
Or if for some other reason you want to keep the container running but it immediately stops after you run it.
If that sounds like you keep reading.
Let’s create a container first and see it stops
Here you can see the code in docker-compose for a simple container for python:3.7:
So when I run the container from this docker-compose, it shows the following:
You can see from the above image that the container stops.
(So the normal solution is to create a container and bash it to get inside at the time of creating the container, in that case it won’t stop.
But for some edge case, if you want to keep open the container and enter and exit the container to run scripts read ahead. )
The solution : Keep the container running
So there are few ways of making sure that it never stops.
This StackOverFlow link mentions few of them.
The one I like most, after creating the container, is to attach an interactive shell to it. And because that interactive shell is active, it won’t get stopped.
Here’s how you can do it with docker-compose:
Here’s the after running this it doesn’t stop anymore :
From the above image, you can see that the container is not stopping anymore and it is running.
Now you can bash into the container and do what ever you want with the this command :
docker exec -it <container name> bash`
Why the docker container stops
Let me explain why a container gets stopped.
A docker container exits when its main process finishes. Containers main purpose is to run process or processes inside an isolated environment.
So when those process finishes, it gets stopped. Unlike let’s say a VM, containers are efficient. So they won’t stay around if all the processes finishes.
That said, because we run database or web servers inside the container. They are long living processes, so if you run any of those long-running process you will see it won’t get stopped.
Normally, developers don’t run into issues like this. But for some cases, you may need the containers to keep running.