FlaskPython

Deploy a Flask app

Run Flask in production with Gunicorn in a container built from your Dockerfile, an app factory, managed PostgreSQL with Flask-Migrate and an RQ worker on Redis. This guide takes a new project to a production deploy on Modelence.

Last updated /Tested with Flask 3.1.3, Gunicorn 27.0.1, Flask-Migrate 4.1.0, RQ 3.0.1 and Python 3.12.3

To deploy a Flask app, serve it with Gunicorn rather than flask run, bind it to 0.0.0.0 on the port the platform gives the container, and read its secret key and database URL from environment variables. Modelence is a managed cloud on AWS that builds the app from your Dockerfile, runs it as containers in one of 17 regions next to managed MongoDB, PostgreSQL and Redis, and deploys it with one command.

Flask leaves the structure of an app to you, so getting it ready for production comes down to a few choices: an app factory that Gunicorn can call, Flask-SQLAlchemy and Flask-Migrate for the database, ProxyFix so Flask knows a request arrived over HTTPS, and a separate worker for slow jobs. This guide builds a small notes app with all four, writes the Dockerfile and modelence.config.json and deploys it. If you already have a Flask app, skip to Run it under Gunicorn.

Flask on Modelence at a glance

How Flask runs
Gunicorn calls the app factory and runs 2 worker processes with 4 threads each, in a container built from your Dockerfile
Port and HTTPS
Gunicorn binds to 0.0.0.0 on the service's port, and ProxyFix reads X-Forwarded-Proto and X-Forwarded-For from the load balancer
Databases
Managed MongoDB, PostgreSQL and Redis in the app's region. Flask-SQLAlchemy reads PostgreSQL from DATABASE_URL
Migrations
flask db upgrade from Flask-Migrate runs against the environment's database before each deploy
Background jobs
An RQ worker runs as a second service from the same image, with managed Redis as its queue
Regions and backups
17 AWS regions, with production databases backed up at least every 6 hours in the region you pick
Price
Free plan to start. PostgreSQL, Redis and a worker need a paid plan, from $20 a month with $20 of usage included

Before you start

  • Python 3.10 or newer, which Gunicorn 27 needs. This guide uses 3.12
  • Docker, optionally, to build and run 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. The PostgreSQL database, Redis and RQ worker in this guide need a paid plan
  • 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 Flask project with an app factory

Create a virtual environment and install Flask together with the packages a production app needs:

mkdir notes-app && cd notes-app
python3 -m venv .venv
source .venv/bin/activate
pip install flask gunicorn flask-sqlalchemy flask-migrate "psycopg[binary]" rq
pip freeze > requirements.txt

Gunicorn is the production server, Flask-SQLAlchemy and Flask-Migrate handle the models and their migrations, psycopg is the PostgreSQL driver and RQ runs jobs from a Redis queue. pip freeze pins the installed versions in requirements.txt, so the image gets the same ones.

Put the app in a package called notes and build it in a factory function, create_app(), in notes/__init__.py. Gunicorn, the flask command and the RQ worker each call it to get a configured app, and nothing connects to a database at import time:

  • SQLALCHEMY_DATABASE_URI comes from DATABASE_URL, with a SQLite file as the fallback on your machine.
  • from_prefixed_env() loads every variable that starts with FLASK_ into the config, so FLASK_SECRET_KEY sets SECRET_KEY. Values that parse as JSON are converted, which makes FLASK_SESSION_COOKIE_SECURE=true a real boolean.
  • ProxyFix is explained under Production readiness.
notes/__init__.py
import os

from flask import Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from werkzeug.middleware.proxy_fix import ProxyFix

db = SQLAlchemy()
migrate = Migrate()


def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///notes.db")
    app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_pre_ping": True}
    # FLASK_SECRET_KEY becomes SECRET_KEY, and so on for every FLASK_ variable.
    app.config.from_prefixed_env()

    # One proxy in front: Modelence's load balancer, which terminates HTTPS.
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)

    db.init_app(app)
    migrate.init_app(app, db)

    from . import views

    app.register_blueprint(views.bp)
    return app

Add a model, routes and a job

The app stores notes in the database, and each new note queues a job:

