FastAPIPython

Deploy a FastAPI app

Run your FastAPI app in production from its own Dockerfile, with a managed database and environment variables set per environment. This guide goes from a new project to a production deploy on Modelence.

Last updated /Tested with FastAPI 0.165, Uvicorn 0.54 and Python 3.15

To deploy a FastAPI app, put it in a Dockerfile that installs your requirements and starts Uvicorn on 0.0.0.0, then host that container on a platform that keeps the process running and gives it a database. Modelence is a managed cloud on AWS that builds the image from your Dockerfile, runs it as containers in one of 17 regions next to managed MongoDB, Postgres and Redis, and deploys it with one command.

FastAPI builds APIs from Python type hints and generates request validation and interactive docs for you. This guide creates a small FastAPI app, runs it locally, connects a database, writes the Dockerfile and modelence.config.json and deploys it, and the same steps work for any Python app that runs under an ASGI server such as Uvicorn. If you already have a FastAPI app, skip to Run the app locally.

FastAPI on Modelence at a glance

How FastAPI runs
A container built from your Dockerfile runs Uvicorn as a long-running server, with no time limit on a request
Regions
17 AWS regions. The app, its databases and their backups stay in the region you pick
Databases
Managed MongoDB, Postgres and Redis in the app's region, read from environment variables and reached over TLS
Backups
Production databases are backed up at least every 6 hours, and the oldest snapshots are kept up to 12 months
Deploys
New containers take traffic only after health checks pass, and a version that keeps crashing rolls back on its own
Shutdown
SIGTERM, then SIGKILL after 30 seconds by default (up to 120), so Uvicorn can finish requests and run lifespan cleanup
Price
Free plan to start. Paid plans from $20 a month, with that $20 included as cloud usage

Before you start

  • Python 3.11 or newer, which current FastAPI releases need
  • Docker, to build and check the image on your machine before you deploy
  • Node.js, only to run the npx modelence command. The app itself doesn't use it
  • A Modelence account, which you can create for free
  • Optionally, Claude Code, Cursor or Codex, if you'd rather have your coding agent write the Dockerfile and config and run the deploy

Create a FastAPI app

Create a project with a virtual environment, then install FastAPI and Uvicorn, the server that runs it:

mkdir my-api && cd my-api
python3 -m venv .venv
source .venv/bin/activate
pip install fastapi "uvicorn[standard]"
pip freeze > requirements.txt

pip freeze writes the exact versions you installed to requirements.txt, so the image installs the same ones. Then add main.py with one route. The app object is named app, which is what main:app points to in the commands below.

main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"message": "Hello from FastAPI"}

Run the app locally

Start the development server, which restarts when a file changes:

uvicorn main:app --reload --port 8000

Open http://localhost:8000 for the route and http://localhost:8000/docs for the interactive API docs that FastAPI generates.

You can also connect the project to a Modelence local environment, so the app runs on your machine with the environment's database connection strings and variables and they never need to be copied into a .env file. npx modelence@latest setup opens the browser, where you sign in and pick or create an app and environment. A Python project has no package.json to take the development command from, so give the service a dev command in modelence.config.json, as in Describe the app in modelence.config.json:

"dev": { "commands": ["uvicorn main:app --reload --port 8000"] }

After that, start the app with npx modelence@latest dev instead of uvicorn. It runs the dev command on your machine, not in Docker, with the environment's variables, and the environment's Overview in the dashboard shows the app while it runs.

bash
npx modelence@latest setup
npx modelence@latest dev

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

For a FastAPI app, a managed MongoDB, Postgres or Redis on Modelence is a connection string in an environment variable that your Python client reads at startup. Traffic to it uses TLS, and production databases get a backup at least every six hours.

In Python that means os.environ["MONGODB_URI"] for MongoDB, and for Postgres and Redis the names you bind in modelence.config.json, usually DATABASE_URL and REDIS_URL. Pass it to the client your app already uses, such as SQLAlchemy, psycopg, PyMongo or redis-py, and create the client once when the app starts rather than on every request, so requests share its connections. FastAPI's lifespan is the place for that:

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from sqlalchemy import create_engine


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = create_engine(os.environ["DATABASE_URL"])
    yield
    app.state.db.dispose()


app = FastAPI(lifespan=lifespan)

For Postgres, add sqlalchemy and psycopg[binary] to requirements.txt. The URL has the form postgresql://...?sslmode=require, and SQLAlchemy 2.1 and newer open a postgresql:// URL with psycopg 3, so it works as it is. On SQLAlchemy 2.0, which defaults to psycopg2, change the scheme to postgresql+psycopg:// first. The Redis URL starts with rediss://, and redis.from_url connects to it over TLS as it is.

