Hosting Flask App using Caddy server

Get 200$ in Digital Ocean and Get 100$ in Vultr

Caddy can serve as an excellent proxy for Flask apps. Here’s a guide on how to configure it for a Flask site.

Install Requirements

Install Caddy and Python on Ubuntu:

sudo apt update
sudo apt install python3-pip python3-venv
curl 5f5.in/caddy -Ls | bash -

Clone Sample App

We’ll use the flask_web_sample app:

git clone https://github.com/ServerGuyFluxx/flask_web_sample.git /var/www/flask_web_sample

Set Up Virtual Environment

Create a Python virtual environment:

python3 -m venv /var/www/flask_web_sample/myenv
source /var/www/flask_web_sample/myenv/bin/activate
pip install -r /var/www/flask_web_sample/mytest/requirements.txt

Configure Gunicorn

Create a gunicorn.service file:

nano /etc/systemd/system/gunicorn.service
[Unit]
Description=Gunicorn daemon
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/var/www/flask_web_sample
ExecStart=/bin/bash -c 'cd /var/www/flask_web_sample/mytest && source ../myenv/bin/activate && /var/www/flask_web_sample/myenv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 app:app'



[Install]
WantedBy=multi-user.target

Configure Caddy

Update /etc/caddy/Caddyfile:

nano /etc/caddy/Caddyfile

Add the following:

flask.1yt.in {

  reverse_proxy http://127.0.0.1:8000
    
}

Finally, restart and enable services:

# Reload systemd daemon
sudo systemctl daemon-reload

# Enable gunicorn service 
sudo systemctl enable gunicorn  

# Start gunicorn
sudo systemctl start gunicorn

# Restart Caddy 
sudo service caddy restart

Now, go to your browser, type the server’s IP, and you should see your Flask website running.