Quick Tips: Using Remote mySQL for Heroku NodeJS API

Heroku makes deploying applications effortless -- if you use their rate-limited database. Then things get a little more complicated when you want to use your own database. Just barely though.

I'll show you in a couple steps how to get your remote mySQL server connected to your Heroku app.

I decided to test out Heroku for one of our Node based apps. Our app is simple Express API that queries a remote mySQL database. It uses the node-mysql library to connect to the DB. If we're on the local environment, we connect to the localhost, if production, we use live server credentials.

Step 1 - Remote MySQL

Make sure your MySQL DB user permissions have been configured to allow for remote connections from the server you plan on connecting from (Heroku, your host, etc). You can do this fairly easily through CPanel, or use the MySQL docs.

In this case, you want to add your Heroku server to the config. In my case, it was a server hosted on AWS, so I added a wildcard style config (%.compute-1.amazonaws.com).

Step 2 - Add DB to Heroku

Run the following command line to add your remote database to the Heroku configuration file:

heroku config:add DATABASE_URL=mysql2://username:password@ip.goes.here/data_base_name --app heroku-app-name

Then you can access it in Node using process.env.DATABASE_URL. This creates a database.yml file that lets Heroku know about any remote databases.

That's it!

You should be able to deploy your application and access the remote DB now.

If you're using AWS, here's a separate guide on configuring that with Heroku.

Hope that helps!
Oscar


Keep Reading

Oscar

Oscar is an artist and engineer who's been creating cannabis brands and media experiences for over 10 years, and developing full-stack applications for over 15 years.