While implementing reverse proxy in nginx, the IP address of upstream is cached by nginx. This becomes a problem when the upstream server changes its IP address. In my case, I was using a reverse proxy in nginx to access my home server hosted services from the internet. As I did not have a static IP address, I had set up a service which would update the DNS A record of the domain name to the current public IP address of my home network. This worked fine for a while, but after a few days, I noticed that the services were not accessible from the internet. I checked the logs of the home server and found that the IP address of the home server had changed. I checked the DNS record and found that it was updated to the new IP address. However, nginx was caching the IP address of the upstream server and was not refreshing it.
The solution for this problem is to use a variable in the proxy pass directive of nginx, as it forces re-resolution of the DNS name, as nginx treats variables differently to static configuration. With this, a
resolver (the name server to use) must be available and configured for this to work (and entries inside a /etc/hosts file won’t be used in a lookup). The
resolver directive takes the IP address of the DNS server as an argument.
resolver 126.96.36.199 ipv6=off valid=10s;set $home_server "http://example.com:1234/";
Then, inside the
location block, we can use the
$home_server variable in the
That’s it! Now, nginx will refresh the DNS record of the upstream server and will use the new IP address. Hope this post helps you in your journey of learning nginx.