为什么docker立即关闭tcp连接?

时间:2018-10-17 05:51:30

标签: docker telnet netcat busybox

我使用此命令来测试终端中的网络连接:

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

和另一个终端

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

好像它被关闭立即连接起来,我什么都不能输入。

当我尝试本地设置时,效果很好

nc -l 0.0.0.0:9999

telnet localhost 9999

Docker版本17.12.1-ce,内部版本7390FC6 Ubuntu VERSION =“ 18.04.1 LTS(Bionic Beaver)”

1 个答案:

答案 0 :(得分:2)

共有2种不同的样式netcat。容器中的nc与您的主机的序列不同,因此主机传递,容器解决方案失败。

我猜您的主机nc不是传统主机,如下所示:

# 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]

您的容器nc是一个不同的版本,它的命令语法完全不同:

# 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)

如果在容器中使用netstat,则会发现9999端口未通过命令打开,结果是客户端立即退出。

因此,您需要将命令更改为以下内容:

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