How to Run Flask Server on Raspberry Pi: Step-by-Step Guide
To run a
Flask server on Raspberry Pi, first install Flask using pip3 install flask. Then create a Python script with your Flask app and run it using python3 your_script.py to start the server accessible on your Pi's IP address.Syntax
Here is the basic syntax to run a Flask server on Raspberry Pi:
pip3 install flask: Installs Flask using Python 3's package manager.python3 app.py: Runs your Flask application script.app.run(host='0.0.0.0', port=5000): Starts the Flask server accessible on all network interfaces at port 5000.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello, Raspberry Pi!" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Example
This example shows a simple Flask app running on Raspberry Pi that responds with a greeting message when accessed.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello, Raspberry Pi!" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Output
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
Common Pitfalls
Common mistakes when running Flask on Raspberry Pi include:
- Not setting
host='0.0.0.0'inapp.run(), which makes the server only accessible from localhost. - Forgetting to install Flask with
pip3for Python 3. - Running the script with
pythoninstead ofpython3if Python 3 is required. - Firewall or network settings blocking port 5000.
python
## Wrong way (server only accessible locally): # app.run() ## Right way (server accessible on network): app.run(host='0.0.0.0', port=5000)
Quick Reference
Summary tips for running Flask on Raspberry Pi:
- Use
pip3 install flaskto install Flask. - Run your app with
python3 app.py. - Set
host='0.0.0.0'inapp.run()to allow network access. - Access the server via
http://[Raspberry_Pi_IP]:5000from other devices. - Check firewall and network settings if connection fails.
Key Takeaways
Install Flask on Raspberry Pi using pip3 before running your app.
Set host='0.0.0.0' in app.run() to make the server accessible on your network.
Run your Flask app with python3 to ensure Python 3 compatibility.
Access your Flask server from other devices using your Pi's IP and port 5000.
Check network and firewall settings if you cannot connect to the server.