Docker Attach to a running container


Example

'Attaching to a container' is the act of starting a terminal session within the context that the container (and any programs therein) is running. This is primarily used for debugging purposes, but may also be needed if specific data needs to be passed to programs running within the container.

The attach command is utilized to do this. It has this syntax:

docker attach <container>

<container> can be either the container id or the container name. For instance:

docker attach c8a9cf1a1fa8

Or:

docker attach graceful_hopper

You may need to sudo the above commands, depending on your user and how docker is set up.

Note: Attach only allows a single shell session to be attached to a container at a time.

Warning: all keyboard input will be forwarded to the container. Hitting Ctrl-c will kill your container.

To detach from an attached container, successively hit Ctrl-p then Ctrl-q

To attach multiple shell sessions to a container, or simply as an alternative, you can use exec. Using the container id:

docker exec -i -t c8a9cf1a1fa8 /bin/bash

Using the container's name:

docker exec -i -t graceful_hopper /bin/bash

exec will run a program within a container, in this case /bin/bash (a shell, presumably one the container has). -i indicates an interactive session, while -t allocates a pseudo-TTY.

Note: Unlike attach, hitting Ctrl-c will only terminate the exec'd command when running interactively.