# notes/models.py
from datetime import datetime, timezone

from . import db


class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(200), nullable=False)
    created = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
# notes/tasks.py
import os

from redis import Redis
from rq import Queue


def note_added(note_id):
    from . import create_app, db
    from .models import Note

    with create_app().app_context():
        note = db.session.get(Note, note_id)
        print(f"Note {note.id} added: {note.text}", flush=True)


def enqueue(func, *args):
    # Without Redis on your machine, run the job inline.
    if "REDIS_URL" not in os.environ:
        return func(*args)
    Queue(connection=Redis.from_url(os.environ["REDIS_URL"])).enqueue(func, *args)

The job builds its own app with create_app(), because it runs in the worker process, where no request is active. The page is a form in notes/templates/index.html that loads {{ url_for('static', filename='style.css') }} from notes/static/, so after a deploy you can see at once whether static files load. The routes live in a blueprint, and /health answers without touching the database:

notes/views.py
from flask import Blueprint, redirect, render_template, request, url_for

from . import db
from .models import Note
from .tasks import enqueue, note_added

bp = Blueprint("notes", __name__)


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


@bp.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        note = Note(text=request.form["text"])
        db.session.add(note)
        db.session.commit()
        enqueue(note_added, note.id)
        return redirect(url_for("notes.index"))
    notes = db.session.scalars(db.select(Note).order_by(Note.created.desc()).limit(20))
    return render_template("index.html", notes=notes)

Run the app locally

Create the migrations folder and the first migration, apply it, and start the development server:

flask --app notes db init
flask --app notes db migrate -m "notes table"
flask --app notes db upgrade
flask --app notes run --debug --port 8000

Without DATABASE_URL the tables go into instance/notes.db, and without REDIS_URL the job runs inline. Open http://localhost:8000, add a note, and the job's output appears in the terminal. Commit the migrations/ folder, since every environment applies the same files.

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 the web service in Describe the app in modelence.config.json sets one:

"dev": { "commands": ["flask --app notes run --debug --port 8000"] }

After that, start the app with npx modelence@latest dev instead of flask run. It runs the dev command on your machine with the environment's variables, so flask db upgrade and the app use that environment's database.

bash
npx modelence@latest setup
npx modelence@latest dev

Run it under Gunicorn

flask run starts Werkzeug's development server, which prints a warning not to use it in production. Before writing the Dockerfile, start the app the way the container will:

export FLASK_SECRET_KEY=local-check
gunicorn "notes:create_app()" --bind 0.0.0.0:8000 --workers 2 --threads 4 --access-logfile -
  • "notes:create_app()" tells Gunicorn to import notes and call the factory. The quotes keep the shell from reading the parentheses.
  • --bind 0.0.0.0:8000 listens on every interface. Gunicorn's own default is 127.0.0.1:8000, which only accepts connections from inside the container, unless PORT is set, in which case it binds 0.0.0.0:$PORT. Modelence sets PORT to the service's first port, so either way the app is reachable.
  • --workers 2 --threads 4 runs two processes with four threads each, so eight requests can be in progress at once. With more than one thread Gunicorn switches to its gthread worker, which suits a Flask app that mostly waits on the database or an API. In our test the master and both workers used about 165 MB together.
  • --access-logfile - writes one line per request to the output, which ends up in the environment's logs.

Open http://localhost:8000/health and http://localhost:8000/static/style.css, then stop Gunicorn with Ctrl+C.

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

For Flask, a managed MongoDB, PostgreSQL or Redis on Modelence is a connection string in an environment variable, under the name you give it in env. Here PostgreSQL arrives as DATABASE_URL, of the form postgresql://...?sslmode=require, and the factory hands it to Flask-SQLAlchemy unchanged. SQLAlchemy 2.1 picks psycopg 3 for a postgresql:// URL, which is the driver installed above, and passes sslmode=require through, so the connection uses TLS. If a project pins SQLAlchemy 2.0, write the scheme as postgresql+psycopg://, since 2.0 looks for psycopg2.

