Setup a wildcard TLD using Dnsmasq on OS X

I run a lot of local and remote development applications, and in order to organize these I started using custom TLDs with descriptive domains and configuring my hosts file to point to the relevant virtual machine. This worked great at first, but it didn't take long to become cluttered and difficult to manage. Since the hosts file doesn't support wildcards, I decided to use Dnsmasq to forward requests. I'm a big fan of Homebrew, but Dnsmasq is available via MacPorts as well. These instructions will assume Homebrew is being used.

$ brew update
$ brew install dnsmasq

The next step is to set up your dnsmasq.conf. The installer probably told you to run this command:

$ cp /usr/local/opt/dnsmasq/dnsmasq.conf.example /usr/local/etc/dnsmasq.conf

Now let's edit /usr/local/etc/dnsmasq.conf to include our custom DNS routing rules. The convention here is /[TLD]/[IP]. You can use IPv6 addresses as well. I'm setting up domains for two virtual machines such that *.vm1 domains resolve to one VM and *.vm2 domains resolve to my second VM.

address=/vm1/192.168.70.101
address=/vm2/192.168.70.102

Copy Dnsmasq into LaunchDaemons to ensure it starts up on every system login.

$ sudo cp -fv /usr/local/opt/dnsmasq/*.plist /Library/LaunchDaemons

Then load it up!

$ sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist

The next step is to make sure outbound requests check Dnsmasq before any remote DNS servers. For this to take place you'll need to edit your Network preferences and add 127.0.0.1 above any other entires. On most networks these days your DNS will be discovered automatically which makes this a challenge. The simplest solution, I've found, it to simply use Google's public DNS servers in addition to Dnsmasq. This won't work on all networks, which is where OS X's Network profiles come in handy. I created a new profile for Dnsmasq with the following DNS server order:

127.0.0.1
8.8.8.8
8.8.4.4

The latter two are Google's DNS servers, which should work in most cases. If you run into a situation where it does not (in a cafe or an airport, for example), you can simply change the profile back to the default Automatic and proceed as normal. There are some solutions out there for customizing resolver which would preserve automatically detected DNS servers, but I've found this method to be less than bullet-proof. It's much more predictable to simply switch Network profiles.

Any time you make changes to your dnsmasq.conf file you will need to reload it. The easiest way to do this is to find the process and kill it—it will be started up again automatically. You may want to bind the below to an alias.

$ sudo kill $(ps aux | grep '[d]nsmasq' | awk '{print $2}')

That's it! You should now be able to create any arbitrary subdomains off your new TLDs and route them through your virtual machines.

This entry was posted in development and tagged development, dns, dnsmasq, wildcard