Flask 500 in Production: Working Outside Application Context
Flask works locally but returns 500 under Gunicorn, with no traceback or a 'Working outside of application context' error? Find the real exception, fix the context, and catch it before users do.
A Flask 500 in production almost always comes from one of three things: a traceback you cannot see, code that touches current_app, g or the database outside an application context, or setup code that only breaks under Gunicorn. Read the Gunicorn error log first, make sure no error handler swallows the exception, then wrap background and import-time code in with app.app_context():.
Locally you run flask run with debug on, and the browser shows the full traceback. In production debug is off, so the user sees "Internal Server Error" and you see nothing. This guide takes you from that blank page to the real error, then through the fixes in the order they usually matter.
Step 1: Read the Real Traceback
Do not guess. Every unhandled exception in Flask is logged. You only need to know where the logs go.
- Gunicorn on a server: run
journalctl -u your-app -n 200if you use systemd, or open the file you set with--error-logfile. - Docker:
docker logs --tail 200 <container>. - Platforms (Render, Railway, Fly, Heroku): open the service logs and search for
Traceback.
Gunicorn writes its error log to stderr by default. If you start it with --error-logfile /dev/null or send output to a file nobody reads, the traceback is gone. Set it back:
gunicorn "app:create_app()" --workers 3 --bind 0.0.0.0:8000 \
--error-logfile - --access-log-format '%(h)s "%(r)s" %(s)s %(L)s'
The %(L)s field prints the request time in seconds, which helps later when you ask whether the 500 was also slow. If you see a 502 instead of a 500, the worker is being killed rather than raising; read Gunicorn WORKER TIMEOUT and 502 on Django, because the same Gunicorn settings apply to Flask.
A guide on Flask tracebacks not showing in Nginx logs makes the same point: the error often exists, but it is logged somewhere you are not looking.
Step 2: Make Sure an Error Handler Is Not Hiding It
If the logs show a 500 with no traceback, look for a custom handler. This is the most common hiding place:
@app.errorhandler(Exception)
def handle_error(e):
return jsonify(error="Something went wrong"), 500
This returns a clean JSON body and logs nothing. Flask only logs the traceback for you when no handler takes the exception. Log it yourself:
import logging
from werkzeug.exceptions import HTTPException
@app.errorhandler(Exception)
def handle_error(e):
if isinstance(e, HTTPException):
return e
app.logger.exception("Unhandled error on %s %s", request.method, request.path)
return jsonify(error="Something went wrong"), 500
app.logger.exception writes the message and the full traceback at error level. Returning HTTPException untouched keeps normal 404 and 400 responses working.
If your Flask logs do not appear next to Gunicorn's, connect them:
import logging
def create_app():
app = Flask(__name__)
gunicorn_logger = logging.getLogger("gunicorn.error")
if gunicorn_logger.handlers:
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
return app
Step 3: Fix "Working Outside of Application Context"
This is the error behind many production 500s. Flask objects such as current_app and g are proxies. They only work while an application context is active. Flask pushes one for you during a request. Outside a request, there is none, and you get:
RuntimeError: Working outside of application context.
Sentry's explainer and a freeCodeCamp forum thread both show the standard cure: push the context yourself.
from app import create_app
from app.extensions import db
from app.models import User
app = create_app()
with app.app_context():
count = db.session.query(User).count()
print(count)
Flask-SQLAlchemy 3.x needs this for every use of db.session, db.create_all() and db.engine. Code that worked in version 2 can start failing after an upgrade for the same reason.
The places that hit this in production:
- A script, cron job or management command that imports models and runs queries.
- Module-level code, such as a query at the top of a file that runs on import.
- Tests that call a helper directly, without a client.
- Anything that runs in a thread, covered next.
Step 4: Pass the App Into Threads and Background Work
A new thread does not inherit the context of the request that started it. This code works in a quick test and fails under load:
import threading
from flask import current_app
@app.post("/signup")
def signup():
threading.Thread(target=send_welcome_email, args=(user.id,)).start()
return "", 202
def send_welcome_email(user_id):
key = current_app.config["MAIL_KEY"] # RuntimeError in the thread
Hand the real app object to the thread and push a context inside it:
@app.post("/signup")
def signup():
real_app = current_app._get_current_object()
threading.Thread(target=send_welcome_email, args=(real_app, user.id)).start()
return "", 202
def send_welcome_email(app, user_id):
with app.app_context():
key = app.config["MAIL_KEY"]
...
For anything that matters, such as emails, invoices or webhooks, use a real queue instead of raw threads. A thread dies with the worker, and Gunicorn recycles workers. If you use Celery, the same context rule applies to tasks, and Celery Tasks Not Executing in Production covers the worker side.
Step 5: Check How Gunicorn Loads Your App
A mismatch between how you start locally and how Gunicorn starts breaks apps that use the application factory pattern.
# Local
flask --app app run
# Production: call the factory with parentheses
gunicorn "app:create_app()"
If you pass app:app and app is not a module-level object, Gunicorn exits with "Failed to find attribute". If you use a factory, the string must include (). A Railway thread on a factory entry point that worked locally but failed deployed shows what the mismatch looks like.
Also watch for heavy work at import time. Gunicorn imports your module in each worker. A model loaded from disk, a network call or a database query at module level runs on every boot and can time out or fail only on the server. Move it inside create_app or load it lazily on first use.
Step 6: Compare Config Between Local and Production
Many 500s on a fresh deploy are plain config gaps:
- A missing environment variable.
os.environ["DATABASE_URL"]raisesKeyErrorat import time and the worker never boots. Fail early with a clear message, or useos.environ.getwith a check. - No
SECRET_KEY. Sessions and flash messages raiseRuntimeError: The session is unavailable because no secret key was set. Set it from the environment. - Different database host.
localhostin your.envpoints at the container itself in Docker. Use the service name or the managed database URL. - Different package versions. Pin versions in
requirements.txtand install from it, so the server does not pull a newer Flask or SQLAlchemy than the one you tested. - Debug-only behavior. If your code behaves differently when
app.debugis true, test with debug off.
The fastest check is to run production locally: set the same environment variables and start gunicorn "app:create_app()" instead of flask run. Most of these failures reproduce in seconds.
Step 7: Catch the Next 500 Before Users Report It
A 500 that happens for one route and one kind of user is easy to miss. Add three cheap safeguards:
- Send unhandled exceptions to an error tracker with the route, user and release attached. See Sentry alternatives for 2026 if you are comparing options.
- Add a health route that touches the database, and monitor it with an uptime check.
- After every deploy, load your sign-up and login pages once, because those are the paths that break first.
How Relia Helps
Relia has a Python package that reports unhandled exceptions from a Flask app with the stack trace and request details. It joins that error with the deploy that came before it and the users who hit it, and explains the incident in plain words. When there is a stack trace, it gives a fix plan with the file and line, and after you deploy it checks whether the fix worked. Uptime monitors and checks of key pages cover the routes users depend on. You can look at the live demo first.
FAQ
Why does Flask show Internal Server Error with no details in production?
Debug mode is off, so the browser shows a generic page. The traceback is in your server logs. If it is missing there too, a custom error handler is probably catching the exception without logging it.
What does "Working outside of application context" mean in Flask?
You used current_app, g or the database where Flask has no active application context. Wrap the code in with app.app_context():, or pass the app object into the thread or job that needs it.
Should I turn on debug mode to see the error in production?
No. Debug mode exposes an interactive debugger that can run code on your server. Read the logs, or send the exception to an error tracker.
Why does Flask work with flask run but fail under Gunicorn?
Gunicorn loads your module differently. Common causes are a wrong entry point for a factory, work done at import time, and environment variables that are set in your shell but not in the service.
Do I need an app context inside a normal request?
No. Flask pushes both the request and application context for you during a request. You only add one manually in scripts, threads, jobs and tests.