How to deploy Flask app on Heroku

Sep 11, 2021 | - views

Create application

Create flask app

Create new file app.py

import os

from flask import Flask

PORT = int(os.environ.get('PORT', '8080'))

app = Flask(__name__)


@app.route("/")
def main():
    return "Hello, World!"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=PORT)

Create requirements.txt

Put all your dependencies to requirements.txt

Flask==2.0.1
gunicorn==20.1.0

Create entrypoint (main.bash)

Create file main.bash

#!/scripts/bash

set -e
gunicorn --bind 0.0.0.0:$PATH app:app

Create dockerfile

FROM python:3.9.6-slim
WORKDIR /opt/app

COPY requirements.txt ./requirements.txt
RUN pip install  --default-timeout=1000 --prefer-binary --no-cache-dir -r ./requirements.txt
COPY . .
USER 1001
ENTRYPOINT ["bash", "main.bash"]

Create dockerignore

.git/*

Deploy

Install heroku

sudo snap install heroku --classic
heroku login
heroku: Press any key to open up the browser to login or q to exit
 ›   Warning: If browser does not open, visit
 ›   https://cli-auth.heroku.com/auth/browser/***
heroku: Waiting for login...
Logging in... done
Logged in as me@example.com

Init git repository

git init

Deploy app to heroku

Create heroku app (limit 5 apps in free account)

heroku create

Login to heroku with cli

heroku container:login

Push docker image

heroku container:push web

Release image

heroku container:release web

Open app

heroku open

Wait app initialization