Self-Hosting Flet Web Apps

This guide details how to self-host Flet applications on your own server, using NGINX as a reverse proxy.

Setup Flet Environment

  • **Dependencies:** Create a requirements.txt file listing application dependencies. Minimum requirement is flet.
  •     flet
        
  • **Virtual Environment:** Create and activate a Python virtual environment, then install requirements.
  •     python -m venv .venv
        source .venv/bin/activate
        pip install -r requirements.txt
        
  • **Sample Flet App:** A basic Flet application structure.
  •     import flet as ft

    def main(page: ft.Page): page.title = "My Flet app" page.add(ft.Text("Hello, world!"))

    if __name__ == "__main__": ft.run(main)

  • **Environment Variables:**
  • * FLET_WEB_APP_PATH: Configures the URL path for the Flet web app (e.g., /apps/myapp). Defaults to root. * FLET_SERVER_PORT: Sets the port for the Flet web app. Defaults to 8000. * Refer to [Environment Variables](https://docs.flet.dev/publish/web/dynamic-website/#environment-variables) for a complete list.

    Automatically Start Flet App

  • **systemd Unit File:** Create a flet.service file to manage the Flet app as a system service.
  • * **Example (flet.service):**
            [Unit]
            Description=Flet App
            After=network.target

    [Service] User=ubuntu Group=ubuntu WorkingDirectory=/home/ubuntu/flet-app Environment="PATH=/home/ubuntu/flet-app/.venv/bin" ExecStart=/home/ubuntu/flet-app/.venv/bin/python /home/ubuntu/flet-app/main.py

    [Install] WantedBy=multi-user.target

    * Adjust User, Group, WorkingDirectory, and paths according to your setup.
  • **Enable Service:** Link the service file and manage its lifecycle.
  •     cd /etc/systemd/system
        sudo ln -s /home/ubuntu/flet-app/flet.service
        sudo systemctl start flet
        sudo systemctl enable flet
        sudo systemctl status flet
        

    NGINX Proxy Setup

    Configure NGINX to proxy HTTP and WebSocket traffic to the Flet app.

  • **NGINX Configuration (within /etc/nginx/sites-available/*):**
  •     location / {
            proxy_pass         http://127.0.0.1:8000/;
            proxy_http_version 1.1;
            proxy_set_header   Upgrade $http_upgrade;
            proxy_set_header   Connection keep-alive;
            proxy_set_header   Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Proto $scheme;
        }

    location /ws { proxy_pass http://127.0.0.1:8000/ws; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }

  • **Post-Configuration:** Restart NGINX and access your app in a browser.