logo

Deploying a Python App with PostgreSQL on Heroku

O

Ohidur Rahman Bappy

MAR 22, 2025

Deploying a Python App with PostgreSQL on Heroku

Learn the steps to create a PostgreSQL database and deploy a Python application to Heroku.

Prerequisites

  • Python environment with pip or pipenv
  • Heroku account

Step 1: Install Gunicorn

First, you need to install Gunicorn, a Python WSGI HTTP Server for UNIX:

pipenv install gunicorn
# or
pip install gunicorn

Step 2: Install Heroku CLI

Install the Heroku CLI from Heroku's official documentation.

Step 3: Login via Heroku CLI

heroku login

Step 4: Create a Heroku App

heroku create appname

Step 5: Set Up PostgreSQL Database

Create a PostgreSQL database on your Heroku app:

heroku addons:create heroku-postgresql:hobby-dev --app appname

Step 6: Configure Database URI

Retrieve the database URI:

heroku config --app appname

Step 7: Create a Procfile

Create a Procfile to define your application's process type:

touch Procfile
# Add the following line
echo "web: gunicorn app:app" >> Procfile

Step 8: Generate requirements.txt

List your project dependencies:

pip freeze > requirements.txt

Step 9: Specify the Python Runtime

Create a runtime.txt file to specify the Python version:

touch runtime.txt
# Add the Python version
echo "python-3.7.2" > runtime.txt

Step 10: Deploy Using Git

Initialize git, add files, and deploy to Heroku:

git init
git add .
git commit -m 'Initial Heroku deployment'
heroku git:remote -a appname
git push heroku master

Step 11: Initialize Database Tables

Run the following commands to create tables in your database:

heroku run python
>>> from app import db
>>> db.create_all()
>>> exit()

Step 12: Open Your App

Access your deployed application:

heroku open

Congratulations! Your Python application with PostgreSQL is now deployed on Heroku.