Docker exec and docker run

  1. docker run -it bash : This creates a terminal to execute the commands inside a container and when i use exit command container then container stopped.

  2. docker start : This is used to start the above stopped container

  3. docker exec -it bash : This is used to exec into the the running container . Now i used exit command to stop the bash process.

  4. After using exit command, container is still up running and it is verified using docker ps command.

exit command used at first stopped the container and exit command used at last did not stop the container.

WHY IS IT SO ?

Hello @dnpuneeth3,

In the first case, you run the bash container and attach it to the current process (run without -d flag), so when you press Ctrl + C or use the exit command, it terminated the current process and also the container.

When you use docker start container_name, detach mode is used by default, so when you exec to it and exit, it doesn’t terminate the container.

Detached mode, shown by the option --detach or -d , means that a Docker container runs in the background of your terminal. It does not receive input or display output.

Happy learning,
Trung.

1 Like

Why Ctrl + C or exit does not works in detached mode ?

Hello dnpuneeth3
exit should be working fine. Also, you can use Ctrl +d to exit from a container.

Hi @dnpuneeth3,

With our -d flag, the container run but the terminal is connected to the container also. When we exit, it terminates the current process of the terminal and also the container.
When running in detached mode, Docker will start your container the same as before but this time will “detach” from the container and return you to the terminal prompt.
In the 2nd situation, the container is running in the background, so it doesn’t relate to the terminal and will not be stopped when you exit or Ctrl + C.
Please read this for more detail: Run your image as a container | Docker Docs

Happy learning,
Trung.