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 mainto deploy.
plaintext
Procfile
web: gunicorn app:app
requirements.txt
Flask
gunicorn
runtime.txt
python-3.11.4Example
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
gunicorntorequirements.txt, causing runtime errors. - Using
flask runinProcfileinstead ofgunicorn, 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
| Step | Command/File | Purpose |
|---|---|---|
| 1 | git init | Initialize Git repository |
| 2 | heroku create | Create Heroku app |
| 3 | Procfile | Define app start command |
| 4 | requirements.txt | List Python dependencies |
| 5 | git add . && git commit -m 'msg' | Commit changes |
| 6 | git push heroku main | Deploy app to Heroku |
| 7 | heroku open | Open 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.