Each Gunicorn worker process keeps its own connection pool, five connections by default plus up to ten more under load, so two workers can hold up to 30 connections per container. pool_pre_ping tests a pooled connection before handing it out, so one that dropped, for example while the database fails over to a healthy machine, gets replaced instead of failing a request. Production databases are backed up at least every six hours.

Redis arrives as REDIS_URL, a rediss:// URL. Redis.from_url connects to it over TLS and verifies the certificate, and the RQ worker takes the same URL. MongoDB works the same way through PyMongo or Flask-PyMongo, with its connection string read from the environment. A PostgreSQL database you already run on Supabase or Neon keeps working once its URL is declared in env with "type": "secret".

Run migrations before you deploy

Apply migrations once per deploy, from your machine or CI, with the environment's database URL:

DATABASE_URL="<the environment's PostgreSQL URL>" flask --app notes db upgrade

With a connected local environment, npx modelence@latest dev already provides that variable to commands it runs. Keep flask db upgrade out of the Dockerfile's CMD and the service's start: every container runs those on boot, several at a time during a rollout, and a slow migration could still be running when the health check gives up on the container. During a rollout the old containers keep serving until the new ones are healthy, so write migrations the running code can live with, such as a new nullable column, and remove old columns one deploy later.

PostgreSQL and Redis are resources in modelence.config.json, and the deploy creates them before the new version starts:

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

Write a Dockerfile

A Python app on Modelence is built from its own Dockerfile, as in the FastAPI and Django guides. Add this one 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 rate-limits pulls, so a plain FROM python:3.12-slim can fail a build.
  • requirements.txt is installed before the code is copied, so a code change reuses the cached packages.
  • CMD is the Gunicorn command from Run it under Gunicorn in exec form, so SIGTERM reaches Gunicorn itself rather than a shell in front of it.
  • PYTHONUNBUFFERED=1 sends print output and log lines to the logs as soon as they are written.

Add a .dockerignore next to it, so the virtual environment and the local SQLite file stay out of the image:

.git
.venv
__pycache__
instance
.env
Dockerfile
FROM public.ecr.aws/docker/library/python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "notes:create_app()", "--bind", "0.0.0.0:8000", "--workers", "2", "--threads", "4", "--access-logfile", "-"]

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. It declares two services built from the same Dockerfile, plus PostgreSQL and Redis:

  • web runs the Dockerfile's CMD on port 8000 and counts as healthy once /health answers. It comes first, so the first deploy attaches the environment's URL to it.
  • worker swaps CMD for the RQ worker through start, which runs under /bin/sh -c, so $REDIS_URL is filled in from the environment. It listens on no port, so it has no health check, and "rollout": "recreate" stops the old worker before the new one starts.
  • FLASK_SECRET_KEY is a secret with no value in the file. The deploy asks for it, and you can view or change it later in the dashboard, where every view is logged.
  • FLASK_SESSION_COOKIE_SECURE is a plain value committed with the code, which from_prefixed_env() turns into SESSION_COOKIE_SECURE = True, so the session cookie is only sent over HTTPS.
modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "web": {
      "type": "service",
      "dockerfile": "Dockerfile",
      "ports": [8000],
      "healthCheck": { "type": "http", "path": "/health" },
      "dev": { "commands": ["flask --app notes run --debug --port 8000"] }
    },
    "worker": {
      "type": "service",
      "dockerfile": "Dockerfile",
      "start": { "commands": ["rq worker --url \"$REDIS_URL\""] },
      "healthCheck": { "type": "none" },
      "rollout": "recreate"
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "queue": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "queue", "output": "url" },
    "FLASK_SECRET_KEY": { "type": "secret" },
    "FLASK_SESSION_COOKIE_SECURE": { "value": "true" }
  }
}

Adjust the config for your project

  • If your app is a module-level app = Flask(__name__) in app.py rather than a factory, use app:app in CMD instead of "notes:create_app()".
  • Gunicorn's docs suggest 2 to 4 workers per CPU core. On a larger container, which you pick under Configure in the dashboard, raise --workers. To change it without a rebuild, remove --workers from CMD and set WEB_CONCURRENCY under Environment variables, which Gunicorn reads as its default.
  • For an app that is mostly CPU work, such as image processing, drop --threads and add workers instead, since Python threads share one CPU core per process.
  • Set the Python version in the FROM line to the one the project declares in .python-version or pyproject.toml. With uv or Poetry, copy the lockfile with pyproject.toml and install from it, such as with uv sync --frozen.
  • Using Celery instead of RQ, set the worker's start to celery -A notes.tasks worker --loglevel=info, with the broker URL read from REDIS_URL.
  • Declare other keys, such as a Stripe key or SMTP password, with "type": "secret" and no value. Give them a FLASK_ prefix to have them land in app.config, or read them with os.environ.
  • If the Flask app lives in a subdirectory, such as backend/, set "root": "backend" on both services. The dockerfile path is relative to it, and the build sees only the files under it.

Check the build locally

With Docker installed, build the image and run it with the variables a deploy provides. Without DATABASE_URL the container falls back to an empty SQLite file, so check the health route and a static file rather than the page:

docker build -t notes-app .
docker run --rm -e PORT=8000 -e FLASK_SECRET_KEY=local-check -p 8000:8000 notes-app

Then open http://localhost:8000/health and http://localhost:8000/static/style.css. A deploy runs the same build, so anything that fails here fails there too.

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 the variables the environment doesn't have yet. For FLASK_SECRET_KEY, paste the output of python -c "import secrets; print(secrets.token_hex())". Then it uploads the project, builds both services and follows the build until they are live. You pick the AWS region the first time you deploy an environment, and its containers and databases are created there.

The first deploy creates PostgreSQL and Redis, starts web and worker once they are ready and attaches <app>-<environment>.cloud.modelence.app to port 8000 of web. The new database has no tables yet, so run flask db upgrade against it as in Add a database before you use the app, and again before any deploy that adds a migration. To use your own domain, add it in the dashboard under Domains.

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

Trust the load balancer's headers

Modelence's load balancer terminates HTTPS and talks plain HTTP to the container, passing the original scheme and client address in X-Forwarded-Proto and X-Forwarded-For. Flask ignores those headers on its own, so without ProxyFix request.scheme is http, url_for(..., _external=True) builds http:// links, OAuth callbacks fail on a redirect URI mismatch and request.remote_addr is the load balancer's address for every visitor, which also breaks per-client limits in Flask-Limiter.

ProxyFix(app.wsgi_app, x_for=1, x_proto=1) trusts exactly one proxy, which is what sits in front of the app. Don't raise the numbers beyond the proxies you actually have, because a client can write its own X-Forwarded-For, and trusting extra entries lets it pick the address Flask sees. If you put Cloudflare's proxy in front of a custom domain, that adds a hop, so use x_for=2 there.

Add a health check

With "healthCheck": { "type": "http", "path": "/health" }, a container counts as healthy once /health answers with a 2xx status within 4 seconds, so a version that boots but can't serve requests never takes traffic and the deploy rolls back. The route returns a small JSON body and doesn't query the database, so a brief database failover doesn't get healthy containers replaced. Keep it outside login_required and any before_request hook that redirects signed-out users, because the check follows redirects and expects a 2xx at the end.

Flask answers any Host header unless you set TRUSTED_HOSTS, new in Flask 3.1. If you do, include the environment's hostname, which Modelence passes in SITE_URL, and your custom domains, since the check sends the same Host as real traffic.

Serve static files

Gunicorn serves /static/ through Flask, which sends each file with an ETag and Last-Modified and answers repeat requests with 304 Not Modified. Since SEND_FILE_MAX_AGE_DEFAULT is None by default, browsers check back on every page load. That is fine for a few stylesheets and scripts.

For long cache lifetimes, add a version to the file name or query string and raise SEND_FILE_MAX_AGE_DEFAULT, or wrap the app in WhiteNoise, which serves compressed files and caches them for a long time when the names carry a hash:

from whitenoise import WhiteNoise

app.wsgi_app = WhiteNoise(app.wsgi_app, root="notes/static/", prefix="static/")

Run jobs in the worker service

Don't start threads, a scheduler or a queue consumer inside the Flask app. Each Gunicorn worker in each container would run them, so with two workers in two containers every scheduled email goes out four times. The worker service runs RQ on its own and picks jobs off Redis, and enqueue from any web container lands in the same queue.

