32

Can /etc/hosts be used instead of resolver when using proxy_pass?

I need to perform a proxy_pass to the same nginx machine. Is there a way to resolve the domains using the machine's /etc/hosts file instead of specifying a DNS server thru the "resolver" property?

This will save me the additional hops needed to reach the same server. I have tried setting up the internal IP mapped to the DNS in /etc/hosts file but nginx is still reading from the DNS server set in the resolver property. Or is there a way to make the HTTPProxy module to consider the /etc/hosts file settings?

Thanks for any advice you could share..

This is the same question I posted in the nginx forum: http://forum.nginx.org/read.php?11,218997

Ianthe the Duke of Nukem
  • 1,581
  • 2
  • 19
  • 37
  • 1
    The strange thing , this is working if you use upstream (host resolution) – Thomas Decaux Jul 19 '17 at 15:33
  • Upstream worked for me as well, it's a bit of extra code but it seems cleaner than some of the other methods listed below. – rage8885 May 12 '20 at 19:18
  • It also possible to workaround with systemd-resolved if using a server with systemd. See this answer https://stackoverflow.com/a/64909236/153718 – Epeli Nov 19 '20 at 10:00

2 Answers2

42

You can get around this by installing dnsmasq and setting your resolver to 127.0.0.1. Basically this uses your local DNS as a resolver, but it only resolves what it knows about (among those things is your /etc/hosts) and forwards the rest to your default DNS.

Mikael Karon
  • 553
  • 5
  • 8
  • 5
    But sadly `dnsmasq` does not automatically detect changes in `hosts` file. You have to send `HUP`. – Mitar Dec 16 '14 at 16:51
  • 1
    Can you give more details on how we should setup dnsmasq in order to get our nginx to resolve the other container dns name properly ? just installing dnsmasq and adding extra_hosts: - "container_name:127.0.0.1" to my docker-compose.yml config didn't resolve the issue – Adrien Lemaire Jan 23 '19 at 03:37
  • If you are using docker I think DNS works a little bit different, especially if you're doing container to container communication. Check out the [docker networking configuration](https://docs.docker.com/config/containers/container-networking/) for more info. – Mikael Karon Jun 12 '19 at 10:38
5

A workaround is to use Nginx map, in order to copy the /etc/hosts content.

map $wanted_host $wanted_host_ip
{
    default 127.0.0.1;
    b.dev.local X.X.X.X;
    a.dev.local X.X.X.X;
}

server
{
    listen              80;
    server_name         ~^(?P<wanted_port>[0-9]+?)-(?P<wanted_host>.+?)\.HOSTNAME$;

    location /
    {
        proxy_pass http://$wanted_host_ip:$wanted_port;

    }
}

This will map wanted_hostto wanted_host_ip , like a resolver.

Thomas Decaux
  • 18,451
  • 2
  • 83
  • 95