Search code examples
dockertelnetnetcatbusybox

Why docker close the tcp connection immediately?


I use this command to test the net connectivity in the terminal:

docker run --rm --name test -it -p 9999:9999 busybox nc -l 0.0.0.0:9999

and in another terminal

$ telnet localhost 9999
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.

seemed it connected by closed immediately, I can not input anything.

it's working fine when I try localy

nc -l 0.0.0.0:9999

and

telnet localhost 9999

Docker version 17.12.1-ce, build 7390fc6 Ubuntu VERSION="18.04.1 LTS (Bionic Beaver)"


Solution

  • There are 2 total different style netcat. The nc in container is not the same series with your host, so host pass, container solution fail.

    I guess your host nc is not traditional one, something like follows:

    # nc
    This is nc from the netcat-openbsd package. An alternative nc is available
    in the netcat-traditional package.
    usage: nc [-46bCDdhjklnrStUuvZz] [-I length] [-i interval] [-O length]
          [-P proxy_username] [-p source_port] [-q seconds] [-s source]
          [-T toskeyword] [-V rtable] [-w timeout] [-X proxy_protocol]
          [-x proxy_address[:port]] [destination] [port]
    

    You container nc is a different version, it has a total different command syntax:

    # docker run --rm --name test -it -p 9999:9999 busybox /bin/sh
    / # nc
    BusyBox v1.29.3 (2018-10-01 22:37:18 UTC) multi-call binary.
    
    Usage: nc [OPTIONS] HOST PORT  - connect
    nc [OPTIONS] -l -p PORT [HOST] [PORT]  - listen
    
            -e PROG Run PROG after connect (must be last)
            -l      Listen mode, for inbound connects
            -lk     With -e, provides persistent server
            -p PORT Local port
            -s ADDR Local address
            -w SEC  Timeout for connects and final net reads
            -i SEC  Delay interval for lines sent
            -n      Don't do DNS resolution
            -u      UDP mode
            -v      Verbose
            -o FILE Hex dump traffic
            -z      Zero-I/O mode (scanning)
    

    If you use netstat in container, you will find 9999 port was not open with your command, as a result, your client quit immediately.

    So, you need to change your command to follows:

    docker run --rm --name test -it -p 9999:9999 busybox nc -l -p 9999