Attach to the running container and observe its output
In the previous step, we started a container in detached mode. Although the container ran a simple command and likely exited quickly, we can still attach to it to see its output. The docker attach
command allows you to connect to the standard input, output, and error streams of a running or exited container.
First, let's get the ID of the container we started in the previous step. You can use the docker ps -a
command and look for the container running the echo
command. Copy the container ID.
docker ps -a
Now, use the docker attach
command followed by the container ID to attach to the container.
docker attach <container_id>
Replace <container_id>
with the actual ID of your container. Since the container ran a simple echo
command and exited, you might not see any output immediately, or you might see the output "Hello from detached container!" if the output is still buffered. The attach
command will connect you to the container's streams. Because the container has already finished its task, the attach
command will likely exit immediately after connecting.
To demonstrate attaching to a container that stays running, let's start a new detached container that runs a command which keeps it alive for a few seconds. We'll use the ubuntu
image again and run sleep 10
.
docker run -d ubuntu sleep 10
Get the ID of this new container using docker ps
. This time, the container should be in the Up
state.
docker ps
Now, attach to this running container using its ID.
docker attach <new_container_id>
Replace <new_container_id>
with the ID of the container running sleep 10
. You will be attached to the container's standard streams. Since the sleep
command doesn't produce output, you won't see anything. The terminal will appear to be waiting. The container will run for 10 seconds and then exit. When the container exits, the attach
command will also exit, returning you to your terminal prompt.