Loading a web page on your phone that's served by a Raspberry Pi on your desk is one of the most satisfying first projects on a Pi, and Flask makes it a few lines of Python. This guide goes from a freshly booted Pi to a Flask server your whole network can reach, that controls a GPIO pin, accepts data from an ESP32, and starts by itself at boot.
Quick answer: create a virtual environment (python3 -m venv --system-site-packages venv), pip install flask, write an app.py with app.run(host="0.0.0.0", port=5000), and open http://<pi-ip>:5000 from any device on the same Wi-Fi. For GPIO, use gpiozero, which works on every Pi including the Pi 5. To start it at boot, add a systemd service.
By the end you'll have a Flask app that serves pages and JSON, switches an LED on a GPIO pin from your browser, and restarts automatically whenever the Pi reboots.
Why Flask, and Why Raspberry Pi?
There are bigger frameworks out there — Django being the obvious one — but Flask earns its place on a Raspberry Pi specifically because of how little it asks for. No forced folder structure, no admin panel you don't need, no ORM you have to configure before you've even written a route. You write a few lines of Python, and you're serving a page.
Pair that minimal footprint with a Raspberry Pi, and the combination makes sense for a particular kind of project: things that need to run quietly, sip very little power, and stay on 24/7 without anyone thinking about them. A home automation dashboard. A sensor readout page you check from your phone. A small API that talks to other devices on your network. None of these need a beefy server — they need something small, reliable, and always there.
You also don't need the latest Pi model. A Pi 3, a Pi 4, a Pi 5, or even a Pi Zero 2 W runs Flask comfortably for small to medium projects. A local dashboard serving a few users a minute barely registers on any of them.
What You'll Need Before Starting
- A Raspberry Pi (any model with network access — Wi-Fi or Ethernet)
- A microSD card with Raspberry Pi OS installed and booted
- Access to the Pi via terminal — either directly with a monitor/keyboard, or remotely via SSH
- Python 3, which comes pre-installed on current Raspberry Pi OS builds
- For Step 8 only: one LED, a 330Ω resistor, a breadboard, and two jumper wires
- About thirty minutes and a bit of patience for your first install
If you haven't set up SSH yet, it's worth doing — controlling your Pi headlessly from your main computer makes this whole process far less fiddly.
One note before you start copying commands: the examples use the classic default username pi. Recent Raspberry Pi OS images let you choose your own username when you flash the card, so wherever you see pi or /home/pi, substitute yours.
Step 1: Updating the System
Open a terminal on your Pi, either directly or over SSH, and start with the basics:
sudo apt update && sudo apt upgrade -yThis pulls the latest package lists and updates anything outdated. It's tempting to skip this step when you're impatient to get coding, but skipping it is exactly how people end up with mysterious version conflicts an hour later.
Step 2: Installing Python and pip
Most current Raspberry Pi OS images ship with Python 3 already installed. You can confirm with:
python3 --versionIf pip isn't installed yet, grab it:
sudo apt install python3-pip -ypip is Python's package installer. The virtual environment in the next step comes with its own copy, so this system-wide install is mostly a safety net, but it's quick and harmless.
Step 3: Setting Up a Virtual Environment (Don't Skip This)
This is the part a lot of quick tutorials skip, and it's the part that saves you headaches later. A virtual environment keeps your project's Python packages separate from the system-wide Python installation. Without it, you risk version conflicts between different projects, or breaking system tools that rely on specific package versions. On Raspberry Pi OS Bookworm and newer, pip goes further and refuses to install packages system-wide, printing an "externally-managed-environment" error. There, a virtual environment isn't just good practice, it's required.
sudo apt install python3-venv -y
mkdir ~/flask-project
cd ~/flask-project
python3 -m venv --system-site-packages venv
source venv/bin/activateThe --system-site-packages flag lets the virtual environment see the GPIO libraries that come with Raspberry Pi OS (gpiozero and lgpio), so hardware code in Step 8 works without compiling anything. Packages you pip install still go into the venv only.
Once activated, you'll see (venv) appear at the start of your terminal prompt. That's your sign everything you install next stays contained to this project.
Step 4: Installing Flask
With your virtual environment active, install Flask:
pip install flaskThat's the whole installation. Flask pulls in a few small pure-Python dependencies (Werkzeug, Jinja2 and friends), so there's nothing to compile and no long wait on a slow SD card. That light footprint is a big part of why Flask is such a good fit for a Pi.
Step 5: Writing Your First Flask App
Create a new file called app.py inside your project folder:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello from your Raspberry Pi!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)Let's actually unpack what's happening here, because understanding it matters more than copying it.
Flask(__name__)creates your application instance.@app.route('/')is a decorator that tells Flask "when someone visits this URL path, run the function underneath it."- The function returns whatever you want shown in the browser — in this case, plain text, but it could just as easily be HTML, JSON, or a rendered template.
app.run(host='0.0.0.0', port=5000)starts the server. Thehost='0.0.0.0'part is easy to overlook but genuinely important — it tells Flask to accept connections from any device on your network, not just from the Pi itself. Without it, you'd only be able to load the page locally on the Pi, which defeats the purpose.
Run it with:
python3 app.pyYou should see output similar to this (the last address will be your own Pi's IP):
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://192.168.1.45:5000
Press CTRL+C to quitThat development-server warning is normal for a home project. The production setup is covered in Step 10.
While developing, app.run(host="0.0.0.0", port=5000, debug=True) reloads the server whenever you save app.py and shows errors in the browser. Turn debug off before leaving it running: the debug page can run code from the browser.
Step 6: Finding Your Pi's IP Address
To reach the server from another device, you need your Pi's local IP address. Run:
hostname -IThis gives you something like 192.168.1.45. From any other device on the same Wi-Fi network — your laptop, your phone — open a browser and go to:
http://192.168.1.45:5000You should see your "Hello from your Raspberry Pi!" message right there on your screen.
If hostname -I prints more than one address, try the first one. Most home networks also let you use the Pi's hostname instead of an IP, for example http://raspberrypi.local:5000 (swap in your Pi's own hostname). If the page won't load, jump to the troubleshooting list at the end.
That moment, loading a page on your phone that's actually coming from a tiny board on your desk, is the one that makes this whole thing click for most people.
Step 7: Adding More Routes
Real projects need more than one page. Here's an expanded app.py with a JSON route and a route that receives data, for example sensor readings posted by an ESP32:
from datetime import datetime
from flask import Flask, jsonify, request
app = Flask(__name__)
readings = [] # kept in memory; use a file or database for anything permanent
@app.route("/")
def home():
return "Welcome to my Raspberry Pi server."
@app.route("/status")
def status():
return jsonify(status="online", time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
@app.route("/api/reading", methods=["POST"])
def add_reading():
data = request.get_json(silent=True)
if not data or "temperature" not in data:
return jsonify(error="expected JSON with a temperature"), 400
data["received"] = datetime.now().isoformat(timespec="seconds")
readings.append(data)
del readings[:-100] # keep the last 100
return jsonify(ok=True), 201
@app.route("/api/readings")
def list_readings():
return jsonify(readings)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)Test the POST route from another computer:
curl -X POST http://192.168.1.45:5000/api/reading -H "Content-Type: application/json" -d '{"device":"esp32-garage","temperature":24.5}'Then open /api/readings in a browser to see it. An ESP32 can send exactly this request with HTTPClient; point the POST example in the ESP32 HTTP GET and POST guide at http://<pi-ip>:5000/api/reading and the Pi becomes a small data collector for your sensors.
The Pi has no battery-backed clock (except the Pi 5 with a battery fitted), so it sets the time from the internet after booting. If /status shows a wrong time, the Pi probably isn't online yet.
Step 8: Controlling GPIO from the Browser
Because the Pi has GPIO pins, Flask can bridge a web page and real hardware: lights, relays, sensors.
Wiring. Connect the LED's longer leg (anode) through a 330 Ω resistor to GPIO18 (physical pin 12), and the shorter leg to a GND pin such as physical pin 14. The resistor is essential. The full pin map is in the Raspberry Pi GPIO pinout reference.
Use gpiozero. It's preinstalled on Raspberry Pi OS, it works on every model from the Zero to the Pi 5, and the --system-site-packages venv from Step 3 can already see it. (The older RPi.GPIO library doesn't work on the Pi 5; if you're following an old tutorial that uses it, install the rpi-lgpio drop-in.)
This version serves a page with two buttons. They send POST requests, because actions that change something shouldn't be plain links: browsers and link-preview bots happily open links on their own.
from flask import Flask, jsonify
from gpiozero import LED
app = Flask(__name__)
led = LED(18) # BCM 18 = physical pin 12
PAGE = """<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pi LED</title>
<h1>LED is <span id="state">{state}</span></h1>
<button onclick="setLed('on')">On</button>
<button onclick="setLed('off')">Off</button>
<script>
async function setLed(s) {
const r = await fetch('/led/' + s, {method: 'POST'});
document.getElementById('state').textContent = (await r.json()).state;
}
</script>"""
@app.route("/")
def index():
return PAGE.format(state="on" if led.is_lit else "off")
@app.route("/led/<state>", methods=["POST"])
def set_led(state):
if state == "on":
led.on()
elif state == "off":
led.off()
else:
return jsonify(error="use on or off"), 400
return jsonify(state=state)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)Run it, open http://<your-pi-ip>:5000 on your phone, and tap the buttons: the LED switches and the page updates without reloading. gpiozero releases the pin automatically when the program exits, so there's no cleanup code to forget.
A word of caution: the server listens on 0.0.0.0, so anyone on your network can open the page and press the buttons, and the same would be true for a relay or a motor. That's fine on a home network for an LED. Before you control anything that matters, add a login (for example HTTP Basic auth with the flask-httpauth package), and never port-forward the app to the internet; use a VPN such as Tailscale or WireGuard to reach it from outside.
Step 9: Keeping the Server Running After You Close the Terminal
Here's something that trips up almost everyone the first time: close the terminal or SSH session, and the Flask server dies with it. Fine for testing, useless for a project you want running permanently.
A quick fix for casual use is nohup:
nohup python3 app.py &This detaches the process from the terminal session, so closing your SSH connection won't kill it. Its output goes to a file called nohup.out, and you'll have to stop it yourself with pkill -f app.py.
For anything you want running reliably — especially something that should survive a reboot — a systemd service is the proper long-term solution. Create a file at /etc/systemd/system/flaskapp.service (for example with sudo nano /etc/systemd/system/flaskapp.service):
[Unit]
Description=Flask Web Server
Wants=network-online.target
After=network-online.target
[Service]
User=pi
WorkingDirectory=/home/pi/flask-project
ExecStart=/home/pi/flask-project/venv/bin/python3 app.py
Environment=PYTHONUNBUFFERED=1
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.targetnetwork-online.target makes the service wait until the network is actually up, which matters if your app connects to anything at startup. PYTHONUNBUFFERED=1 makes print() output show up in the logs immediately.
Change User=pi and the two /home/pi/... paths if your username or project folder is different. Then reload systemd, enable the service, and start it:
sudo systemctl daemon-reload
sudo systemctl enable flaskapp.service
sudo systemctl start flaskapp.serviceNow your Flask app starts automatically every time the Pi boots, and restarts itself if it ever crashes. Use this setup for any project you're not just testing.
Check that it's running with sudo systemctl status flaskapp.service, and follow its logs with journalctl -u flaskapp.service -f. If the service won't start, those logs will tell you why. A wrong path in ExecStart, a different username, or a missing package in the venv are the usual culprits. After editing app.py, apply the change with sudo systemctl restart flaskapp.service.
Step 10: A Production Server (When You Need One)
Flask's built-in server is fine for a home dashboard. If many people will use the app, or you want it sturdier, run it under Gunicorn:
pip install gunicorn
gunicorn --workers 1 --threads 4 --bind 0.0.0.0:5000 app:appThen put that command in ExecStart in place of python3 app.py. Keep one worker for apps that use GPIO: each Gunicorn worker is a separate process, and two processes can't own the same pin (the second fails with a GPIO busy error). Threads give you concurrency without that problem. For HTTPS and port 80, put Nginx in front of Gunicorn as a reverse proxy.
Troubleshooting
The page won't load from another device. Make sure both devices are on the same network (guest Wi-Fi often isolates devices from each other), that the server is actually running, and that you're using the Pi's current IP, since routers can hand out a different one after a reboot. Reserving the Pi's IP in your router settings fixes that for good.
Port conflicts. If you get an "Address already in use" error, something else — often a previous Flask process that didn't shut down cleanly — is sitting on port 5000. Find it with sudo ss -ltnp | grep 5000, then stop it with kill <PID>.
Forgetting host='0.0.0.0'. This is the single most common reason people think their server "isn't working" when really it's just only listening locally on the Pi.
Running Flask's built-in server in true production. Flask's default server is fine for development and small personal projects, but if you're exposing something to the wider internet rather than just your home network, look into pairing it with something like Gunicorn and Nginx down the line. For a home dashboard or local project, the built-in server is genuinely fine.
ModuleNotFoundError: No module named 'gpiozero' (or 'RPi'). The venv can't see the system GPIO libraries. Recreate it with python3 -m venv --system-site-packages venv, as in Step 3.
GPIO busy or pin already in use. Another copy of the app is still running (often the systemd service while you test by hand). Stop one: sudo systemctl stop flaskapp.service.
error: externally-managed-environment when running pip. You're outside the venv. Run source venv/bin/activate first.
Permission denied on port 80. Ports below 1024 need root. Keep port 5000, or put Nginx in front (Step 10).
Firewall blocking the port. If you've enabled ufw or another firewall, make sure port 5000 (or whichever port you're using) is allowed through.
Where This Can Go From Here
Once the basics are working, the project ideas open up fast:
- A live dashboard pulling temperature and humidity readings from a DHT22 sensor
- A simple home automation control panel for lights and relays
- A small personal API that other devices on your network can query
- A camera feed page using the Pi Camera Module
- A self-hosted to-do list or notes app for your home network
Flask's simplicity means you can start with something tiny and keep layering features on without rebuilding the foundation. If you'd rather wire flows together than write Python, Node-RED on the Raspberry Pi 5 is the visual alternative, and an MQTT broker on the same Pi is the better choice when many devices send frequent readings.
FAQ
Can a Raspberry Pi run a web server? Yes. Any Pi with networking can run Flask; a Pi 3, 4, 5 or Zero 2 W handles a home dashboard easily.
Why can't I open the page from my phone? Usually the app isn't using host="0.0.0.0", the phone is on a guest or mobile network, or the Pi's IP changed. See Troubleshooting.
Does this work on the Raspberry Pi 5? Yes, with gpiozero as shown. Only the old RPi.GPIO library fails on the Pi 5.
Flask or Django on a Pi? Flask for small dashboards and APIs; Django when you need user accounts, an admin site and a database from day one.
How do I make the address permanent? Reserve the Pi's IP in your router's DHCP settings, or use its hostname: http://raspberrypi.local:5000.
Can I access it from outside my home? Safely, through a VPN such as Tailscale or WireGuard. Don't port-forward a Flask app to the internet.
Related guides: Raspberry Pi GPIO pinout reference · Raspberry Pi 5 pinout · ESP32 HTTP GET and POST · Install Mosquitto on the Pi