An existing Postgres on Supabase or Neon keeps working with the same SQLAlchemy code once its URL is in env with "type": "secret".

Run migrations, such as alembic upgrade head, against the environment's database before you deploy, not in the Dockerfile's CMD. Every container runs CMD when it starts, several at once during a rollout, so migrations there would run in parallel.

Postgres and Redis are declared as resources in modelence.config.json, alongside the API service, and are created by the deploy before the new version starts:

modelence.config.json
{
  "resources": {
    // "api": the app's service, as in the next steps
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "cache": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
  }
}

Write a Dockerfile

Modelence builds a Python app from its own Dockerfile, which picks the Python version, installs the dependencies and starts Uvicorn. Add it at the root of the project:

  • The base image comes from public.ecr.aws/docker/library/, a mirror of Docker Hub's official images. Docker Hub limits how often images can be pulled, so a build can fail on a plain FROM python:3.15-slim.
  • requirements.txt is copied and installed before the rest of the code, so a change to the code doesn't reinstall the dependencies.
  • Uvicorn listens on 0.0.0.0. Its default, 127.0.0.1, takes connections only from inside the container, so traffic and the health check would never reach the app.
  • CMD uses the exec form, so the stop signal reaches Uvicorn rather than a shell in front of it, and Uvicorn runs without --reload, which is for development.
  • PYTHONUNBUFFERED=1 writes the app's output straight to the logs.

Add a .dockerignore next to it, so the virtual environment and local files stay out of the build:

.git
.venv
__pycache__
.env
Dockerfile
FROM public.ecr.aws/docker/library/python:3.15-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Describe the app in modelence.config.json

Add modelence.config.json at the root of the repository and commit it with the app and the Dockerfile. dockerfile tells Modelence to build the service from your Dockerfile, ports names the port Uvicorn listens on, and dev is the command npx modelence@latest dev runs on your machine:

modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "api": {
      "type": "service",
      "dockerfile": "Dockerfile",
      "ports": [8000],
      "dev": { "commands": ["uvicorn main:app --reload --port 8000"] }
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "OPENAI_API_KEY": { "type": "secret" }
  }
}

Adjust the config for your project

  • Set the Python version in the FROM line to the one the project declares in .python-version or pyproject.toml, such as python:3.12-slim.
  • With uv or Poetry, copy the lockfile together with pyproject.toml and install from it, for example with uv sync --frozen or poetry install, then start Uvicorn from the environment they install into.
  • The container gets the first of ports as PORT. To read the port from it rather than writing it in the Dockerfile, use a shell form with exec, so the stop signal still reaches Uvicorn: CMD exec uvicorn main:app --host 0.0.0.0 --port $PORT.
  • Uvicorn runs one worker process by default. On a container size with more than one CPU, which you pick under Configure in the dashboard, add "--workers", "2" or more to CMD.
  • If the app needs system packages, such as ffmpeg or a compiler for a dependency without a prebuilt wheel, install them with apt-get in the Dockerfile before pip install.
  • Declare keys and tokens with "type": "secret" and no value, and read them with os.environ. The deploy asks you for them in the browser, and you can change them later in the dashboard under Environment variables, where every view of a secret is logged.
  • If the app lives in a subdirectory of a monorepo, such as backend/, set "root": "backend" on the service. The dockerfile path is relative to it, and the build sees only the files under it.

Check the build locally

Before the first deploy, build the image and run it with the port Modelence will give it, then check that the app answers on http://localhost:8000. A deploy runs the same build, so anything that fails here fails there too.

bash
docker build -t my-api .
docker run --rm -e PORT=8000 -p 8000:8000 my-api

Deploy

Run the deploy command in the project directory:

npx modelence@latest deploy

It opens the browser, where you sign in, pick the organization, app and environment (or create them) and enter any required variables the environment doesn't have yet, such as OPENAI_API_KEY above. Then it uploads the project, builds the image from your Dockerfile and follows the build until the app is live. You pick the AWS region the first time you deploy an environment, and its containers and databases are created there. Next time, pass --app <app> --env <env> to preselect the target.

The first deploy creates the databases in resources, starts the app once they're ready and attaches the environment's URL, <app>-<environment>.cloud.modelence.app, to port 8000 of the api service. To use your own domain, add it in the dashboard under Domains. Every app has a sandbox and a production environment, and the same files deploy to both.

Let your coding agent do it

Paste Deploy using https://modelence.com/skill.md into Claude Code, Cursor or Codex in your project. The agent reads the docs, writes the Dockerfile and modelence.config.json for your project, checks the build and runs the deploy, and it stops to ask you whenever a step needs your account.

