What’s the difference between “docker exec” and “docker attach”?

Both docker exec and docker attach are commands used to interact with Docker containers, but they have different purposes.

docker exec is used to run a command in a running container. The syntax for docker exec is:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Here, OPTIONS are any additional options you want to provide, CONTAINER is the name or ID of the container you want to run the command in, COMMAND is the command you want to run, and ARG is any additional arguments you want to pass to the command.

For example, if you want to run a bash shell in a running container with ID abc123, you would use the following command:

docker exec -it abc123 bash

This would start an interactive bash session in the container with ID abc123.

docker attach, on the other hand, is used to attach your terminal to a running container. The syntax for docker attach is:

docker attach [OPTIONS] CONTAINER

Here, OPTIONS are any additional options you want to provide, and CONTAINER is the name or ID of the container you want to attach to.

For example, if you want to attach your terminal to a running container with ID abc123, you would use the following command:

docker attach abc123

This would attach your terminal to the running container with ID abc123, and you would see the output of any processes running in the container.

Note that docker attach is not the same as starting a new shell session in the container, as docker exec does. When you use docker attach, you are attaching your terminal to the standard input, output, and error streams of the container, and you are not starting a new process in the container.

Docker

Posted by vastee