在Docker容器中访问服务时哪种方式更快?

在泊坞窗容器中运行的服务。

假设容器的IP为172.18.0.4,端口为'-p 1234:8888'。

那么访问主机中的服务,哪种方式更快?

  • 172.18.0.4:8888
  • 127.0.0.1:1234

如何测量

我使用命令dd if=/dev/zero of=~/file bs=8k count=20000创build了一个157 MB的文件。 命令netcat将被用来将这个文件从主机传送到容器(带有发布的端口)。 有关如何使用netcat传输文件的详细信息logging在联机帮助页中。

使用容器IP地址

 user@host:~$ time nc -x 172.20.0.2 8888 < file nc -x 172.20.0.2 8888 < file 0.00s user 0.07s system 38% cpu 0.178 total user@host:~$ time nc -x 172.20.0.2 8888 < file nc -x 172.20.0.2 8888 < file 0.00s user 0.05s system 36% cpu 0.152 total user@host:~$ time nc -x 172.20.0.2 8888 < file nc -x 172.20.0.2 8888 < file 0.00s user 0.06s system 35% cpu 0.169 total 

使用本地主机IP地址

 user@host:~$ time nc -x 127.0.0.1 8888 < file nc -x 127.0.0.1 8888 < file 0.00s user 0.06s system 33% cpu 0.180 total user@host:~$ time nc -x 127.0.0.1 8888 < file nc -x 127.0.0.1 8888 < file 0.00s user 0.06s system 38% cpu 0.158 total user@host:~$ time nc -x 127.0.0.1 8888 < file nc -x 127.0.0.1 8888 < file 0.00s user 0.06s system 40% cpu 0.137 total 

平均

使用该命令的六个传输持续时间,平均持续时间是: – 使用容器IP地址 – 0.166。 – 0.158使用本地主机IP地址。 有8毫秒的差异。

结论

免责声明:该文件不是我的$HOMEDIR而是映射到内存中的/tmp 。 读取然后更快。 我不知道什么time命令停止了: – 当最后一个TCP数据包被发送了? – 最后一个TCP数据包被缓冲了吗? – 收到最后一个ACK时? 我会打赌这一个

在任何方面,8毫秒的差异,国际海事组织,不是一个大问题。 即使8毫秒的加载页面有时会有很大的不同,caching静态文件可以提供更好的结果比这种差异更快。

回答

使用本地主机IP地址似乎更快。


更多的testing..

确认localhost的IP地址有一个小的标准偏差(0.045 vs 0.024)。 请注意,差异(9 ms)约为平均传输持续时间(169 ms)的5%。

我的猜测是,它会是一样的。

您可以通过configuration容器来使用主机的networking堆栈来提高性能。

docker run --net=host ...

这保证了最佳性能,但是容器中的所有端口都将暴露给主机。

参考: https : //docs.docker.com/engine/reference/run/#network-host