Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker: reattach to `docker exec` process

Tags:

docker

If I use docker exec to fire up a shell,

docker exec -ti <CONTAINER> /bin/bash

I could use Ctrl+p Ctrl+q to detach this shell process. Then this shell is still running inside the container, but how can I reattach to that one particular shell (the one started by docker exec, not docker run)?

like image 260
Wirawan Purwanto Avatar asked Jan 28 '16 18:01

Wirawan Purwanto


People also ask

How do you reattach a docker container?

docker run -it and connect from another terminal by docker attach -> press Ctrl+P Ctrl+Q. docker run -it and connect from another terminal by docker attach --no-stdin -> press Ctrl+C.

What is the difference between Docker exec and docker attach?

docker exec executes a new command / create a new process in the container's environment, while docker attach just connects the standard input/output/error of the main process(with PID 1) inside the container to corresponding standard input/output/error of current terminal(the terminal you are using to run the command) ...

How do I get out of Docker exec?

docker exec You can leave the container with exit or ctrl-D .

How detach from docker attach?

Docker supports a keyboard combination to gracefully detach from a container. Press Ctrl-P, followed by Ctrl-Q, to detach from your connection. You'll be dropped back into your shell but the previously attached process will remain alive, keeping your container running.


2 Answers

Sadly, this is not possible yet; see this issue on GitHub. I've also wanted this functionality, but at the moment it seems like there's no direct way to do this.

A workaround has been proposed, to take care of the case where you're accessing a box via ssh and running docker exec on the remote box (or, for the case where your terminal emulator is unstable and may crash on you): Always run your docker exec commands inside screen or tmux. If you do this, whenever you get detached from the screen/tmux session, you can re-attach to it later and still have your docker exec commands accessible. (this is a bit different than what was suggested by @vodolaz095, since it involves running screen or tmux outside the container, making it suitable for use with containers that don't run screen/tmux as their main process)

like image 186
codermonkeyfuel Avatar answered Sep 30 '22 14:09

codermonkeyfuel


docker exec is specifically for running new things in an already started container, be it a shell or some other process.

docker attach is for attaching to a running process, so you can use only one instance of shell.

Run you container(process)

docker run -tid --name <CONTAINER> <IMAGE>:<TAG> bin/bash

Then

docker attach <CONTAINER>

To detach Ctrl+p + Ctrl+q

On this way you can attach and detach multiple times with only one instance of shell

like image 29
Hemerson Varela Avatar answered Sep 30 '22 15:09

Hemerson Varela