Deploying Flask: Gunicorn, Environment, and Production Checklist

• Python • By TryzTech Team
FlaskPythonBackendWeb Development

An application that runs smoothly on a laptop is not automatically ready for public requests. During development, debug mode and auto reload make code changes easy to see. Production has different priorities: the process must remain stable, secrets must stay out of the repository, errors need to be recorded, and the application must expose a way to check its health.

Deploying Flask is not tied to one provider. Dashboard details and release commands vary, but the underlying needs remain similar: a WSGI server, environment variables, a prepared database, static files, logs, and a health check.

Why Not Use flask run?

The flask run command starts Werkzeug’s built-in development server. It is designed for coding and debugging, not for production load or worker management.

Gunicorn is a common WSGI server for Flask applications on Linux. Install it as a project dependency and start the app with:

# File: terminal
python -m pip install gunicorn
gunicorn --bind 0.0.0.0:8000 "app:create_app()"

The "app:create_app()" target tells Gunicorn to import the app module, call the create_app() factory, and use the returned Flask object. --bind selects the address and port that receive connections.

There is no need to guess a large worker count immediately. Start with the platform default or a small value, then measure response times, memory use, and workload behavior. Adding workers without checking server capacity can exhaust memory.

Move Configuration into the Environment

Secrets and database addresses should not be written directly in source code. Read them when the application process starts:

# File: config.py
import os


class Config:
    SECRET_KEY = os.environ["SECRET_KEY"]
    SQLALCHEMY_DATABASE_URI = os.environ["DATABASE_URL"]
    SQLALCHEMY_TRACK_MODIFICATIONS = False

Using os.environ["SECRET_KEY"] deliberately fails when the variable is missing. For required configuration, a clear startup failure is easier to diagnose than an application running with an unsafe default secret.

Every environment should have its own values. Development, staging, and production do not need to share a database or secret. A .env file can help locally, but add it to .gitignore and use the platform’s secret manager in production.

Debug mode must also stay off. Do not set FLASK_DEBUG=1 or use --debug on a public server because the debugger can reveal internal details and may expose code execution.

Add a Small Health Check

Deployment platforms and monitoring services need a lightweight URL that confirms the web process is responding:

# File: routes/health.py
from flask import Blueprint, jsonify

health_bp = Blueprint("health", __name__)


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

Register the Blueprint in create_app(). This basic endpoint proves the web process is alive. If database or external-service checks are needed, consider a separate readiness endpoint so a temporary dependency issue does not always restart the process.

Code Changes Do Not Update the Database

The latest model may require columns that do not exist in production yet. Run migrations as an explicit release step, for example with Flask-Migrate:

# File: terminal
python -m flask --app app db upgrade

Back up important data before a risky migration, and make sure application versions remain compatible during rollout. db.create_all() is not a migration replacement because it does not safely update existing tables.

Static Files and Reverse Proxies

Flask can serve its static folder, but deployments with more traffic often hand assets to a reverse proxy, object storage, or a CDN. Confirm that URLs generated by url_for("static", ...) remain correct and that cache headers fit the release strategy.

When the application runs behind a reverse proxy, headers can communicate the original HTTPS protocol and client address. Use ProxyFix only when the proxy is configured and the number of trusted proxies is known. Blindly trusting those headers lets clients forge request information.

Logs Must Leave the Process

In containers and managed platforms, write logs to standard output and standard error so the platform can collect them. Record useful context such as method, path, status code, and request ID, but never log passwords, tokens, session cookies, or sensitive request bodies.

Production errors should return a safe HTML page or JSON response to users while the complete stack trace goes to private logs. Users receive a sensible response, and developers still have enough detail to investigate.

Flask Release Checklist

Before directing traffic to a new version, verify the following:

  • Production dependencies are locked and Gunicorn can import create_app().
  • SECRET_KEY, DATABASE_URL, and other required settings come from the environment.
  • Debug mode is off and stack traces are not sent to users.
  • Migrations have been tested, with a backup available for risky database changes.
  • Static files load from their production URLs.
  • Session cookies use secure settings when the application runs over HTTPS.
  • /health responds and monitoring can reach it.
  • Startup and error logs arrive somewhere searchable.

Check the Application After Deployment

Deployment is not complete just because a dashboard turns green. Open the home page, sign in with a test account, perform one CRUD operation, and call an important API endpoint. Watch the logs at the same time for hidden warnings or errors.

Prepare a path back to the previous version if the smoke test fails. A simple rollback that has already been tested is far more useful than inventing a recovery plan after the application is already unhealthy.

Keep reading within the same topic.

Don't Miss Out

Get the latest tech articles, tips, and insights delivered to your inbox.