Deployment · By Rivtor · Updated
Deploy Flask with SQLAlchemy and PostgreSQL
Run Flask behind a production WSGI server, read PostgreSQL configuration from the server environment and apply reviewed schema migrations. Disable the development debugger and verify the app’s database operations and static-file handling after release.
See the Rivtor deployment workflow →
Replace the development server
Flask’s local development command is useful while coding but is not the production serving boundary. Choose a supported WSGI server and install it as a runtime dependency. Check whether the application exports app directly or creates it through a factory.
These alternative commands illustrate two project shapes on a Unix-like runtime. Choose the one matching your module and use the port assigned by the host:
gunicorn --bind 0.0.0.0:8000 'app:app'
# Factory-style alternative, not a second process to run:
gunicorn --bind 0.0.0.0:8000 'app:create_app()'
The name app is illustrative. Running from a different service root changes Python’s import resolution. Never enable debug mode to diagnose a public deployment.
Configure the database library deliberately
SQLAlchemy needs a URL compatible with the installed PostgreSQL driver. Keep the full URL private and inspect only sanitized configuration. Set a bounded connection pool; multiply its size by the number of WSGI worker processes before choosing a worker count.
Flask-SQLAlchemy, plain SQLAlchemy and different migration tools have different configuration hooks. Use your actual application’s documented command. Do not run create_all on every request or assume it safely evolves an existing schema. Rehearse migrations on disposable data.
Check the deployed application
| Check | Expected observation |
|---|---|
| Startup | Production WSGI server imports the intended app |
| Health | The configured path returns the intended response |
| Data operation | A synthetic record can be written and read |
| Restart | The record remains in PostgreSQL |
| Browser page | Static assets and redirected URLs resolve correctly |
Rivtor documents Flask detection and PostgreSQL provisioning. Review the service-root reference and data variables. Behind a proxy, configure forwarded-header handling only for a known trust boundary; blindly trusting arbitrary client-supplied headers can create incorrect URLs or security assumptions.