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.
| Route | What it does |
|---|---|
GET / | Returns the app name, API version, and links |
GET /health | Runs SELECT 1 against PostgreSQL |
GET /version | Returns v1 or v2, so a deploy is easy to verify |
GET /notes | Lists notes |
POST /notes | Creates 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.txtmain.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 osfrom contextlib import asynccontextmanagerfrom datetime import datetimefrom typing import Annotated, Generator
from fastapi import Depends, FastAPI, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom sqlalchemy import DateTime, Integer, String, create_engine, select, textfrom 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}
@asynccontextmanagerasync 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 rowrequirements.txt pins the dependencies:
fastapi==0.121.2uvicorn[standard]==0.40.0sqlalchemy==2.0.45psycopg[binary]==3.3.1Calling 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.
createdb notespython -m venv .venvsource .venv/bin/activatepip install -r requirements.txtexport DATABASE_URL=postgresql://localhost:5432/notesuvicorn main:app --reloadThe 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.
curl http://127.0.0.1:8000/healthcurl -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/notesOnce 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.

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:

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:
| Setting | Value |
|---|---|
| Language | Python |
| Build command | pip install -r requirements.txt |
| Start command | uvicorn main:app --host 0.0.0.0 --port 8000 |
| Port | 8000 |
| Environment variable | DATABASE_URL (marked Secret) |

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.

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

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:
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:
git add main.pygit commit -m "Add single-note endpoint"git push origin mainAuto-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.

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:

Verify the updated endpoints:
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):

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:

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 thereThis 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
| Symptom | Likely cause | Fix |
|---|---|---|
| 502 Bad Gateway | App is not listening on 0.0.0.0 or the configured port | Match the port in your start command with the Port field in service settings |
Build fails at pip install | Missing system package or incompatible Python version | Read the build log, install the missing OS package, or switch Python versions |
NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres | SQLAlchemy received a postgres:// URL | Use postgresql+psycopg://, or keep normalise_database_url() in main.py |
ModuleNotFoundError: No module named 'psycopg' | Driver missing from requirements.txt | Add psycopg[binary] to requirements.txt and redeploy |
| Database connection refused or timed out | Wrong host/port, rotated password, stopped database, or hit the connection limit | Check the Connection tab, reset the password if needed, and stay under 20 connections on Basic |
| Deploy succeeded but old code is live | Auto-deploy is off, or an earlier commit is pinned | Check the active commit SHA on the service and deploy the latest commit |
| Rollback succeeded but the app errors | The database schema moved ahead of what the older code expects | Run 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.0and the exact port configured in service settings. DATABASE_URLis stored as a Secret and kept out of Git./healthreturnsokagainst 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.