01.07.2024

How to keep the Docker container running after starting services

What's the problem point

Docker will run pre-built software into the "sandboxed" container. On the one hand, this approach us to provide absolutely idempotence, we have a guarantee that software is not dedends of the environment and "behaviour" is the same at any time. On the other hand, Docker will stops when predefined commands done. Example - container will immidiately stops after echo command:

docker run <image> <command>   # Run command
docker ps  # Check the running containers

This Docker's bahaviour is not a bug, it is a feature to save system resources. But sometimes container should run permanently, e.g. if software should wait "incoming" connections.

How to "force" Docker container never stops

You can got your aim several methods:

Pseudo-terminal launch. This way is good if you need to keep container running time-to-time. Just run your command with -it flags:

docker run -it <image> bash   # Run command interpreter
<command>   # Run command "inside" the container
docker ps  # Check the container status

Run any command "in a loop". To prevent container stop you can run any command in a cycle, then you can close the terminal session:

docker run <image> bash -c <command>

Then just check container status:

docker ps

You can get the same result if run docker in "detached" mode. Just use -d flag:

docker run <image> bash -c <command>
# Run command docker ps  # Check the running containers

Conclusion

After this article reading you knew how to save docker container alive even if your scenario finished.