Skip to main content

Optimizing Nginx Startup: How to Delay DNS Lookup in proxy_pass

·299 words·2 mins
Sebastian Scheibe
Author
Sebastian Scheibe
Table of Contents

In Nginx configurations where proxy_pass directives include domain names, startup delays or failures can occur if those domains are unreachable.

You might have seen an error like this:

host not found in upstream "this-domain-does-not.exist" in /etc/nginx/sites-enabled/test.com:18

This issue can significantly slow down the server’s response time or prevent Nginx from booting entirely. Fortunately, there’s a straightforward workaround to prevent Nginx from performing DNS lookups at startup, thereby improving its initialization speed.

Common Scenario
#

Typically, your Nginx configuration might look something like this:

server {
    listen 80;
    server_name test.com;

    location / {
        proxy_pass https://thirdpartydomain.com;
    }
}

In the above setup, Nginx attempts to resolve the domain thirdpartydomain.com at startup. If the domain is unreachable, this resolution can delay or even block the server from starting.

Optimized Configuration
#

To circumvent this issue, you can modify the configuration to delay DNS resolution until the proxy_pass directive is actually processed. This method involves using a variable to store the upstream domain, which Nginx will resolve only when the location is accessed:

server {
    listen 80;
    server_name test.com;
    
    location / {
        set         $upstream_foo thirdpartydomain.com;
        proxy_pass  https://$upstream_foo;
    }
}

With this configuration, Nginx bypasses DNS resolution at startup and defers it until the / location is requested. This adjustment not only speeds up the server startup but also allows flexibility in managing DNS issues without disrupting the initial loading process.

Check here for more information about proxy_pass.

Specifying DNS resolver
#

In case the domain you are accessing is internal, you might want to specify a DNS manually. For that, just add the resolver entry with a DNS server IP.

Check here for more information about resolver.

server {
    listen 80;
    server_name test.com;
    
    location / {
        set         $upstream_foo thirdpartydomain.com;
        resolver    1.1.1.1;
        proxy_pass  https://$upstream_foo;
    }
}

References
#