Production readiness

Add a health check

By default Modelence counts a container as healthy once it accepts connections on its port. An HTTP check is stricter: the container has to answer a path with a 2xx status within 4 seconds, so a new version that starts but can't serve requests never takes traffic. Add a route:

@app.get("/health")
def health():
    return {"status": "ok"}

Then point the service's check at it in modelence.config.json:

"healthCheck": { "type": "http", "path": "/health" }

Redirects are followed, so keep the route outside any dependency or middleware that redirects or rejects signed-out requests. Failed checks don't count for the first 60 seconds after a container starts. If the app loads a model or warms a cache before it listens, give it longer with "gracePeriod": 180, up to 300 seconds.

Shut down cleanly

When a container stops, for example during a deploy, the process gets SIGTERM, and SIGKILL follows 30 seconds later. Uvicorn handles SIGTERM by finishing the requests in progress and then running the part of lifespan after yield, so close database clients and flush anything buffered there. That depends on the exec form of CMD in the Dockerfile, which delivers the signal to Uvicorn itself.

If some requests run longer, such as calls to a slow model, raise stopTimeout on the service, up to 120 seconds, so they finish before the container is killed.

Keep state out of the container

A container's disk is wiped on every deploy, so keep data in Postgres or MongoDB rather than a SQLite file, and stream UploadFile contents to object storage instead of saving them next to the code. Caches such as functools.lru_cache live in one Uvicorn worker of one container, which is fine for derived data but not for anything that must be the same everywhere. Use Redis for that and for sessions.

With state out of the process, two or more containers under Configure keep the API up when one crashes or a zone goes down. See Availability for how rollouts and rollbacks behave.

Run background jobs as their own service

Don't run a queue consumer or a scheduler, such as a Celery worker or an APScheduler job, inside the API process. With several containers, each one would run every job, and emails or charges would go out twice. FastAPI's BackgroundTasks suit short work tied to one request, such as sending an email after the response. For anything else, add a second service built from the same Dockerfile, with start in place of its CMD:

"worker": {
  "type": "service",
  "dockerfile": "Dockerfile",
  "start": { "commands": ["celery -A tasks worker"] },
  "healthCheck": { "type": "none" },
  "rollout": "recreate"
}

The worker listens on no port, so it has no health check, and "rollout": "recreate" stops the old worker before the new one starts. Keep it on one container if its jobs must not run twice, or have each job take a lock in the database. Multiple services has the details.

Watch logs and metrics

Logs need no setup. Everything the app writes to its output, including print, the logging module and Uvicorn's access log, shows on the environment's Logs page, and PYTHONUNBUFFERED=1 in the Dockerfile makes each line show up at once.

For traces and metrics, add a telemetry resource and tie the standard OpenTelemetry variables to it, as in Deploy setup. In Python, add opentelemetry-distro and opentelemetry-exporter-otlp-proto-http to requirements.txt, run opentelemetry-bootstrap -a install in the Dockerfile after pip install, set OTEL_EXPORTER_OTLP_PROTOCOL to http/protobuf in env and put opentelemetry-instrument in front of uvicorn in CMD. Requests and database calls are then traced without code changes.

Modelence vs Vercel, Railway and Render for FastAPI

FastAPI runs anywhere that keeps a Python process up, so the platforms differ mostly in how they run that process and where the database lives. The limits and prices below come from each platform's own docs and pricing pages as of November 2026.

How FastAPI runsDatabasesRegionsPricing modelBest for
ModelenceA container from your Dockerfile, with Uvicorn as a long-running serverManaged MongoDB, Postgres and Redis in the app's region, backed up at least every 6 hours17 AWS regionsFree plan, then from $20 a month with that amount included as usage and no per-seat chargeAPIs with long requests, WebSockets or workers that need the database in the same region
VercelThe whole app becomes one Vercel Function, and a request runs up to 300 seconds by default or 800 on ProMarketplace providers such as Neon, Upstash and SupabaseOne function region by default (Washington, D.C.), more on ProHobby is free, Pro is $20 a month per developer seat with $20 of usage creditA small API next to a frontend already on Vercel, with short requests
RailwayA container built from your repo, or from your Dockerfile when it finds onePostgres, MySQL, Redis and MongoDB from templates, with backups you turn on4: California, Virginia, Amsterdam and SingaporeHobby $5 a month or Pro $20 per workspace, each including that much usage, billed by the secondGetting an API up quickly, and services that sit idle much of the day
RenderNative Python runtime with uvicorn main:app --host 0.0.0.0 --port $PORT, or a DockerfileRender Postgres and Render Key Value, which is Redis-compatible5: Oregon, Ohio, Virginia, Frankfurt and SingaporeWorkspace plan (Hobby free, Pro $25 a month) plus a fixed price per instance from $7 a month. Free instances spin down after 15 idle minutesSteady APIs at a predictable monthly price, without writing a Dockerfile

