这里是初学者 Docker 问题,
所以我有一个运行模块化应用程序的开发环境,它使用 Docker Compose 运行 3 个容器:服务器、客户端、数据库。
docker-compose.yml
看起来像这样:
#############################
# Server
#############################
server:
container_name: server
domainname: server.dev
hostname: server
build: ./server
working_dir: /app
ports:
- "3000:3000"
volumes:
- ./server:/app
links:
- database
#############################
# Client
#############################
client:
container_name: client
domainname: client.dev
hostname: client
image: php:5.6-apache
ports:
- "80:80"
volumes:
- ./client:/var/www/html
#############################
# Database
#############################
database:
container_name: database
domainname: database.dev
hostname: database
image: postgres:9.4
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=root
- POSTGRES_DB=dbdev
- PG_TRUST_LOCALNET=true
ports:
- "5432:5432"
volumes:
- ./database/scripts:/docker-entrypoint-initdb.d # init scripts
您可以看到我正在为每个人分配一个 .dev 域名,这可以很好地从另一台机器(Docker 内部网络)查看一台机器,例如这里我正在 ping server.dev
来自 client.dev
的 CLI:
root@client:/var/www/html# ping server.dev
PING server.dev (127.0.53.53): 56 data bytes
64 bytes from 127.0.53.53: icmp_seq=0 ttl=64 time=0.036 ms
这在内部很好用,但在我的主机操作系统网络上不行。
为方便起见,我想在我的本地网络中分配域,而不是在 Docker 容器网络中,这样我就可以在浏览器 URL 上输入 client.dev 并加载 Docker 容器。
目前,我只能使用动态的 Docker IP 访问:
client: 192.168.99.100:80
server: 192.168.99.100:3000
database: 192.168.99.100:5432
是否有一种自动/方便的方法可以做到这一点,而不需要我手动将 IP 添加到我的/etc/hosts 文件中?
顺便说一句,如果这有任何相关性,我在 OSX 上。
谢谢!
编辑:我发现了这个似乎相关的 Github 问题:https://github.com/docker/docker/issues/2335
据我了解,他们似乎说这是开箱即用的东西,他们建议使用外部工具,例如:
- https://github.com/jpetazzo/pipework
- https://github.com/bnfinet/docker-dns
- https://github.com/gliderlabs/resolvable
正确吗?如果是这样,在我的特定场景中我应该选择哪一个?
最佳答案
好的,
所以自从 it seems that there is no native way to do this with Docker ,我终于选择了这个alternate solution来自 Ryan Armstrong,其中包括动态更新 /etc/hosts
文件。
我之所以选择这个,是因为它作为一个脚本工作,对我来说很方便,而且我已经有一个启动脚本,所以我可以将这个函数附加到它上面。
The following example creates a hosts entry named docker.local which will resolve to your docker-machine IP:
update-docker-host(){ # clear existing docker.local entry from /etc/hosts sudo sed -i '' '/[[:space:]]docker\.local$/d' /etc/hosts # get ip of running machine export DOCKER_IP="$(echo ${DOCKER_HOST} | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')" # update /etc/hosts with docker machine ip [[ -n $DOCKER_IP ]] && sudo /bin/bash -c "echo \"${DOCKER_IP} docker.local\" >> /etc/hosts" } update-docker-host
当我通过启动脚本启动 Docker 机器时,这将在我的主机操作系统上自动添加或更新 /etc/hosts
行。
无论如何,正如我在研究中发现的那样,除了编辑 hosts 文件之外,您还可以通过 setting up a custom DNS server 来解决这个问题。 :
还在 Github 上找到了几个显然旨在解决这个问题的项目,虽然我没有尝试过:
关于docker - Docker 容器的本地主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36151981/