Backend & Languages

Flask Setup & Deployment Guide

Lightweight Python micro-framework – build routes and a JSON API, use an app factory and config, then serve it with Gunicorn and Nginx.

Updated Official documentation ↗

1. Introduction & use cases

Flask is a small, flexible Python web framework. The core gives you routing, request/response handling and Jinja2 templates; you add only what you need through extensions (Flask-SQLAlchemy, Flask-Login, Flask-Migrate …).

Its simplicity makes it ideal for APIs, prototypes and microservices. For production, Flask’s built-in server is replaced by Gunicorn behind Nginx.

Where it is used

  • Small to medium REST APIs and microservices
  • Serving machine-learning models over HTTP
  • Prototypes and internal tools
  • Websites with Jinja2 templates

2. Prerequisites

You needVersion / notes
PythonA supported 3.x release (3.11 or newer recommended) – check with python3 --version
pip + venvIncluded with Python
API clientcurl or Postman

3. Local setup

  1. 1Create the folder and venv

    Work inside an activated virtual environment.

    BASH
    mkdir flask-api && cd flask-api
    python3 -m venv .venv
    source .venv/bin/activate   # Windows: .venv\Scripts\activate
  2. 2Install Flask

    python-dotenv lets flask read .flaskenv/.env automatically.

    BASH
    pip install flask python-dotenv
    pip freeze > requirements.txt

4. Create & run a project

  1. 1Write the app

    A small JSON API with GET and POST routes.

    app.py
    from flask import Flask, jsonify, request
    
    app = Flask(__name__)
    books = [{"id": 1, "title": "Clean Code"}]
    
    @app.get("/health")
    def health():
        return {"status": "ok"}
    
    @app.get("/api/books")
    def list_books():
        return jsonify(books)
    
    @app.post("/api/books")
    def add_book():
        data = request.get_json(silent=True) or {}
        if not data.get("title"):
            return {"error": "title is required"}, 400
        book = {"id": len(books) + 1, "title": data["title"]}
        books.append(book)
        return book, 201
  2. 2Run in debug mode

    --debug enables auto-reload and the interactive debugger (never in production).

    BASH
    flask --app app run --debug
  3. 3Test the API

    Use a second terminal.

    BASH
    curl http://127.0.0.1:5000/api/books
    curl -X POST http://127.0.0.1:5000/api/books -H "Content-Type: application/json" -d '{"title":"Fluent Python"}'
  4. 4Grow with an app factory and blueprints

    For bigger apps, build the app in a function and split routes into blueprints – easier testing and configuration.

    PYTHON
    # app/__init__.py
    from flask import Flask
    
    def create_app():
        app = Flask(__name__)
        app.config.from_prefixed_env()   # reads FLASK_* variables
        from .books import bp
        app.register_blueprint(bp, url_prefix="/api/books")
        return app
    
    # run with: flask --app app run --debug

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

app.config.from_prefixed_env() loads every FLASK_* variable into app.config (e.g. FLASK_SECRET_KEY → SECRET_KEY). Keep a strong SECRET_KEY for sessions.

.env
FLASK_SECRET_KEY=generate-a-long-random-value
FLASK_SQLALCHEMY_DATABASE_URI=postgresql://flask:pass@localhost/flaskdb
FLASK_DEBUG=0

Key dependencies

Package / toolUsed for
flaskRouting, requests, Jinja2 templates
gunicornProduction WSGI server
python-dotenvLoad .env/.flaskenv
flask-sqlalchemy + flask-migrateDatabase ORM and migrations
flask-corsCORS for browser clients
pytestTests with app.test_client()

Folder structure

project structure
flask-api/
├── app/
│   ├── __init__.py    # create_app()
│   ├── books.py       # blueprint
│   └── templates/
├── tests/
├── .env
├── requirements.txt
└── wsgi.py            # app = create_app()

Essential commands

CommandWhat it does
flask --app app run --debugDevelopment server with reload
flask --app app routesList all routes
flask --app app shellShell with the app context
gunicorn -w 4 -b 127.0.0.1:8000 app:appProduction server
pytestRun tests

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS, 1 GB RAM
App serverGunicorn (workers ≈ 2 × CPU + 1)
Web serverNginx reverse proxy
Domain + SSLDNS + Let’s Encrypt

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Python on the server

    Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.

    BASH
    sudo apt install -y python3 python3-venv python3-pip
    sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app
  3. 3Install the app

    Create a venv on the server and add Gunicorn.

    BASH
    git clone https://github.com/you/flask-api.git /srv/app && cd /srv/app
    python3 -m venv .venv
    .venv/bin/pip install -r requirements.txt gunicorn
    nano .env   # FLASK_SECRET_KEY, database URL …
  4. 4Run it as a systemd service

    systemd starts the app on boot and restarts it on failure. Save the unit file, then enable it. Logs: journalctl -u flask-api -f.

    /etc/systemd/system/flask-api.service
    [Unit]
    Description=flask-api
    After=network.target
    
    [Service]
    User=deploy
    WorkingDirectory=/srv/app
    EnvironmentFile=/srv/app/.env
    ExecStart=/srv/app/.venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 'app:app'
    Restart=always
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target
  5. 5Start and enable the service

    Reload systemd, start the service now and on every boot, and check that it is active (running).

    BASH
    sudo systemctl daemon-reload
    sudo systemctl enable --now flask-api
    sudo systemctl status flask-api
    journalctl -u flask-api -f
  6. 6Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:8000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  7. 7Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  8. 8Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  9. 9Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  10. 10Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  11. 11Fix URLs behind the proxy

    So url_for(..., _external=True) and request.scheme use https, wrap the app with ProxyFix.

    PYTHON
    from werkzeug.middleware.proxy_fix import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ flask --app app run --debug * Serving Flask app 'app' * Debug mode: onWARNING: This is a development server. Do not use it in a production deployment. * Running on http://127.0.0.1:5000Press CTRL+C to quit * Restarting with stat * Debugger is active!
Figure 1: terminal output of the sample Flask project (section 4).
1Routes +blueprints2pip install onserver3Gunicorn :8000(systemd)4Nginx proxy5HTTPS API
Figure 2: production deployment flow (section 6).
flask-api/├── app/│ ├── __init__.py # create_app()│ ├── books.py # blueprint│ └── templates/├── tests/├── .env├── requirements.txt└── wsgi.py # app = create_app()
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Error: Could not locate a Flask application

Tell Flask where the app is: flask --app app run (file app.py) or --app "app:create_app()" for a factory.

request.get_json() returns None

Send Content-Type: application/json, or use get_json(silent=True) and validate.

RuntimeError: Working outside of application context

Code that uses current_app, g or the DB ran outside a request. Wrap it in with app.app_context():.

Session data lost / The session is unavailable because no secret key was set

Set a fixed SECRET_KEY from the environment; it must be the same for all workers.

[CRITICAL] WORKER TIMEOUT in Gunicorn

A request took longer than 30 s. Optimise it, move work to a background job, or raise --timeout.

Best practices

  • Never use app.run()/debug mode in production.
  • Use the app-factory pattern and blueprints once you have more than a few routes.
  • Validate input (marshmallow/pydantic).
  • Log to stdout and let systemd/journald collect logs.
  • Never commit .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.