Guide to Deploying a Flask app on Heroku

Heroku is a popular application deployment platform with a functional free tier of services, and Flask is populalar application development micro-framework in Python. The Heroku-Flask environment is one of the quickest ways to deploy a small application for testing, yet sadly, I did not find a single tutorial that covered all aspects of the deployment process without leaving room for a whole bunch of errors.

Hence, this guide.

Note that this is not a guide to Flask and Flask based development and is focused specifically on deployment of your flask application. There are excellent resources online for learning development Flask, which would get you started in a day, so refer to that if you need to get going in Flask, before learning to deploy your projects online — here.

Setup Environment and Git

mkdir flask-deployment
cd flask-deployment
pipenv install flask gunicorn

Run the following in root (flask-deployment) to setup git:

git init
git add .
git commit -m “Initial Commit”

Setup Heroku

Once you’re done with these installations and sign-up, run the following commands to setup Heroku in the created folder flask-deployment:

Code to login and create a new app

heroku login
heroku create my-first-app

Code to push initial commit to heroku

git push heroku master

Once you’re done with this, move forward to working on your app.

The App

Nomenclature

  • your application is inside the app folder, i.e., it’s path is flask-deployment/app/main.py
  • your app is named main.py
  • your app is named app, as in app = Flask(name) — default naming.

Additional Files

Create the following files in the root folder (flask-deployment):

wsgi.py

from app.main import appif __name__ == “__main__”:
app.run()

NOTE: Ensure that the nomenclature specified earlier is followed.

runtime.txt

python-3.7.5

Procfile

web: gunicorn wsgi:app

requirements.txt

pip freeze > requirements.txt

NOTE: Ensure that this requirement file also contains gunicorn, if it doesn’t, add gunicorn to the last line of requirements.txt manually.

Deployment and Managing Dynos

Pushing code files to Heroku

git add .
git commit -m “Code files”
git push heroku master

Ensuring that a web dyno is running for deployment:

heroku ps:scale web=1

Additionally, you can check if your app is working correctly by running the following in your project’s root folder:

heroku local web

Tip on Database

And that’s it!

Your application will be live on Heroku after this. If you face any issues or have any doubts, feel free to reach out to me at vivek.kaushal@outlook.com.

Cheers!

Hacker | Building Enterpret | ex-Samsung, IIIT-H | vivekkaushal.com