Search code examples
mysqlherokusqlalchemy

heroku cannot connect to MySQL server


I am using flask-sqlalchemy to connect to mysql

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''@127.0.0.1/pharmbase'

While this works fine locally, heroku cannot connect to MySQL server when deployed. Below is a trackback message

2021-01-19T15:36:19.137152+00:00 app[web.1]: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)")

Please any solution on how to solve this


Solution

  • 127.0.0.1 as an IP address means "this machine". More formally, it's the loopback interface. On your laptop you have a MySQL server running. Your heroku dyno does not, so your connection attempt fails.

    You won't be able to connect from your program running on your heroku dyno to your laptop's MySQL server without some network configuration work on your office or home router / firewall. But to begin doing that work you'll need to come up to speed on networking. (Teaching you how is beyond the scope of a Stack Overflow answer.)

    You can add a MySQL add-on to your Heroku app from a third party. Heroku themselves offer a postgreSQL add-on with a free tier, but not MySql. For US$10 per month you can subscribe to one of these MySQL add-ons and you'll be up and running.