前端 docker容器内网络请求缓慢问题

stackvirgil · November 06, 2019 · 108 hits

原文链接:https://www.embbnux.com/2016/10/06/docker-container-network-too-slow-timeout/

一、docker 的网络模式

1、none

当配置为 none 时,docker 容器网络无法输入输出,与世隔绝。

2、bridge

默认为 bridge 模式,docker 有自己的虚拟网卡,通过桥接的方式从主机获得网络。

3、host

当指定为 host 时,主机的网卡直接暴露给了容器,直接通过主机的网络上网,比如要拿主机上的 redis 服务 127.0.0.1:6357,就得通过这种方法,不过就比较不安全了。

4、container

使用其他容器的网络

二、docker 的 dns 解析

docker 容器本质上也是个 linux,所以 dns 的解析方法和 linux 一样,优先是找/etc/hosts 文件,像 localhost 这种域名就是写在这个文件里,比如:

1
2
3
4
5
6
7
8
9
10
11
12
127.0.0.1 localhost
如果docker容器link了其他容器,这里也会多出link的域名,比如:

docker run --name app --link app-redis:redis -d ubuntu
就会在hosts里多出

172.17.0.3 app-redis 038c8388e4a1
找完/etc/hosts文件,然后是/etc/resolv.conf文件:

domain local
nameserver 192.168.65.1
nameserver 192.168.65.10

三、解决 docker 容器里网络请求慢的问题

经过抓包测试等分析,发现网络请求慢,主要发生在 dns 解析中,所以主要采取 dns 优化:
如果请求的是自己内网的 api, 可以直接修改/etc/hosts 文件,如果是外网的请求可以通过更改/etc/resolv.conf 里的 nameserver 实现。
docker 容器肯定不是直接通过修改文件实现的,可以通过 run 的命令

1
2
3
4

docker run --name app --add-host='api.embbnux.com:10.98.10.98' -d ubuntu
# 指定dns server
docker run --name app --dns=223.5.5.5 --dns=8.8.8.8 -d ubuntu

这样在 docker 容器里 dns 解析阶段的时间就被加速了

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.