Slow network requests within the docker container are resolved

  • 2021-01-03 21:09:35
  • OfStack

Found several problems in the process of using docker, requests for network in docker often fail, such as npm install and bundle install operations such as, or as an intermediary in the application to access frequently, timeout api data process, and so on and so forth, so start explore docker network mechanism, to solve the problem of slow network request.

1. Network mode of docker

1, none

When configured with none, the docker container network is input-output and isolated.

2, bridge
The default is bridge mode, with docker having its own virtual network card and bridging the network from the host.

3, host
When it is designated as host, the network card of the host is directly exposed to the container and directly accesses the Internet through the network of the host. For example, if you want to get redis service 127.0.0.1:6357 on the host, you have to use this method, but it is less secure.

4, container
Use a network of other containers

2. dns

docker container is also linux in nature, so dns's parsing method is similar to linux1, the priority is to find /etc/hosts file, such as localhost domain name is written in this file, such as:


127.0.0.1 localhost

If docker container link has another container, there will also be an extra domain name of link, such as:


docker run --name app --link app-redis:redis -d ubuntu

It's going to be in hosts


172.17.0.3 app-redis 038c8388e4a1

Find /etc/hosts file, then /etc/ resolv.conf file:


domain local
nameserver 192.168.65.1
nameserver 192.168.65.10

3. Solve the problem of slow network requests in docker container

After packet capture test and other analysis, it was found that the slow network request mainly occurred in dns parsing, so dns optimization was mainly adopted:

If you are requesting api for your own Intranet, you can directly modify the file /etc/hosts, or if you are requesting an extranet, you can change nameserver in /etc/ resolv.conf.

The docker container is certainly not implemented directly by modifying the file. It can be implemented by the run command:


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

This speeds up the time of the dns parsing phase in the docker container


Related articles: