Multiple Flask app setup

Flask multiple app hosting

🧰 Prerequisites

  • A Linux server (Ubuntu 20.04+ recommended)
  • Root or sudo access
  • Python 3.8+ and pip installed
  • Flask apps ready (e.g., /var/www/app1 and /var/www/app2)

🧩 Step 1: Install Dependencies

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

βš™οΈ Step 2: Setup Each Flask App Separately

Repeat the following steps for each app (e.g., app1, app2).

Example for App1:

sudo mkdir -p /var/www/app1
cd /var/www/app1
python3 -m venv venv
source venv/bin/activate
pip install flask gunicorn

Create a simple app:

nano /var/www/app1/app.py
from flask import Flask
app = Flask(**name**)

@app.route('/')
def home():
    return "Hello from App 1!"

if __name__ == '__main__':
    app.run()

Test it:

python app.py

Visit http://<your_server_ip>:5000

πŸš€ Step 3: Configure Gunicorn for Each App

Gunicorn will serve your Flask apps before Nginx proxies to them.

Create a systemd service for each app.

For app1:

sudo nano /etc/systemd/system/app1.service
[Unit]
Description=Gunicorn instance to serve app1
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/app1
Environment="PATH=/var/www/app1/venv/bin"
ExecStart=/var/www/app1/venv/bin/gunicorn --workers 3 --bind unix:/var/www/app1/app1.sock app:app

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl start app1
sudo systemctl enable app1

Repeat for app2, updating paths and socket names.

🌐 Step 4: Configure Nginx to Serve Multiple Apps

Edit or create new Nginx server blocks for each app.

Example: app1.conf

sudo nano /etc/nginx/sites-available/app1
server {
listen 80;
server_name app1.example.com;

    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/app1/app1.sock;
    }

}

For app2.conf

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

    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/app2/app2.sock;
    }

}

Enable the configurations:

sudo ln -s /etc/nginx/sites-available/app1 /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/app2 /etc/nginx/sites-enabled/

Test Nginx and reload:

sudo nginx -t
sudo systemctl reload nginx

Use Certbot for free HTTPS (Let’s Encrypt):

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d app1.example.com -d app2.example.com

Certbot will auto-configure HTTPS for each domain.

🧠 Step 6: Verify Everything

Check systemd services:

sudo systemctl status app1
sudo systemctl status app2

Check logs:

sudo journalctl -u app1 -f

Visit your apps:

http://app1.example.com β†’ App1

http://app2.example.com β†’ App2

⚑ Alternative Options

If you prefer not to manage systemd and Nginx manually, consider:

  • Docker Compose β€” run each Flask app in its own container.
  • Caddy Server β€” auto-manages reverse proxy + HTTPS.
  • Gunicorn + Supervisor β€” instead of systemd for process management.

Leave a Reply