#!/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="https://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 http://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 http://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应用。
-