Overview
How to Deploy a Python App from GitHub with PostgreSQL

How to Deploy a Python App from GitHub with PostgreSQL

Getting a first build online is straightforward. Things get interesting on the second deploy, when you push new code, keep your database secret working, and need a way to undo a broken release.

In this guide, you will deploy a FastAPI app from GitHub with a managed PostgreSQL database on Seenode, push a code update with auto-deploy enabled, and roll back to an earlier commit.

Quick answer

Create a Basic PostgreSQL database, copy its connection URI into a secret DATABASE_URL environment variable, configure the build command, start command, and port, and deploy from GitHub. Later pushes trigger a fresh build, and rolling back redeploys an older commit without touching your database.

All the code is in GeoSegun/example-fastapi-postgres. Fork or clone it to follow along.

What the example app does

The example is a small notes API backed by one PostgreSQL table, with health and version endpoints so you can verify each deploy.

RouteWhat it does
GET /Returns the app name, API version, and links
GET /healthRuns SELECT 1 against PostgreSQL
GET /versionReturns v1 or v2, so a deploy is easy to verify
GET /notesLists notes
POST /notesCreates a note
GET /notes/{id}Added in v2; returns one note or 404

Everything lives in a small repository:

example-fastapi-postgres/
├── .env.example
├── .gitignore
├── CHANGELOG.md
├── README.md
├── main.py
└── requirements.txt

main.py reads DATABASE_URL, creates the notes table on startup, and defines the routes. This is the v2 code; the v1 commit you deploy first omits GET /notes/{note_id} and sets APP_VERSION = "v1".

import os
from contextlib import asynccontextmanager
from datetime import datetime
from typing import Annotated, Generator
from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import DateTime, Integer, String, create_engine, select, text
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
def normalise_database_url(url: str) -> str:
"""Turn the postgres:// URI from the dashboard into a SQLAlchemy URL."""
if url.startswith("postgres://"):
return url.replace("postgres://", "postgresql+psycopg://", 1)
if url.startswith("postgresql://"):
return url.replace("postgresql://", "postgresql+psycopg://", 1)
return url
APP_VERSION = "v2"
DATABASE_URL = normalise_database_url(os.environ["DATABASE_URL"])
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
class Note(Base):
__tablename__ = "notes"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
body: Mapped[str] = mapped_column(String(500))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=text("now()")
)
class NoteIn(BaseModel):
body: str = Field(min_length=1, max_length=500)
class NoteOut(NoteIn):
id: int
created_at: datetime
model_config = {"from_attributes": True}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Demo shortcut. Use a migration tool such as Alembic once the schema changes.
Base.metadata.create_all(engine)
yield
app = FastAPI(title="Notes API", lifespan=lifespan)
@app.get("/")
def root():
return {
"name": "Notes API",
"docs": "/docs",
"health": "/health",
"version": APP_VERSION,
}
def get_session() -> Generator[Session, None, None]:
with SessionLocal() as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
@app.get("/health")
def health(session: SessionDep):
session.execute(text("select 1"))
return {"status": "ok"}
@app.get("/version")
def version():
return {"version": APP_VERSION}
@app.get("/notes", response_model=list[NoteOut])
def list_notes(session: SessionDep):
return session.scalars(select(Note).order_by(Note.id)).all()
@app.get("/notes/{note_id}", response_model=NoteOut)
def get_note(note_id: int, session: SessionDep):
note = session.get(Note, note_id)
if note is None:
raise HTTPException(status_code=404, detail="Note not found")
return note
@app.post("/notes", response_model=NoteOut, status_code=201)
def create_note(note: NoteIn, session: SessionDep):
row = Note(body=note.body)
session.add(row)
session.commit()
session.refresh(row)
return row

requirements.txt pins the dependencies:

fastapi==0.121.2
uvicorn[standard]==0.40.0
sqlalchemy==2.0.45
psycopg[binary]==3.3.1

Calling Base.metadata.create_all() on startup works fine for an initial deploy, though once your schema starts changing you should switch to a migration tool like Alembic so every change is versioned and reviewable.

Run it locally first

