0
0
FlaskHow-ToBeginner · 4 min read

How to Use Flask in Production: Best Practices and Setup

To use Flask in production, run your app with a production-ready WSGI server like Gunicorn or uWSGI behind a reverse proxy such as Nginx. Avoid using Flask's built-in server as it is not designed for production use.
📐

Syntax

In production, you do not run Flask's built-in server. Instead, you use a WSGI server to serve your Flask app. The typical command to run Flask with Gunicorn looks like this:

  • gunicorn -w 4 -b 0.0.0.0:8000 myapp:app

Here, -w 4 means 4 worker processes, -b 0.0.0.0:8000 binds to all IPs on port 8000, and myapp:app points to your Flask app object.

bash
gunicorn -w 4 -b 0.0.0.0:8000 myapp:app
💻

Example

This example shows a simple Flask app and how to run it with Gunicorn for production. It demonstrates the app structure and the command to start the server.

python
from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()  # Only for development, not production

# To run in production, use the command:
# gunicorn -w 4 -b 0.0.0.0:8000 myapp:app
Output
When accessed via browser at http://localhost:8000, it shows: Hello, Production Flask!
⚠️

Common Pitfalls

Using Flask's built-in server in production: Flask's built-in server is single-threaded and not designed for handling real traffic or security.

Not using a reverse proxy: Without a reverse proxy like Nginx, you miss out on SSL termination, load balancing, and better static file handling.

Ignoring environment variables: Always set FLASK_ENV=production and configure secret keys securely.

python
## Wrong way (development server in production):
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)  # Not for production


## Right way (run with Gunicorn):
# gunicorn -w 4 -b 0.0.0.0:8000 myapp:app
📊

Quick Reference

  • Use Gunicorn or uWSGI as WSGI servers.
  • Place a reverse proxy like Nginx in front for SSL and load balancing.
  • Set environment variables: FLASK_ENV=production, SECRET_KEY.
  • Do not use Flask's built-in server in production.
  • Use multiple worker processes for handling concurrent requests.

Key Takeaways

Never use Flask's built-in server in production; use a WSGI server like Gunicorn instead.
Use a reverse proxy such as Nginx for SSL termination and better request handling.
Set environment variables properly to enable production mode and secure your app.
Run multiple worker processes to handle concurrent users efficiently.
Test your production setup locally before deploying to a live server.