For jobs on a schedule, start the worker with rq worker --with-scheduler, which handles enqueue_at and enqueue_in, or run APScheduler or Celery beat in that service, and keep it at one container so nothing is scheduled twice. A job that can outlast the worker's stopTimeout, 30 seconds by default and up to 120, should be safe to run again, because a deploy can stop the worker in the middle of it. Multiple services has the details.

Keep files and state out of the container

A container's disk is replaced on every deploy, so data belongs in PostgreSQL, MongoDB or Redis, and the SQLite fallback is only for your machine. Files that users upload through request.files go to an S3-compatible bucket, for example with boto3, with the bucket's keys declared as secrets.

Flask's default session is a cookie signed with SECRET_KEY, so it works across containers and deploys as long as they share the key, which FLASK_SECRET_KEY makes sure of. For sessions stored on the server, Flask-Session can keep them in the managed Redis. With state out of the containers, two or more web containers under Configure keep the app up when one crashes or a zone goes down. See Availability for how rollouts and rollbacks behave.

Shut down cleanly

When a container stops, for example during a deploy, Gunicorn gets SIGTERM, and SIGKILL follows after the service's stopTimeout, 30 seconds by default. Gunicorn stops accepting connections and gives its workers its own --graceful-timeout, also 30 seconds, to finish the requests they are handling.

If some requests take longer, such as a slow report or a call to an AI model, raise both: --graceful-timeout 90 in CMD and "stopTimeout": 100 on web, up to 120. The exec form of CMD is what makes the signal reach Gunicorn at all.

Send errors and app logs to the logs

Everything the app writes to its output shows on the environment's Logs page, including Gunicorn's access log and its error log, which goes to the output by default. Flask logs an unhandled exception with its full traceback through app.logger before it returns the 500, so failed requests leave a trace without any setup.

Your own app.logger.info(...) calls are dropped, though, because outside debug mode the logger inherits Python's default level, WARNING. Set a level in the factory to keep them:

import logging

logging.basicConfig(level=logging.INFO)

Modelence vs Render, Heroku, PythonAnywhere and Vercel for Flask

Render, Heroku, PythonAnywhere and Vercel each have their own guide for running a Flask app. The table is based on each platform's own docs and pricing pages as of November 2026.

PlatformHow Flask runsDatabasesPricing
ModelenceGunicorn in a container built from your Dockerfile, in 17 AWS regions, with an RQ or Celery worker as a second serviceManaged MongoDB, PostgreSQL and Redis in the app's region, backed up at least every 6 hoursFree plan, then from $20 a month with that amount included as usage
RenderIts Flask guide sets pip install -r requirements.txt as the build command and gunicorn app:app as the start command, in 5 regions (Oregon, Ohio, Virginia, Frankfurt and Singapore)Render Postgres from $6 a month and Render Key Value from $10. Free Postgres expires 30 days after creationWorkspace plan (Hobby free, Pro $25 a month) plus instances from $7 a month. Free web services spin down after 15 idle minutes
HerokuThe Python buildpack finds requirements.txt, a Procfile line such as web: gunicorn hello:app starts the dyno, and Heroku sets WEB_CONCURRENCY from the dyno size. The Common Runtime runs in the US or EuropeHeroku Postgres from $5 a month, with a release process in the Procfile for migrationsEco dynos $5 a month, which sleep after 30 idle minutes, Basic $7
PythonAnywhereThe app runs from a WSGI configuration file you edit in its Web tab. A free account gets one app at your-username.pythonanywhere.com, with outbound internet limited to an allowlistMySQL on paid plans, and a PostgreSQL server as an option on custom plansBeginner is free with 100 CPU seconds and no custom domain, Developer is $10 a month
VercelThe whole app becomes one Vercel Function, found in a file such as app.py or index.py. A request runs up to 300 seconds, or 800 on Pro, and static files go in public/ instead of Flask's static folderVercel Blob for files, and databases from Marketplace integrationsHobby is free, Pro is $20 a month per developer seat with $20 of usage credit

