Back to Blog Main Page

Heroku Deployment of a Flask App (No Database) Without Leaking Secret API Keys

November 07, 2018

The previous post discussed about the Flask app I created using the Austin, TX Open Data Portal. To deploy the app on Heroku without leaking API keys, I had to do some git manipulation. 💥

Supossing that you already have the heroku-cli installed in your system, and that the files that contain the API keys are .gitignored, commit all files in the application.

  1. Inside the app folder and with the virtual environment activated, login to heroku on the cli.
$ heroku login

Enter credentials.

  1. Create the app on heroku. This can be done in the cli or on the heroku dashboard on the web. On the cli, this would look like:
$ heroku apps:create niceFlaskAppName
  1. Making sure you’re on the virtual environment, pip install gunicorn. Gunicorn is a server that Heroku dyno uses to host a Heroku app.
$ pip install gunicorn
  1. Create Procfile that tells Gunicorn can use the app in the cli or in a text editor. In the cli:
$ echo 'web: gunicorn flaskAppMainFileName:app --log-file=-' > Procfile

The most confusing part of this, especially if you’re new to flask is figuring out the main file that runs the Flask app. This is found in the root folder.

  1. Create runtime.txt which specifies the version of Python used in the app.
$ echo python-3.7.0 > runtime.txt
  1. If this is the first time to use Heroku, do:
$ heroku local

Otherwise, skip this step.

  1. Create requirements.txt:
pip freeze > requirements.txt
  1. Commit everything in the folder in git.

  2. Instead of pushing to heroku at this point, create another branch. I name my branch deploy or something like that.

$ git checkout -b deploy
  1. In this branch, do:
$ git add -f pathToSecretFile
$ git commit -m 'Deploying'
$ git push --force heroku deploy:master

This will now build your app on heroku. Use heroku logs --tail to find see errors if there are any.

  1. If deployment is successful, you can open the app using:
$ heroku open

Or open the app from the Heroku dashboard on the browser.

Again, this does not account for if the app has a database. For that, Heroku Add-ons is needed to be configured.

Lastly, don’t forget to avoid merging the deploy branch into master. 🌝 Good luck!