[英]cant ping docker container by name from host
我的服務器上有很多容器,我需要按名稱(而不是 IP)訪問所有容器。 當然,我可以通過 IP 地址 ping 容器。 問題是我無法通過主機名或名稱 ping 它們。
另外,我不使用 docker-compose。 我使用 docker 文件和 docker restapi
選項 A:運行 DNS 代理服務器容器
這是一個可以執行此操作的DNS proxy server
項目: https://github.com/mageddo/dns-proxy-server
首先,您需要啟動 DNS 代理服務器:
docker run --rm --hostname dns.mageddo -v /var/run/docker.sock:/var/run/docker.sock -v /etc/resolv.conf:/etc/resolv.conf defreitas/dns-proxy-server
然后,運行一個虛擬容器並為其分配一個--hostname
用於測試目的:
docker run -d --hostname=this-can-be-resolved-from-host nginx
最后,嘗試從您的主機解析/ping/curl 您在上一步中分配給 nginx 容器的名稱:
neo@neo-desktop:~$ nslookup this-can-be-resolved-from-host
Server: 172.17.0.4
Address: 172.17.0.4#53
Non-authoritative answer:
Name: this-can-be-resolved-from-host
Address: 172.17.0.3
Name: this-can-be-resolved-from-host
Address: 172.17.0.3
neo@neo-desktop:~$ ping this-can-be-resolved-from-host
PING this-can-be-resolved-from-host (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3 (172.17.0.3): icmp_seq=1 ttl=64 time=0.032 ms
neo@neo-desktop:~$ curl this-can-be-resolved-from-host
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
[...]
選項 B:在 docker 主機上運行直接在hosts
文件中添加容器名稱的注入器:
(由 OP @Tokyo Developer找到的解決方案)
這是一個簡單的“etc/hosts”文件注入工具: https://github.com/dvddarias/docker-hoster
運行注入器容器:
docker run -d \
-v /var/run/docker.sock:/tmp/docker.sock \
-v /etc/hosts:/tmp/hosts \
dvdarias/docker-hoster
運行一個虛擬容器並為其分配一個--hostname
用於測試目的:
docker run -d --hostname=this-can-be-resolved-from-host nginx
嘗試從您的主機解析上一步中分配給 nginx 容器的hostname
和container name
:
nslookup this-can-be-resolved-from-host
Server: 127.0.0.53
Address: 127.0.0.53#53
Non-authoritative answer:
Name: this-can-be-resolved-from-host
Address: 172.17.0.3
nslookup keen_lamarr
Server: 127.0.0.53
Address: 127.0.0.53#53
Non-authoritative answer:
Name: keen_lamarr
Address: 172.17.0.3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.