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

为什么docker会立即关闭tcp连接?,docker,telnet,netcat,busybox,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. 好像它马上就被关闭了,我什么都不能输入 当我在本地尝试

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

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

Docker版本17.12.1-ce,版本7390fc6
Ubuntu VERSION=“18.04.1 LTS(仿生海狸)”

有两种完全不同的风格
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
docker run --rm --name test -it -p 9999:9999 busybox nc -l -p 9999