Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

You can build a working Flask REST API on Ubuntu with a Python virtual environment, explicit routes, and JSON responses, then run it behind Gunicorn and nginx for production. Use Flask’s development server only while coding; the deployed service should run as an unprivileged systemd-managed Gunicorn process, with nginx handling public HTTP connections.

This guide starts with a small health and items API, shows how to test it with curl, and then moves the same application behind a Unix socket and nginx. Flask 3.1.x supports Python 3.9 and newer, but the current Gunicorn installation page requires Python 3.12 or newer, so check your interpreter before creating the production environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you are building

The finished setup has four layers:

  • Flask application: Python functions map URL paths and HTTP methods to responses.
  • Gunicorn: A production WSGI server imports your Flask application and manages worker processes.
  • nginx: A public reverse proxy accepts HTTP requests and forwards them to Gunicorn.
  • systemd: Ubuntu starts, stops, restarts, and logs Gunicorn as a dedicated unprivileged service.

During development, Flask can listen on a local port directly. In production, clients should reach nginx on ports 80 or 443, while Gunicorn remains private on loopback or a Unix socket. Your API’s authentication, validation rules, database, logging policy, rate limits, and error format are part of the API contract and must be defined for the application rather than assumed by Flask.

Check Ubuntu and Python prerequisites

Verify the interpreter before installing anything

Run:

python3 --version

Flask 3.1.x supports Python 3.9 and later. The current Gunicorn installation requirement is Python 3.12 or later. If Ubuntu’s python3 is older than 3.12, install an approved Python 3.12-or-newer package for your Ubuntu release and use that executable when creating the production virtual environment. Do not assume that a virtual environment upgrades Python; it uses the interpreter that created it.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Install the operating-system packages

Refresh package metadata and install Python, virtual-environment support, pip, and nginx:

sudo apt update
sudo apt install python3 python3-venv python3-pip nginx

If you selected a separate Python 3.12 executable, substitute it in the virtual-environment commands below, for example python3.12 -m venv .venv. Keep the interpreter choice consistent for Flask, Gunicorn, systemd, and any later deployment automation.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create an isolated Flask project

Make the project directory and virtual environment

Create a directory that is separate from Ubuntu’s system libraries:

mkdir -p ~/flask-api
cd ~/flask-api
python3 -m venv .venv
. .venv/bin/activate

After activation, the shell prompt normally shows (.venv). Install Flask and Gunicorn inside this environment:

pip install Flask gunicorn

The official Flask installation guidance recommends a virtual environment because each project then has its own package versions instead of changing the operating system’s Python installation or another application’s dependencies. If pip install gunicorn reports an unsupported Python version, recreate the environment with Python 3.12 or newer rather than installing packages into the system interpreter.

Confirm the installed tools

python --version
flask --version
gunicorn --version
which python
which gunicorn

The final two commands should resolve into your project’s .venv/bin directory. If they point to /usr/bin, activate the environment again with . .venv/bin/activate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Write a small JSON API

Create app.py

Save this file in ~/flask-api/app.py:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.get('/api/health')
def health():
    return jsonify(status='ok')

@app.get('/api/items')
def list_items():
    return jsonify(items=[])

@app.post('/api/items')
def create_item():
    payload = request.get_json(silent=True) or {}
    return jsonify(item=payload), 201

app = Flask(__name__) creates the application object. The @app.get and @app.post decorators make the HTTP method part of the route definition, so a GET and a POST are not accidentally treated as the same operation. jsonify serializes Python values and sets a JSON response content type. Returning 201 from the POST route communicates that a resource was created.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

This example deliberately keeps items in memory as an empty list response and echoes a submitted object. It does not provide persistence, authentication, input validation, duplicate detection, or authorization. Add those rules before exposing a real resource.

Make the contract explicit

Document each endpoint before clients depend on it. At minimum, record:

  • The exact path, including the /api prefix.
  • Allowed HTTP methods and what each method changes.
  • Required headers such as Content-Type: application/json and any authentication header.
  • Request fields, data types, size limits, and whether unknown fields are rejected.
  • Successful response JSON shapes and status codes.
  • Error response shape, status code, and whether error details are safe to expose.

For this sample, GET /api/health returns {status: ok}, GET /api/items returns an object containing an items array, and POST /api/items returns the submitted object under item with status 201. In a production contract, use a stable documented schema and reject malformed input instead of silently converting it to an empty object.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run and exercise the API locally

Start Flask’s development server

With the virtual environment active and the current directory set to the project, run:

flask --app app run --debug

The server normally listens on 127.0.0.1:5000. The --debug option enables automatic reloads and the interactive debugger; both are development conveniences and must not be enabled for a public deployment.

Test each route with curl

curl http://127.0.0.1:5000/api/health
curl http://127.0.0.1:5000/api/items
curl -i -X POST http://127.0.0.1:5000/api/items -H 'Content-Type: application/json' -d '{"name":"Ada"}'

