How to force nginx to resolve DNS (of a dynamic hostname) every time when doing proxy_pass?

Better Stack Team
Updated on November 23, 2023

By default, Nginx caches DNS records for a certain period to enhance performance. However, if you have a dynamic hostname and you need Nginx to resolve DNS every time a request comes in, you can use the resolver and set directives in the Nginx configuration.

Here's an example of how you can force Nginx to resolve the DNS of a dynamic hostname for each request:

 
http {
    resolver <DNS_IP> valid=30s;  # Replace <DNS_IP> with your DNS server IP

    server {
        listen 80;

        location / {
            resolver <DNS_IP> valid=30s;  # Replace <DNS_IP> with your DNS server IP
            set $backend "your_dynamic_hostname";  # Replace with your dynamic hostname variable

            proxy_pass <http://$backend>;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

Explanation:

  • The resolver directive specifies the DNS server Nginx should use to resolve domain names.
  • The valid parameter in the resolver directive sets the time limit for caching DNS records. In this example, it's set to 30 seconds, meaning DNS records will expire and be re-resolved every 30 seconds.
  • The set directive is used to create a variable ($backend) that holds your dynamic hostname.

This configuration tells Nginx to resolve the DNS for the dynamic hostname every 30 seconds and pass the requests to the resolved IP.

Remember to replace <DNS_IP> with the IP address of your DNS server and "your_dynamic_hostname" with the variable holding your actual dynamic hostname.

Please be cautious with the low caching time, as it might affect the server's performance due to frequent DNS lookups. Adjust the valid parameter as needed for your use case.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github