0
0
FlaskHow-ToBeginner · 4 min read

How to Use Gunicorn with Flask for Production Servers

To use gunicorn with a Flask app, install Gunicorn and run it from the command line with gunicorn app:app, where app is your Python file and Flask app variable. Gunicorn serves your Flask app efficiently in production environments.
📐

Syntax

The basic command to run a Flask app with Gunicorn is:

gunicorn [OPTIONS] MODULE_NAME:VARIABLE_NAME

Here:

  • MODULE_NAME is the Python file name without .py.
  • VARIABLE_NAME is the Flask app instance inside that file.
  • OPTIONS are optional flags like -w for workers or -b for binding address.
bash
gunicorn app:app
💻

Example

This example shows a simple Flask app and how to run it with Gunicorn. It demonstrates serving the app on localhost port 8000 with 2 worker processes.

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, Gunicorn with Flask!'

# Save this as app.py

# Run this command in terminal:
# gunicorn -w 2 -b 127.0.0.1:8000 app:app
Output
When you visit http://127.0.0.1:8000/ in your browser, you will see: Hello, Gunicorn with Flask!
⚠️

Common Pitfalls

  • Wrong app variable name: Gunicorn needs the exact Flask app variable name; if you use app:application but your variable is app, it will fail.
  • Running Gunicorn inside Flask debug mode: Avoid using Flask's app.run(debug=True) with Gunicorn; Gunicorn handles serving and debugging separately.
  • Not installing Gunicorn: Make sure Gunicorn is installed in your environment with pip install gunicorn.
  • Binding to wrong address: Use -b 0.0.0.0:8000 to allow external access, or 127.0.0.1 for local only.
bash
## Wrong way (will error if app variable name is wrong):
gunicorn app:application

## Right way (matches Flask app variable):
gunicorn app:app
📊

Quick Reference

CommandDescription
gunicorn app:appRun Flask app with default settings
gunicorn -w 4 app:appRun with 4 worker processes
gunicorn -b 0.0.0.0:5000 app:appBind to all IPs on port 5000
gunicorn --reload app:appAuto-reload on code changes (development only)

Key Takeaways

Run Gunicorn with the syntax: gunicorn module_name:flask_app_variable.
Ensure your Flask app variable name matches what you pass to Gunicorn.
Use Gunicorn options like -w for workers and -b for binding address to customize.
Do not use Flask's debug server in production; Gunicorn is production-ready.
Install Gunicorn with pip before running it.