I have many containers on my server, I need to access all containers by the name(not IP). and of course, I can ping containers by IP address. problem is I can't ping them by hostname or name.
also, I don't using docker-compose. I use docker file and docker restapi
Option A: run a DNS proxy server container
Here is a DNS proxy server
project that can do this: https://github.com/mageddo/dns-proxy-server
First, you need to start the DNS proxy server:
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
Then, run a dummy container and assign it a --hostname
for testing purpose:
docker run -d --hostname=this-can-be-resolved-from-host nginx
Finally, try to resolve/ping/curl the name you assigned to the nginx container in the previous step, from your host machine:
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>
[...]
Option B: Run an injector that adds the container names directly in the hosts
file, on the docker host:
(solution found by the OP @Tokyo Developer)
Here is a simple "etc/hosts" file injection tool: https://github.com/dvddarias/docker-hoster
Run the injector container:
docker run -d \
-v /var/run/docker.sock:/tmp/docker.sock \
-v /etc/hosts:/tmp/hosts \
dvdarias/docker-hoster
Run a dummy container and assign it a --hostname
for testing purpose:
docker run -d --hostname=this-can-be-resolved-from-host nginx
Try to resolve the hostname
AND the container name
assigned to the nginx container in the previous step, from your host machine:
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