how to start a mysql server on login

I currently use Valet to develop sites, and many of those sites need SQL databases. To host SQL databases, I run a mariaDB server from the Terminal. In order to start the MySQL server so that I can connect to the databases, I run the command: sudo mysql.server start I want the server to start on login, so normally I would just have this command execute on login, but it requires the sudo command. What do I change and how do I change it so that I do not need the sudo part of the command and I can just start the server on login?


Solution 1:

The best way to do this is to create a launchd .plist, copy it to ~/Library/LaunchAgents and let the system handle it for you.

Sample .plist:

<?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>com.user.startMySQL</string>
        <key>ProgramArguments</key>
        <array>
          <string>mysql.server</string>
          <string>start</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
</dict>
</plist>

I prefer to use the file naming convention com.user.<name of function>.plist when naming them so I can easily identify what is loaded and what is not.

Next, you need to load this .plist as root so it runs as root

$ sudo launchctl load com.user.startMySQL.plist

To verify that it has loaded you can issue the command sudo launchctl list and the command mysql to initiate a connection to the MySQL service.

Please note that this is just a simple example - you may wish to create a script to check to see if mysqld is already running before launching it.