You need Python 3.12+ and a local PostgreSQL instance.

Terminal window
createdb notes
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
export DATABASE_URL=postgresql://localhost:5432/notes
uvicorn main:app --reload

The API runs at http://127.0.0.1:8000, with interactive docs at /docs. Adjust the username in DATABASE_URL if your local PostgreSQL does not match your OS user.

Terminal window
curl http://127.0.0.1:8000/health
curl -X POST http://127.0.0.1:8000/notes \
-H 'content-type: application/json' \
-d '{"body":"first note"}'
curl http://127.0.0.1:8000/notes

Once those requests succeed locally, you are ready to set up the database and web service on Seenode.

Step 1: Create the PostgreSQL database

In the Seenode dashboard, open Database and click Create database. Name it notes-demo, choose PostgreSQL, and leave the default version selected. New databases default to the Basic plan.

Creating a Basic PostgreSQL database

The Basic plan costs $4/month and includes 1 GB of storage, 20 connections, and seven retained backups. Seenode’s seven-day trial covers one Basic web service and one Basic database with no credit card required.

Once the database is ready, open its Connection tab to view the host, port, database name, username, and connection URI:

The database Connection tab with the URI format selected

Watch the password placeholder in that URI: the dashboard displays <password> instead of the real value, and copying the URI can copy the placeholder text. If yours still says <password>, click Reset password on the same tab, copy the new password while it is shown, and paste it into the URI. URL-encode characters like @, :, /, or # if the password includes them.

Seenode does not auto-link database credentials in the dashboard, so you will paste this URI into your web service’s environment variables as DATABASE_URL in the next step. Keep the URI out of Git (the repo’s .gitignore already excludes .env).

Step 2: Create the web service from GitHub

In the dashboard, open Web and click Create web service. Select Git repository, connect GitHub if prompted, and pick example-fastapi-postgres. Leave the branch on main.

For the first deploy, open Git commit and pick the earlier commit, Notes API: FastAPI and PostgreSQL (acbc436). Starting on v1 lets you walk through an update to v2 and a rollback afterwards.

Set these options:

SettingValue
LanguagePython
Build commandpip install -r requirements.txt
Start commanduvicorn main:app --host 0.0.0.0 --port 8000
Port8000
Environment variableDATABASE_URL (marked Secret)

The build command, start command, and port for the web service

Seenode’s load balancer forwards HTTP and HTTPS traffic to whatever container port you enter here, so your app has to bind to 0.0.0.0 on that exact port. If Uvicorn listens on 127.0.0.1 or a different port, the build still passes while every public request returns a 502. Bind directly to the configured port instead of relying on a PORT environment variable.

Add DATABASE_URL under Environment variables, paste the connection URI, and check Secret.

DATABASE_URL stored as a secret environment variable

Create the instance. The first build installs dependencies, starts Uvicorn, and brings the service online:

The first deployment completing in the Logs tab

The logs show cloning, checkout, pip install, and Uvicorn starting up. If setup fails, check the Build logs; if the build passes but the URL fails to answer, switch to Runtime logs.

Once the status turns live, test the public URL:

Terminal window
curl https://your-app.seenode.app/health
# {"status":"ok"}
curl https://your-app.seenode.app/version
# {"version":"v1"}
curl -X POST https://your-app.seenode.app/notes \
-H 'content-type: application/json' \
-d '{"body":"deployed from GitHub"}'
# {"body":"deployed from GitHub","id":1,"created_at":"..."}
curl https://your-app.seenode.app/notes
# [{"body":"deployed from GitHub","id":1,"created_at":"..."}]

If /health returns ok and /notes returns the note you just posted, the app is talking to PostgreSQL through your secret.

Step 3: Ship an update

Next, ship v2 by adding a single-note endpoint and bumping APP_VERSION:

APP_VERSION = "v1"
APP_VERSION = "v2"
@app.get("/notes/{note_id}", response_model=NoteOut)
def get_note(note_id: int, session: SessionDep):
note = session.get(Note, note_id)
if note is None:
raise HTTPException(status_code=404, detail="Note not found")
return note
@app.post("/notes", response_model=NoteOut, status_code=201)

