I was suddenly in the need of deploying a very basic Flask API to the cloud, so it can be available to the public.
The thing is, Flask is not made for a production and scalable environment, but if you only need to deploy a very basic web server to Heroku then this guide is for you.
First of all we will need to set up a virtual enviroment with Pipenv, a Flask app, and initialize a repository.
# create a new folder where we'll initialize our repo.
Open app.py and create a very simplistic app that returns a json string to see if it can be run with gunicorn:
Heroku will use Gunicorn to act as a web server for our Flask app, we have already installed gunicorn with pipenv, we have to run it with our flask app to make sure it works.
pipenv run gunicorn app:app
It seems that it works flawlessly, let’s visit our project’s home page.
And it is working as it should. Now we have to deploy our project with Heroku.
To deploy our project we will need to edit two files:
A Procfile will be used to let Heroku know how to handle our web server.
web: gunicorn app:app
By default gunicorn bind the service on port 8000, if we wanted to change this port we could do so by appending the argument
--bind ip_address:port. We can also pass environment variables in case that Heroku have a specific port.
web: gunicorn app:app --bind 0.0.0.0:$PORT
Now let’s open runtime.txt, this file let Heroku know what version of python are we using.
We’re letting Heroku know that we’re using Python 3.6.5 (which at the time is the latest and stable one).
Once we have defined our runtime, we should commit our changes.
# add files
Once we have a working directory tree, we should be able to create a Heroku app and push our project.
# create a heroku app, you can leave name_here empty
And we’re done, we can visit our app by executing
heroku open, it will open a browser tab with your app’s domain name.
I wrote an example repository that already have a runtime and Procfile so you can deploy your flask project to Heroku, here’s the repo.
If you have any questions, feel free to comment bellow. Have fun.