Attach a Docker container

In this article, we cover how to attach a Docker container. We have already seen how to Execute a command inside Docker container and Connect to a Shell inside Docker container. This is a bit different from the articles previously covered. Here, we mainly attach local Standard Input to the Docker container. And, not only that even standard output and error streams also get attached.

Since, it is necessary to know either Container Name or Container ID before attaching a Docker container. Therefore, use the following syntax to get required data –

docker container ls -a

Attach a Docker container

Use the following syntax to attach a Docker container –

docker container attach [OPTIONS] <Container-NAME/ID>

For instance, for container – ABC

docker container attach ABC

It may return with an error –

You cannot attach to a stopped container, start it first

Reason: Our container isn’t running. Therefore, we have to start it first. Use the following command to start the Docker container, which in this case is ABC –

docker container start ABC

Now, run the command again to attach the Docker container – ABC. This time around it should work –

docker container attach ABC

It is worth mentioning here that, if we try to use Ctrl + D or enter exit it would also stop the running container. Although, we just wanted to detach the container. Instead, it stopped the container itself. So, use the following key combinations to detach the container without stopping it –

Ctrl+p+Ctrl+q

It would return with –

read escape sequence

We can verify whether the container has exited or is still up and running through the following command –

docker container ls -a

In conclusion, we have covered how to attach a Docker container here.

Additional Info –

If we don’t wish to attach Standard Input then use the following syntax –

docker container attach --no-stdin <Container-NAME/ID>

Similar Posts