SoFunction
Updated on 2025-03-09

The docker container is exited after running (how can it be run all the time)

Phenomenon

Start the docker container

docker run –name [CONTAINER_NAME] [CONTAINER_ID] 

Check the container running status

docker ps -a 

I found that the mydocker container that just started has exited

reason

A very important point to be explained: when the Docker container runs in the background, there must be a foreground process.

If the commands run by the container are not those that have been suspended (such as running top or tail), they will automatically exit.

The main thread of the docker container (the command executed by CMD in the dockfile) ends, and the container will exit

Solution

Can be started using interactively

docker run -i [CONTAINER_NAME or CONTAINER_ID]

The above is not very friendly, it is recommended to use background mode and tty options

docker run -dit [CONTAINER_NAME or CONTAINER_ID]

Check container status

docker ps -a

Docker calls out the background container

docker attach [CONTAINER_NAME or CONTAINER_ID]

TIPs: When exiting, use [ctrl + D], which will end the current thread of docker and the container ends. You can use [ctrl + P][ctrl + Q] to exit without terminating the container running.

The following command will execute the specified command in the specified container. [ctrl+D] will not terminate the container operation after exiting.

docker exec -it [CONTAINER_NAME or CONTAINER_ID] /bin/bash

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.