Setting /etc/hosts on an Android Emulator using a Mac

Testing sites on mobile devices is a necessity. When you find a bug that needs some loving and you want to do the code tweaks on your localhost, the Android emulator balks. It doesn’t know anything about your localhost. Luckily, you can resolve this by editing the emulator’s /system/etc/hosts/ file. Here’s what to do:

First, start your emulator setting a partition size so the emulator doesn’t throw an out of memory error:

$ emulator -avd nameOfAvd -partition-size 512

Next – in another shell window/tab – check what devices are running (so you can edit the one you want):

$ adb devices

List of devices attached
emulator-5554 device

The emulator-5554 is the device I started with the emulator command. Right now it is in read-only mode. Remount the device to make it writable

$ adb -s emulator-5554 remount

remount succeeded

Now that it is remounted, grab the hosts file and put it somewhere on your filesystem (I use the Desktop):

$ adb -s emulator-5554 pull /system/etc/hosts ~/Desktop/

6 KB/s (25 bytes in 0.003s)

Edit the ~/Desktop/hosts file as needed with the editor of your choice:

127.0.0.1        localhost
192.168.1.100    bacon.local

Finally, push that hosts file onto your emulator:

$ adb -s emulator-5554 push ~/Desktop/hosts /system/etc/hosts

45 KB/s (249 bytes in 0.005s)

BAM! The emulator can now access sites using the hosts specified in the newly edited hosts file.

Useful docs: emulator and managing AVDs