0
0
FlaskHow-ToBeginner · 4 min read

How to Deploy Flask to Heroku: Step-by-Step Guide

To deploy a Flask app to Heroku, create a Procfile to tell Heroku how to run your app, add a requirements.txt with dependencies, and use Git to push your code to Heroku. Heroku will build and run your Flask app automatically after you push.
📐

Syntax

Deploying Flask to Heroku involves these key files and commands:

  • Procfile: Defines the command to start your app, e.g., web: gunicorn app:app.
  • requirements.txt: Lists Python packages your app needs.
  • runtime.txt (optional): Specifies Python version.
  • Git commands: git init, heroku create, git push heroku main to deploy.
plaintext
Procfile
web: gunicorn app:app

requirements.txt
Flask
gunicorn

runtime.txt
python-3.11.4
💻

Example

This example shows a simple Flask app deployed to Heroku. It includes the app code, necessary files, and deployment commands.

python
# app.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Heroku!'

# Procfile
web: gunicorn app:app

# requirements.txt
Flask
gunicorn

# Deployment commands
# git init
# heroku create
# git add .
# git commit -m "Initial commit"
# git push heroku main
Output
When visiting the Heroku app URL, the browser shows: Hello, Heroku!
⚠️

Common Pitfalls

Common mistakes when deploying Flask to Heroku include:

  • Not creating a Procfile, so Heroku doesn't know how to start the app.
  • Forgetting to add gunicorn to requirements.txt, causing runtime errors.
  • Using flask run in Procfile instead of gunicorn, which is not suitable for production.
  • Not committing all files before pushing to Heroku.
plaintext
Wrong Procfile:
web: flask run

Right Procfile:
web: gunicorn app:app
📊

Quick Reference

StepCommand/FilePurpose
1git initInitialize Git repository
2heroku createCreate Heroku app
3ProcfileDefine app start command
4requirements.txtList Python dependencies
5git add . && git commit -m 'msg'Commit changes
6git push heroku mainDeploy app to Heroku
7heroku openOpen app in browser

Key Takeaways

Always create a Procfile with 'web: gunicorn app:app' to tell Heroku how to run your Flask app.
Include gunicorn in requirements.txt for production-ready server support.
Use Git to push your code to Heroku after setting up the app and files.
Avoid using 'flask run' in production; gunicorn is the recommended server.
Check that all necessary files are committed before deploying.