Commit and push the change:

Terminal window
git add main.py
git commit -m "Add single-note endpoint"
git push origin main

Auto-deploy is off by default. You can deploy the update in two ways:

  • Open Deploy and click Deploy latest commit after pushing.
  • Open Settings and enable Auto deploy so every push to the tracked branch builds automatically.

Auto deploy enabled in the service settings

With auto-deploy turned on, pushing to main kicks off a new build right away. Once it goes live, the service’s active commit updates to the new SHA and requests to the new route show up in the runtime logs:

The v2 deployment and live requests in the Logs tab

Verify the updated endpoints:

Terminal window
curl https://your-app.seenode.app/version
# {"version":"v2"}
curl https://your-app.seenode.app/notes/1
# {"body":"deployed from GitHub","id":1,"created_at":"..."}

Changing an environment variable later only restarts the app with the current image. It does not pull new code or run a Git build, so code changes always need a deploy or auto-deploy.

Step 4: Roll back a bad release

Rolling back redeploys an earlier commit from the same branch. Your application code reverts, while your PostgreSQL database stays as it is.

Open Deploy, select Deploy specific commit, and pick the v1 commit (acbc436):

Choosing an earlier commit to deploy

Seenode rebuilds the v1 image and switches traffic back to it. /version returns v1, the v2 route returns 404, and the notes you created earlier stay in PostgreSQL:

The previous commit live again after a rollback

Terminal window
curl https://your-app.seenode.app/version
# {"version":"v1"}
curl -o /dev/null -s -w "%{http_code}\n" https://your-app.seenode.app/notes/1
# 404
curl https://your-app.seenode.app/notes
# existing notes are still there

This rollback is safe because v2 only added a route. If a release drops or renames a column, redeploying older code will fail against the updated schema. For destructive schema changes, pair the rollback with a down migration or restore a database backup.

If a process hangs and you do not need to change code, use Restart service instead. It restarts the running container from the current image without pulling from Git or rebuilding.

Troubleshooting the common failures

SymptomLikely causeFix
502 Bad GatewayApp is not listening on 0.0.0.0 or the configured portMatch the port in your start command with the Port field in service settings
Build fails at pip installMissing system package or incompatible Python versionRead the build log, install the missing OS package, or switch Python versions
NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgresSQLAlchemy received a postgres:// URLUse postgresql+psycopg://, or keep normalise_database_url() in main.py
ModuleNotFoundError: No module named 'psycopg'Driver missing from requirements.txtAdd psycopg[binary] to requirements.txt and redeploy
Database connection refused or timed outWrong host/port, rotated password, stopped database, or hit the connection limitCheck the Connection tab, reset the password if needed, and stay under 20 connections on Basic
Deploy succeeded but old code is liveAuto-deploy is off, or an earlier commit is pinnedCheck the active commit SHA on the service and deploy the latest commit
Rollback succeeded but the app errorsThe database schema moved ahead of what the older code expectsRun a down migration or restore a database backup

Check both log tabs when debugging. A passing build log confirms the image compiled, while runtime logs show whether Uvicorn started and accepted requests.

What it costs

  • Basic web service: $4/month (0.5 GB RAM, 0.25 vCPU)
  • Basic PostgreSQL: $4/month (1 GB storage, 20 connections, seven retained backups)
  • Total for this setup: $8/month

The seven-day trial includes one Basic web service and one Basic database. Static sites are free, persistent storage is $0.50/GB/month, credits do not expire, and bandwidth does not change the monthly tier price. Check the pricing page for current rates.

Deploy checklist

Before you call the deployment done:

  • The app listens on 0.0.0.0 and the exact port configured in service settings.
  • DATABASE_URL is stored as a Secret and kept out of Git.
  • /health returns ok against your PostgreSQL database.
  • Creating and reading a note works on the public URL.
  • The active commit SHA matches the commit you expect.
  • You have verified an update deploy after the initial build.
  • You know whether a code rollback is safe for your current database schema.

You can grab the full source from GeoSegun/example-fastapi-postgres. Fork it, tweak the notes model, and run through an update and rollback before connecting a production repo.