Add a local Port Forward in OSX

If you like to put various Services into Virtual Machines for development like i do (or use vagrant and get your dependencies installed in a VM) you might want to still connect to localhost to use those services. Or your development machine has its default on localhost.

Sadly the Firewall Configuration with pfctl which is mentioned in some Blogs didnt work on my Macbook with Parallels. Doesnt like to forward onto another interface probably.

But the OSX launchd has a nice feature to simulate the behaviour of a inetd service. This means that we can use launchd to listen on a port and take action if a process connects to it…. Like forward it to another host.

The following Example works for a virtualized mysql host, but you can easily adapt it to other Ports and Services.

Put this config file into /System/Library/LaunchDaemons and name it mysql.plist.
It forwards a connection to localhost Port 3306 to a host named mysql and also port 3306.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
     <key>Enabled</key>
     <true/>
     <key>Label</key>
     <string>com.demo.mysqlforward</string>
     <key>Program</key>
     <string>/usr/bin/nc</string>
     <key>ProgramArguments</key>
     <array>
          <string>/usr/bin/nc</string>
          <string>mysql</string>
          <string>3306</string>
     </array>
     <key>Sockets</key>
     <dict>
          <key>Listeners</key>
          <dict>
               <key>SockServiceName</key>
               <string>mysql</string>
               <key>Bonjour</key>
               <array>
                    <string>mysql</string>
               </array>
          </dict>
     </dict>
     <key>inetdCompatibility</key>
     <dict>
          <key>Wait</key>
          <false/>
     </dict>
     <key>POSIXSpawnType</key>
     <string>Interactive</string>
</dict>
</plist>

to enable the service use the launchd control programm:

sudo launchctl load mysql.plist
sudo launchctl start com.demo.mysqlforward

if you forward a custom service you might have to edit your /etc/services and add it (e.g. mongod)