0

I am running a container with docker run --name cont -dt img. As I understand this provides the container with a tty but will not attach stdout, stderr and stdin of my host terminal to the container which is also running in the background.

Now I thought that if I did docker attach cont (docker documentation says it attaches stdio to a running container, attach) I would obtain the same effect (by running first docker logs cont to see the stdout before the prompt) as running docker run --name cont -it img (display stdout/sterr allocate a tty and connect the stdin to the container). However my host terminal attaches but just hangs and ctrl+c must be used to detach (ctrl+p+q will not work).

I'd like to understand why attach does not work like I intend it? I mean the true logic behind it and how you came to understand this if possible, I know that running cont with the option -dit and reattaching works. If anybody has tips or can point to some reading sources to understand this it would help a lot. Thanks!

Dockerfile

FROM ubuntu:latest

RUN apt update -y
COPY . /tmp
WORKDIR /tmp
CMD ["/tmp/app.sh"]

app.sh

#!/bin/sh
echo "Enter your name: "
read name
echo "Hello ${name}!"
lucmobz
  • 151
  • 1
  • 6

1 Answers1

0

Without -i you have not connected stdin to the container. You'll still see any formatted output that a tty is used for, but it's only stdout/stderr. And from your experimentation, the detach signal (cont-P cont-Q) needs that stdin to be connected to be processed. For more on the -it flags, see this answer.

BMitch
  • 231,797
  • 42
  • 475
  • 450
  • But `docker attach cont` *should* connect stdout/stderr/stdin from host to guest as it says in the documentation. That is what I do not understand. – lucmobz Jan 10 '22 at 10:32
  • @lucmobz it would attach stdin if it existed, but that doesn't exist to attach to when the container is created without the option. – BMitch Jan 10 '22 at 11:51
  • Ok it makes sense, but the documentation about `docker attach` I found really confusing as it did not mention *attach if it exists*. – lucmobz Jan 10 '22 at 11:56
  • It still is confusing however that if I run `docker run --name cont -a stdin -it img` (which I assume is attach stdin but not stdout/sterr) I can type something that is not disaplayed (which makes sense because no stdout), can hit enter, from another terminal I see the container is stopped, but my terminall still hangs. If instead I detach with `ctrl+p+q` which works (as I used `-it`) and do `docker attach cont` now I can type and hit enter and it will display stdout (nonsense as I did not run the container with stdout in the beginning). Very puzzling. Thanks for the answer though. – lucmobz Jan 10 '22 at 12:05
  • @lucmobz perhaps a bug, the code is open source under moby/moby and docker/cli. – BMitch Jan 10 '22 at 12:51