Search code examples
dockerterminal

`sh` in Docker behaves buggy (related to i/o)


When I try to connect to my docker container (got from https://github.com/gitcoinco/passport-scorer), it outputs weird symbols to console:

$ docker exec -t passport-scorer_postgres_1 sh
/ # ^[[45;5R

Pressing ENTER does not work as expected for sh: it just moves the cursor to beginning of the next line (new sh prompt is not produced).

If I type ls and press ENTER in this prompt (both directly after this or after first removing ^[[45;5R by Backspace), the cursor is just moved to the next line (ls is not executed).

However, this works as expected:

docker exec -t passport-scorer_postgres_1 ls

Help to connect to my container.

I use Gnome Terminal.

$ echo $TERM
xterm-256color

Solution

  • You have to use the -i flag as well (combined -it).

    As Docker official documentation says:

    --interactive -i Keep STDIN open even if not attached

    --tty -t Allocate a pseudo-TTY

    Example with detailed comments:

    # It's not working as you expect because the STDIN is not open (-i)
    # so the container doesn't handle the written things from terminal
    # (Only the direct command is executed inside the container).
    # -------------
    >>> docker exec -t 27a4dcfe37df sh
    # 
    ls
    
    # It's working if I pass directly the "ls" command
    # (Because the STDIN is not needed for further operations,
    # just run the provided command and that's it).
    # -------------
    >>> docker exec -t 27a4dcfe37df ls. 
    bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    
    # It's working as you expect.
    # The STDIN is kept open (-i) so the user can operate in the terminal
    # (inside container). In other words, the container can handle the
    # provided details from STDIN.
    # -------------
    >>> docker exec -it 27a4dcfe37df sh
    # ls
    bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    #