Autostart MySQL, PHP-FPM, and nginx on OS X Lion

In my last post, I wrote about my adventure setting up a local WordPress OS X nginx MySQL PHP web server on a Mac. You can use launchd to automatically start MySQL, PHP-FPM, and nginx on OS X. Create and install plist files in ~/Library/LaunchAgents to run programs at startup on a per-user basis or /System/Library/LaunchDaemons to start a daemon as root.

Use vi ~/Library/LaunchAgents/org.mysql.mysqld.plist to save a MySQL plist file:

<?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>Label</key><string>mysql</string>
<key>Program</key><string>/usr/local/mysql/bin/mysqld_safe</string>
<key>KeepAlive</key><true/>
</dict>
</plist>

Use vi ~/Library/LaunchAgents/org.php.php-fpm.plist to save a PHP-FPM plist file:

<?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>Label</key><string>php-fpm</string>
<key>Program</key><string>/usr/local/sbin/php-fpm</string>
<key>KeepAlive</key><true/>
</dict>
</plist>

Use sudo vi /Library/LaunchDaemons/org.nginx.nginx.plist to save an nginx plist file:

<?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>Label</key><string>nginx</string>
<key>Program</key><string>/usr/local/sbin/nginx</string>
<key>KeepAlive</key><true/>
</dict>
</plist>

Run the following commands to load the services for the first time:

launchctl load -w ~/Library/LaunchAgents/org.mysql.mysqld.plist
launchctl load -w ~/Library/LaunchAgents/org.php.php-fpm.plist
sudo launchctl load -w /Library/LaunchDaemons/org.nginx.nginx.plist

Run the following to check to see if the services are all running:

ps aux | grep mysql
ps aux | grep fpm
ps aux | grep nginx

Run the following to unload the services so they don’t keep autostarting again:

launchctl unload -w ~/Library/LaunchAgents/org.mysql.mysqld.plist
launchctl unload -w ~/Library/LaunchAgents/org.php.php-fpm.plist
sudo launchctl unload -w /Library/LaunchDaemons/org.nginx.nginx.plist

Run the following to stop the services:

msyql stop
sudo kill -SIGQUIT $( cat /usr/local/var/run/php-fpm.pid )
sudo kill -QUIT $( cat /usr/local/nginx/logs/nginx.pid )

Refer to man launchd.plist for more launchd parameters.