Render's Flask guide is one of the shortest paths from a repository to a running app, and its free tier is enough to try an idea. Heroku runs the same Procfile and Gunicorn setup that many older Flask tutorials describe, and its release phase applies migrations for you. PythonAnywhere's free account, with consoles in the browser, suits learning Flask and small personal apps, and Vercel suits a small Flask API whose requests finish quickly and whose frontend already lives there. Modelence fits a Flask app that needs a web service, a worker, PostgreSQL and Redis running together on AWS in a region you choose out of 17, and it lets a coding agent write the config and run the deploy. Render alternatives, Heroku alternatives and Modelence vs Vercel go into more depth.

Next steps

Frequently asked questions

How do I deploy a Flask app to production?

Serve it with Gunicorn instead of flask run, bind it to 0.0.0.0 on the platform's port, read SECRET_KEY and the database URL from environment variables and wrap the app in ProxyFix when it runs behind a load balancer. On Modelence you add a Dockerfile that installs requirements.txt and starts Gunicorn, describe the app and its database in modelence.config.json and run npx modelence@latest deploy, which builds the image and runs it as containers on AWS.

Why shouldn't I use flask run in production?

flask run starts Werkzeug's development server, which is built for one developer on one machine and prints a warning saying so. It has no process management, and in debug mode it exposes an interactive debugger that can run code. A production server such as Gunicorn runs several worker processes, restarts a worker that hangs and shuts down gracefully when the platform stops the container.

How many Gunicorn workers should a Flask app use?

Gunicorn's docs suggest 2 to 4 workers per CPU core. For a typical Flask app that waits on a database or an API, a few workers with several threads each, such as --workers 2 --threads 4, handle more requests in the same memory. Gunicorn reads WEB_CONCURRENCY as its default worker count, so you can tune it per environment without rebuilding the image.

Why does Flask build http:// links after I deploy it?

The load balancer terminates HTTPS and forwards plain HTTP to the app, so Flask sees every request as HTTP unless you tell it to trust the forwarded headers. Wrap the app in Werkzeug's ProxyFix with x_proto=1 and x_for=1, matching the one proxy in front of it on Modelence. url_for with _external=True then builds https:// links, and request.remote_addr shows the visitor's address.

Can I host a Flask app for free?

Yes, several platforms have a free tier. Modelence's free plan runs one instance that sleeps when idle, and managed PostgreSQL, Redis and a second service such as a worker come with the paid plans. Render's free web services spin down after 15 idle minutes and its free Postgres expires after 30 days, and PythonAnywhere's free Beginner account runs one app with 100 CPU seconds and outbound internet limited to an allowlist.

Can I host a Flask app on AWS without managing servers?

Yes. Modelence runs on AWS: it builds the image from your Dockerfile, runs it as containers behind a load balancer with HTTPS, and creates the PostgreSQL and Redis databases in the same region, chosen from 17. You never configure the load balancer, container service or database instances yourself, and your coding agent can run the deploy from the project directory.

How do I run Flask-Migrate migrations when I deploy?

Run flask db upgrade once per deploy, against the environment's database, before the new code starts, and never in the container's start command, where several containers would run it at the same time. On Modelence you run it from your machine or CI with DATABASE_URL set to the environment's PostgreSQL URL. Keep each migration compatible with the version still running during the rollout.

Can I use SQLite for a Flask app in production?

Not on Modelence or any platform that replaces containers on each deploy, because the SQLite file lives on the container's disk and disappears with it, and each container would have its own copy. Point SQLALCHEMY_DATABASE_URI at the managed PostgreSQL through DATABASE_URL instead, and keep SQLite as the fallback on your own machine. Flask-Migrate runs the same migrations against both.

How do I run background jobs with Flask on Modelence?

Run the queue consumer as a second service in modelence.config.json, built from the same Dockerfile, with start set to rq worker --url "$REDIS_URL" or a Celery worker command, no health check and "rollout": "recreate". The managed Redis holds the queue, and its rediss:// URL reaches both services as REDIS_URL. Keep schedulers in that service at one container, so scheduled jobs aren't queued twice.

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

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

Deploy other stacks

Deploy your Flask app

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

Or paste this into your coding agent