11

TL;DR: how do I get a client in my container to make an HTTPS connection to a service on the host?

I've got a service running on a VM on my local dev machine (macOS) that's serving HTTPS on port 8443; it's got a certificate for dev.mycoolproject.com and dev.mycoolproject.com has an A record pointing to 127.0.0.1. So, if I run my client on my local machine and point it to https://dev.mycoolproject.com:8443 it makes a secure connection to my local service.

I want to run my client inside a docker container and still have it connect to that local server on the host. But obviously dev.mycoolproject.com pointing at 127.0.0.1 won't work, and I can't just use /etc/hosts to redirect it because the host's IP is dynamic. I can reach the local server at host.docker.internal:8443, but I'll get TLS errors because the hostname doesn't match.

Is there any way I can get docker's DNS to map dev.mycoolproject.com to the host IP? I looked into running dnsmasq locally in the container but I had trouble getting it to work.

Emoses
  • 345
  • 1
  • 3
  • 8
  • I guess it can help you https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach – Andrei Kovrov Sep 30 '20 at 23:00
  • 1
    I looked at that answer and I didn't find what I needed: I'm on a macOS host, so I can't use host networking, and I think I explained in my question why I can't just use `host.docker.internal` – Emoses Sep 30 '20 at 23:44
  • Try this speciffic answer: https://stackoverflow.com/a/43541681/397872 @Emoses – Jacek Krysztofik May 03 '22 at 12:07

2 Answers2

10

In a container where you might not have access to tools like dig or nslookup and don't want to install another 55MB package (like debian's dnsutils) just to get the host.docker.internal IP it might be better to use getent instead of dig:

getent hosts host.docker.internal | awk '{ print $1 }'
dpr
  • 10,591
  • 3
  • 41
  • 71
  • Good call! I was working in a debian container so `dig` was on hand. `getent` works great too. – tgtb Dec 05 '21 at 18:12
5

I ran into a similar issue yesterday and came up with a workaround that adds an entry to /etc/hosts resolving to the the host IP.

You'll need dig or another DNS tool to query for the IP.

If you are running as root you can use:

echo "$(dig +short host.docker.internal) dev.mycoolproject.com" >> /etc/hosts

If you have sudo you can run:

echo "$(dig +short host.docker.internal) dev.mycoolproject.com" | sudo tee -a /etc/hosts

Initially I was hoping the --add-host run option would allow for special docker entries in the host ip argument (like host.docker.internal) but unfortunately they don't.

I wanted to avoid more container configuration so I went with this. Setting up dnsmasq would be a more stable solution.

tgtb
  • 161
  • 6