如何通过“主机名"在 Docker 容器之间进行通信 [英] How to communicate between Docker containers via "hostname"
问题描述
我计划将我的单体服务器拆分成许多小型 docker 容器,但还没有找到一个很好的容器间通信"解决方案.这是我的目标场景:
I plan to split my monolthic server up into many small docker containers but haven't found a good solution for "inter-container communication" yet. This is my target scenario:
我知道如何将容器链接在一起以及如何公开端口,但这些解决方案都没有让我满意.
I know how to link containers together and how to expose ports, but none of these solutions are satisfying to me.
是否有任何解决方案可以像在传统服务器网络中那样通过主机名(容器名称)在容器之间进行通信?
推荐答案
在 Docker 1.9 之后,docker network
命令(见下文 https://stackoverflow.com/a/35184695/977939) 是实现此目的的推荐方法.
After Docker 1.9, the docker network
command (see below https://stackoverflow.com/a/35184695/977939) is the recommended way to achieve this.
我的解决方案是在主机上设置一个 dnsmasq 来自动更新 DNS 记录:A"记录具有容器的名称并自动指向容器的 IP 地址(每 10 秒).自动更新脚本</a>粘贴在这里:
My solution is to set up a dnsmasq on the host to have DNS record automatically updated: "A" records have the names of containers and point to the IP addresses of the containers automatically (every 10 sec). The automatic updating script is pasted here:
#!/bin/bash
# 10 seconds interval time by default
INTERVAL=${INTERVAL:-10}
# dnsmasq config directory
DNSMASQ_CONFIG=${DNSMASQ_CONFIG:-.}
# commands used in this script
DOCKER=${DOCKER:-docker}
SLEEP=${SLEEP:-sleep}
TAIL=${TAIL:-tail}
declare -A service_map
while true
do
changed=false
while read line
do
name=${line##* }
ip=$(${DOCKER} inspect --format '{{.NetworkSettings.IPAddress}}' $name)
if [ -z ${service_map[$name]} ] || [ ${service_map[$name]} != $ip ] # IP addr changed
then
service_map[$name]=$ip
# write to file
echo $name has a new IP Address $ip >&2
echo "host-record=$name,$ip" > "${DNSMASQ_CONFIG}/docker-$name"
changed=true
fi
done < <(${DOCKER} ps | ${TAIL} -n +2)
# a change of IP address occured, restart dnsmasq
if [ $changed = true ]
then
systemctl restart dnsmasq
fi
${SLEEP} $INTERVAL
done
确保您的 dnsmasq 服务在 docker0
上可用.然后,使用 --dns HOST_ADDRESS
启动您的容器以使用此迷你 dns 服务.
Make sure your dnsmasq service is available on docker0
. Then, start your container with --dns HOST_ADDRESS
to use this mini dns service.
参考:http://docs.blowb.org/setup-host/dnsmasq.html
这篇关于如何通过“主机名"在 Docker 容器之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!