#!/bin/bash
# 配置參數
APP_NAME="my_flask_app"
APP_PORT=5000
NGINX_CONF="/etc/nginx/sites-available/$APP_NAME"
NGINX_CONF_ENABLED="/etc/nginx/sites-enabled/$APP_NAME"
APP_DIR="/var/www/$APP_NAME"
REPO_URL="//github.com/yourusername/$APP_NAME.git"
DB_USER="root"
DB_PASSWORD="your_password"
DB_NAME="your_database"
# 安裝依賴
sudo apt-get update
sudo apt-get install -y git python3 python3-pip nginx mysql-server mysql-client
# 克隆應用代碼
if [ -d "$APP_DIR" ]; then
echo "Application directory already exists. Pulling latest changes..."
cd "$APP_DIR"
git pull
else
echo "Cloning application repository..."
git clone "$REPO_URL" "$APP_DIR"
cd "$APP_DIR"
fi
# 安裝Python依賴
pip3 install -r requirements.txt
# 數據庫遷移
echo "Running database migrations..."
python3 manage.py db upgrade
# 配置Nginx
cat <<EOF > "$NGINX_CONF"
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass //127.0.0.1:$APP_PORT;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
}
EOF
# 啟用Nginx配置
sudo ln -s "$NGINX_CONF" "$NGINX_CONF_ENABLED"
sudo systemctl restart nginx
# 啟動Flask應用
nohup python3 app.py > /dev/null 2>&1 &
echo "Deployment complete. Your app is running at //yourdomain.com"
腳本說明
-
安裝依賴:
-
安裝Git、Python、Pip、Nginx和MySQL。
-
-
克隆或更新應用代碼:
-
如果應用目錄已存在,則拉取最新代碼;否則克隆倉庫。
-
-
安裝Python依賴:
-
使用
pip3安裝requirements.txt中列出的Python依賴。
-
-
數據庫遷移:
-
假設你的Flask應用使用了Flask-Migrate進行數據庫遷移。運行
python3 manage.py db upgrade來應用數據庫遷移。
-
-
配置Nginx:
-
配置Nginx以代理到Flask應用。
-
-
啟動Flask應用:
-
在后臺啟動Flask應用。
-