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 need | Version / notes |
|---|---|
| Python | A supported 3.x release (3.11 or newer recommended) – check with python3 --version |
| pip + venv | Included with Python |
| API client | curl or Postman |
3. Local setup
1Create the folder and venv
Work inside an activated virtual environment.
BASHmkdir flask-api && cd flask-api python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate2Install Flask
python-dotenv lets
flaskread.flaskenv/.envautomatically.BASHpip install flask python-dotenv pip freeze > requirements.txt
4. Create & run a project
1Write the app
A small JSON API with GET and POST routes.
app.pyfrom 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, 2012Run in debug mode
--debugenables auto-reload and the interactive debugger (never in production).BASHflask --app app run --debug3Test the API
Use a second terminal.
BASHcurl 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"}'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.
FLASK_SECRET_KEY=generate-a-long-random-value
FLASK_SQLALCHEMY_DATABASE_URI=postgresql://flask:pass@localhost/flaskdb
FLASK_DEBUG=0Key dependencies
| Package / tool | Used for |
|---|---|
flask | Routing, requests, Jinja2 templates |
gunicorn | Production WSGI server |
python-dotenv | Load .env/.flaskenv |
flask-sqlalchemy + flask-migrate | Database ORM and migrations |
flask-cors | CORS for browser clients |
pytest | Tests with app.test_client() |
Folder structure
flask-api/
├── app/
│ ├── __init__.py # create_app()
│ ├── books.py # blueprint
│ └── templates/
├── tests/
├── .env
├── requirements.txt
└── wsgi.py # app = create_app()Essential commands
| Command | What it does |
|---|---|
flask --app app run --debug | Development server with reload |
flask --app app routes | List all routes |
flask --app app shell | Shell with the app context |
gunicorn -w 4 -b 127.0.0.1:8000 app:app | Production server |
pytest | Run tests |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS, 1 GB RAM |
| App server | Gunicorn (workers ≈ 2 × CPU + 1) |
| Web server | Nginx reverse proxy |
| Domain + SSL | DNS + Let’s Encrypt |
Deployment steps
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.
BASHssh 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_IP2Install Python on the server
Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.
BASHsudo apt install -y python3 python3-venv python3-pip sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app3Install the app
Create a venv on the server and add Gunicorn.
BASHgit 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 …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.target5Start and enable the service
Reload systemd, start the service now and on every boot, and check that it is active (running).
BASHsudo systemctl daemon-reload sudo systemctl enable --now flask-api sudo systemctl status flask-api journalctl -u flask-api -f6Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:8000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { 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"; } }7Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx8Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status9Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com10Add 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.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run11Fix URLs behind the proxy
So
url_for(..., _external=True)andrequest.schemeuse https, wrap the app with ProxyFix.PYTHONfrom 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.
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
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store.