RSS

Docker container to connect localhost of host

Inside Docker container, want to connect service on localhost of host machine. There is a magic hostname host.docker.internal can be used inside Docker container to reach localhost of host machine.

Problem

I have redis running in localhost, when I run a docker VM, I want to connect redis from inside of Docker VM, so I do not need docker-compose for another redis VM.

Solution

Docker for Mac: use host.docker.internal

For Docker on Mac, there is a magic ip 192.168.65.2 in docker VM which represent host machine, or you can just use host.docker.internal inside docker VM will ok.

I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

The gateway is also reachable as gateway.docker.internal.

– From Docker for Mac

host.docker.internal can also pass as env var:

$ docker run \
  -e REDIS_HOST=host.docker.internal \
  -p 8000:8000 \
  --rm \
  --name foo \
  -it foo

container # ping docker.for.mac.localhost
PING docker.for.mac.localhost (192.168.65.2): 56 data bytes
64 bytes from 192.168.65.2: seq=0 ttl=37 time=3.075 ms
64 bytes from 192.168.65.2: seq=1 ttl=37 time=0.597 ms

Docker for Windows: use host.docker.internal

Docker for Windows have similar solution with Docker for Mac, use host.docker.internal.

I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

This is for development purpose and will not work in a production environment outside of Docker Desktop for Windows.

The gateway is also reachable as gateway.docker.internal.

– From Docker for Windows

Docker for Linux

To use host.docker.internal on Docker for Linux, need adding --add-host host.docker.internal:host-gateway , for example:

$ docker run \
  -it \
  --rm \
  --add-host=host.docker.internal:host-gateway \
  alpine \
  cat /etc/hosts

References

OmniLock - Block / Hide App on iOS

Block distractive apps from appearing on the Home Screen and App Library, enhance your focus and reduce screen time.

DNS Firewall for iOS and Mac OS

Encrypted your DNS to protect your privacy and firewall to block phishing, malicious domains, block ads in all browsers and apps

Ad