The first request should return a JSON object whose status is ok. The second should return an empty items array. The POST response should include an HTTP/1.1 201 status and an item object containing the submitted name. The -i option displays response headers so you can verify status and content type as well as the body.

Test malformed and missing input deliberately

Try a POST without a body and with a non-JSON content type. The sample uses silent=True, so parsing failures become an empty object rather than a Flask exception. That behavior is convenient for a demonstration but usually too permissive for a business API. Replace it with explicit validation that returns a documented client error, commonly status 400, when required fields or types are missing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Separate development behavior from production behavior

Flask’s built-in server is intended for local development, not Internet-facing traffic. It is not the production process manager, does not provide the deployment isolation you need, and exposes a debugger when debug mode is enabled. Stop it with Ctrl+C after local testing.

Gunicorn is a WSGI server designed to run the Flask application with worker processes. Flask’s deployment guidance recommends putting nginx or Apache in front of the WSGI server as a reverse proxy. Gunicorn must run as an unprivileged account; running it as root would make application code run with root privileges if the process were compromised.

Try Gunicorn before creating a service

Bind to loopback for a private test

From the active virtual environment, run:

gunicorn --workers 4 --bind 127.0.0.1:8000 app:app

The target app:app means import the module app and use its Flask object named app. Four synchronous workers are the documented example and a reasonable starting point for many ordinary Flask workloads, not a universal capacity guarantee. Measure your application and tune worker count for its CPU, memory, request time, and traffic pattern.

In another shell, call:

curl http://127.0.0.1:8000/api/health

Binding to 127.0.0.1 keeps Gunicorn off the public network interface when nginx is the edge server. Press Ctrl+C to stop this foreground test.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose synchronous or asynchronous workers deliberately

Gunicorn’s default synchronous worker is appropriate for most uses. The Gunicorn Flask guidance documents gevent for applications that must handle numerous long-running concurrent connections. An asynchronous worker does not automatically make blocking application code safe or faster; evaluate library compatibility, timeout behavior, and observability before changing worker classes.

Create a durable systemd Gunicorn service

Prepare a production-owned directory

Do not run the deployed service from a personal home directory with broad permissions. Create a dedicated unprivileged account and application directory:

sudo adduser --system --group --home /srv/flask-api flaskapi
sudo mkdir -p /srv/flask-api
sudo chown -R flaskapi:flaskapi /srv/flask-api

Copy app.py and your application source into /srv/flask-api, then create and populate its environment as that account. The following commands assume the Python executable you selected satisfies Gunicorn’s Python 3.12-or-newer requirement:

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
sudo -u flaskapi python3 -m venv /srv/flask-api/.venv
sudo -u flaskapi /srv/flask-api/.venv/bin/pip install Flask gunicorn

In a real project, install pinned, reviewed dependencies from your deployment process rather than relying on an unrecorded set of latest packages.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define the service unit

Create /etc/systemd/system/flask-api.service:

[Unit]
Description=Flask API Gunicorn service
After=network.target

[Service]
User=flaskapi
Group=www-data
WorkingDirectory=/srv/flask-api
RuntimeDirectory=flask-api
RuntimeDirectoryMode=0770
ExecStart=/srv/flask-api/.venv/bin/gunicorn --workers 4 --umask 007 --bind unix:/run/flask-api/gunicorn.sock app:app
Restart=always

[Install]
WantedBy=multi-user.target

User=flaskapi prevents the application from running as root. Ubuntu’s nginx worker normally uses the www-data group; assigning that group and using a restrictive umask allows nginx to open the Unix socket. If your nginx process uses a different account or group, change the unit accordingly and verify the directory and socket permissions rather than making them world-writable.

Load, start, and inspect the service

sudo systemctl daemon-reload
sudo systemctl enable --now flask-api.service
sudo systemctl status flask-api.service
sudo journalctl -u flask-api.service -e

enable --now starts the service immediately and enables it at boot. status shows whether systemd considers it active; journalctl displays Gunicorn’s standard output and errors. A repeated restart usually indicates an import error, an incorrect working directory, a missing dependency, an invalid Python version, or a socket-permission problem. Run the exact ExecStart command manually as flaskapi to expose configuration errors quickly, then check the journal again.

Put nginx in front of Gunicorn

Configure a reverse-proxy server block

Create an nginx site configuration such as /etc/nginx/sites-available/flask-api:

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://unix:/run/flask-api/gunicorn.sock:;
        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;
    }
}

Replace api.example.com with the hostname that resolves to the Ubuntu server. The trailing colon in the Unix-socket proxy_pass value is part of nginx’s socket syntax. The forwarded headers preserve the original host, client address, proxy chain, and scheme for application logging and URL generation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Enable and validate the site

sudo ln -s /etc/nginx/sites-available/flask-api /etc/nginx/sites-enabled/flask-api
sudo nginx -t
sudo systemctl reload nginx

