Mikrotik DNS Failover Script

Traditionally, a minimum of two DNS servers are used for any given computer for redundancy. The problem is that Windows computers (and others) will choose the fastest responding server and ignore the order given (primary, secondary, etc.). If we wish to force a primary and only fail over to a secondary, then scripting coupled with Netwatch in RouterOS can help. We begin with entering our primary DNS server IP under IP > DNS. Any static or DHCP clients should use the Mikrotik router’s IP as their DNS server. Next, we create two scripts to handle conditions of either:
A) the primary DNS is up or
B) the primary DNS is down and we need to roll to the backup IP

If our primary DNS IP is 1.1.1.1 and our backup is 2.2.2.2, our scripts will look like:
[sourcecode language=”plain”]
/system script
add name=dnsdown policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive source="/ip dns set allow-remote-requests=yes cache-max-ttl=1w cache-size=2048KiB max-udp-packet-size=512 servers=2.2.2.2"
add name=dnsup policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive source="/ip dns set allow-remote-requests=yes cache-max-ttl=1w cache-size=2048KiB max-udp-packet-size=512 servers=1.1.1.1"
[/sourcecode]

Then, we create a netwatch entry to monitor (via ping) our primary DNS server IP every 30 seconds:
[sourcecode language=”plain”]
/tool netwatch
add comment="" disabled=no down-script="/system script run dnsdown" host=1.1.1.1 interval=30s timeout=1s up-script="/system script run dnsup"
[/sourcecode]