I am very new to Docker and I have been able to understand 4 things
along with some basic commands like docker run, docker log etc.
Now, I came across this command docker attach
with a description here
Use docker attach to attach to a running container using the container’s ID or name, either to view its ongoing output or to control it interactively. You can attach to the same contained process multiple times simultaneously, screen sharing style, or quickly view the progress of your detached process.`
I have no idea what do they mean when they say we can attach if we want to view a container's ongoing activity or output?
If I have a Container for a console application and I simply do docker run
on it then I can see the output right there in the console window.
What could be a few benefits of 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) ...
In this mode, the console you are using to execute docker run will be attached to standard input, output and error. That means your console is attached to the container's process. In detached mode, you can follow the standard output of your docker container with docker logs -f <container_ID> . Just try both options.
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.
When containers are run with the interactive option, you can connect to the container and enter commands as if you are on the terminal:
$ docker run -itd --name busybox busybox dcaecf3335f9142e8c70a2ae05a386395b49d610be345b3a12d2961fccab1478 $ docker attach busybox / # echo hello world hello world
The attach
option also allows multiple connections to view the same container and see what each is typing.
Lastly, while connected to a container with the tty option (-t
), you can type Control-P Control-Q to detach from that container and leave it running in the background. You can then attach to that container again in the future.
What is Docker attach?
Allows one terminal to attach a running container. It allows you to connect to process' STDIO in another terminal.
What's the benefit?
Docs:
This allows you to view its ongoing output or to control it interactively, as though the commands were running directly in your terminal.
Here's a demo of attach:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With