Run nginx -t before every reload. If it reports a syntax error, nginx keeps the previous working configuration; correct the indicated line and test again. If nginx returns 502 Bad Gateway, inspect both layers: confirm flask-api.service is active, verify that /run/flask-api/gunicorn.sock exists, and check that nginx’s account can traverse the runtime directory and open the socket.

Keep public traffic at nginx

Do not bind Gunicorn to 0.0.0.0 when nginx is the intended public edge. A loopback bind or Unix socket prevents clients from bypassing nginx’s request limits, access logging, header handling, and future TLS termination. For HTTPS, configure TLS at nginx using certificates managed by your normal Ubuntu certificate process, then preserve X-Forwarded-Proto so the application can distinguish secure requests.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Deployment choices at a glance

Choice Where it fits Trade-off
flask --app app run --debug Local development and interactive debugging Convenient reloads and debugger; not a production server
Gunicorn on 127.0.0.1:8000 Private production process or a quick deployment test Simple to test, but another component must expose HTTP publicly and supervise restarts
Gunicorn on a Unix socket plus nginx Typical Ubuntu production topology Requires socket permissions and nginx configuration, but keeps Gunicorn private and gives nginx the public edge
systemd service Long-running process with boot startup and journal logging Requires a unit file and explicit user, directory, and environment settings
systemd socket activation Deployments that want systemd to create and hand off the listening socket Adds lifecycle configuration; use Gunicorn’s documented socket-activation pattern consistently rather than mixing incompatible service and socket units
Synchronous Gunicorn workers Most conventional Flask request workloads Each worker handles one request at a time
gevent workers Numerous long-lived concurrent connections when the application stack supports cooperative I/O Requires compatible dependencies and deliberate testing of blocking code

Design the parts Flask does not decide for you

Validation and status codes

Check JSON types, required fields, maximum lengths, and allowed values before writing data. Return a consistent client-error document for malformed JSON or invalid fields, and reserve server-error responses for failures the client cannot correct. Keep successful response shapes stable so clients do not need to infer whether a missing key means null, empty, or an error.

Persistence and concurrency

The example returns an empty list because it has no database. A real API needs a persistence layer and a clear transaction strategy. Multiple Gunicorn workers do not share ordinary Python variables; an in-memory list would be separate in each worker and would disappear when a worker restarts. Store durable state in a database or another service designed for shared access.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authentication, authorization, and secrets

Decide how callers authenticate and which resources each identity may access. Keep credentials, signing keys, and database passwords outside source files, provide them through protected environment or secret-management mechanisms, and never return them in JSON or logs. Apply authorization checks to every mutating and sensitive route, not only to the login endpoint.

Logging, limits, and observability

Log request identifiers, method, path, status, and duration without recording passwords, tokens, or untrusted data that could forge log lines. Set request and upstream timeouts appropriate to the workload. Rate limiting and payload-size limits belong at the application, nginx, or an API gateway layer according to your threat model. Monitor systemd restarts, Gunicorn worker exits, nginx errors, disk space, and memory.

Common failures and fixes

ModuleNotFoundError or an unknown Gunicorn command

The service is probably using a different interpreter from your shell. Use an absolute executable path in ExecStart, confirm the module is under WorkingDirectory, and install dependencies into that exact .venv.

Gunicorn refuses to install

Check python --version inside the environment. Flask 3.1.x can run on Python 3.9 or newer, but the current Gunicorn requirement is Python 3.12 or newer. Recreate the environment with a supported interpreter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

nginx reports 502

Check sudo systemctl status flask-api.service, then sudo journalctl -u flask-api.service. Confirm the socket path in the systemd unit exactly matches nginx, and inspect permissions on /run/flask-api and gunicorn.sock. A service running under the wrong group can create a socket that nginx cannot open.

Requests reach nginx but the application sees the wrong scheme or client address

Verify the four proxy_set_header directives in the server block and make sure the application framework is configured to trust proxy headers only from your controlled proxy. Do not blindly trust client-supplied forwarding headers when nginx is not the only network path.

Changes to app.py are not visible

Debug reloads apply to Flask’s development server, not automatically to a systemd Gunicorn service. Deploy the changed files, restart or reload the service using your chosen Gunicorn strategy, and watch the journal for import or migration errors.

Production checklist

  • Use a Python version supported by both Flask and the current Gunicorn release.
  • Create and activate a project virtual environment; install dependencies there.
  • Define routes, methods, JSON schemas, status codes, and errors explicitly.
  • Test health, success, invalid-input, unauthorized, and server-failure paths with curl or your API test suite.
  • Disable Flask debug mode outside local development.
  • Run Gunicorn as a dedicated unprivileged user, never as root.
  • Keep Gunicorn on loopback or a protected Unix socket behind nginx.
  • Use systemd for startup, restart behavior, and journal logs.
  • Validate nginx configuration before reloading it.
  • Protect secrets, validate payloads, enforce authorization, and avoid sensitive data in logs.
  • Document persistence, migrations, timeouts, rate limits, and operational ownership before launch.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.