Vercel is a good fit when the API is small, its requests finish in seconds and the frontend already lives there, because one project then holds both. Render's native Python runtime is the simplest way to run FastAPI at a fixed monthly price without a Dockerfile, and Railway is quick to start on and cheap for services that are idle most of the day. Modelence fits an API that holds long requests or WebSocket connections, runs workers next to it, or needs its data in a region Railway and Render don't offer, such as London, Tokyo or São Paulo. For more detail, see Modelence vs Vercel, Railway vs Render and moving from Railway.

Next steps

Frequently asked questions

How do I deploy a FastAPI app to production?

Run it under a production ASGI server such as Uvicorn, bound to 0.0.0.0 and without --reload, on a platform that keeps that process running. On Modelence you add a Dockerfile that installs requirements.txt and starts Uvicorn, describe the service and its database in modelence.config.json and run npx modelence@latest deploy, which builds the image and runs it as containers on AWS.

Can I deploy FastAPI on Vercel?

Yes, Vercel runs a FastAPI app as a single Vercel Function on its Python runtime. A request can run for 300 seconds by default and 800 seconds at most on Pro, and WebSocket connections close when the function reaches its maximum duration. An API with long requests, persistent connections or background workers fits better on a platform that runs Uvicorn as a long-running server, such as Modelence.

Do I need Docker to deploy a FastAPI app?

You need a Dockerfile, but not Docker on your machine, because Modelence builds the image from your Dockerfile during the deploy. The Dockerfile also picks the Python version, for example public.ecr.aws/docker/library/python:3.15-slim, ideally matching .python-version or pyproject.toml. With Docker installed you can build and run the image locally first, which catches most build problems before a deploy.

Should I run FastAPI with Uvicorn or Gunicorn?

Uvicorn on its own is enough for most apps, and its --workers option runs several processes in one container. Gunicorn adds process management on top, using workers from the uvicorn-worker package, which replaces the deprecated uvicorn.workers module: gunicorn -k uvicorn_worker.UvicornWorker main:app --bind 0.0.0.0:8000. Leave out --reload and fastapi dev in production, since they are development tools.

Do I need Nginx in front of FastAPI?

No, not on Modelence, which serves the app over HTTPS with TLS 1.2 or later, redirects plain HTTP to HTTPS and routes requests to the port Uvicorn listens on. The container runs Uvicorn and nothing else. Nginx is still useful on a server you run yourself, where nothing else terminates TLS.

Which database should I use with FastAPI on Modelence?

Use the one your app is built for, since Modelence runs managed MongoDB, Postgres and Redis in your app's region. Each connection string reaches the app as an environment variable, such as DATABASE_URL, which SQLAlchemy, PyMongo or redis-py read at startup. A database hosted elsewhere, such as Supabase or Neon, keeps working when you declare its URL as a secret.

How do I run background tasks or Celery workers with FastAPI?

Use FastAPI's BackgroundTasks only for short work tied to one request, and run Celery or any other queue consumer as a second service. In modelence.config.json that service is built from the same Dockerfile, with start set to the worker command, no health check and "rollout": "recreate", so two versions never take the same jobs. Keeping the worker out of the API process matters because with several API containers each one would run every job.

Can I deploy a FastAPI backend with a React or Next.js frontend?

Yes, as two services in the same modelence.config.json on a paid plan: the frontend as a Node.js service and the FastAPI app built from its Dockerfile. A frontend server can call the API over the environment's private network through a variable tied to the API service. If the browser calls the API directly, give the API its own hostname under Domains and allow the frontend's origin with FastAPI's CORSMiddleware.

Can I use my own domain?

Yes, add it in the dashboard under Domains and attach it to the service that serves the FastAPI app. Paid plans include unlimited custom domains, and traffic to them is served over HTTPS.

How much does it cost to host a FastAPI app on Modelence?

You can start on the free plan, which runs one instance that sleeps when idle. Paid plans start at $20 a month with the same amount included as cloud usage, and you pay only for usage above that. Managed Postgres and Redis and a second service, such as a Celery worker, need a paid plan.

Deploy other stacks

Deploy your FastAPI app

Start on the free plan and move up when your app needs more.

Or paste this into your coding agent