Linux

How to Set Up a Web Application with Flask on Ubuntu

Setting up a Flask web application on Ubuntu involves several steps, including installing necessary packages, creating a virtual environment, and configuring a basic Flask app. Follow these steps to get started:

Step 1: Update and Install Required Packages

Ensure your system is up-to-date and install Python and pip:

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

Step 2: Create a Virtual Environment

Navigate to your project directory and create a virtual environment:

mkdir my_flask_app
cd my_flask_app
python3 -m venv venv

Activate the virtual environment:

source venv/bin/activate

Step 3: Install Flask

With the virtual environment activated, install Flask using pip:

pip install flask

Step 4: Create a Basic Flask Application

Create a file named app.py and add the following code:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

Step 5: Run the Flask Application

Run your Flask application using:

python app.py

Visit http://localhost:5000 in your web browser to see the application running.

Step 6: Configure Firewall (if necessary)

Allow traffic on port 5000:

sudo ufw allow 5000

Step 7: Deploy Flask App with Gunicorn (Optional)

Install Gunicorn:

pip install gunicorn

Run the app using Gunicorn for production:

gunicorn --bind 0.0.0.0:5000 app:app

Conclusion

You have successfully set up a Flask web application on Ubuntu. From here, you can expand your app with additional routes, templates, and styles for a complete web project.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button