在服务器上部署 Python 接口服务和 Vue 前端服务项目
环境准备
-
服务器环境
- 系统:Linux (如 CentOS 7/8 或 Ubuntu 20.04)
- 安全组:确保开放必要的端口(默认 HTTP 为 80,HTTPS 为 443)
-
基本软件安装
sudo yum update -y # CentOS sudo apt update -y # Ubuntu sudo yum install git -y # 或者 apt install git -y
-
安装 Nginx 作为前端代理
sudo yum install nginx -y # CentOS sudo apt install nginx -y # Ubuntu sudo systemctl start nginx sudo systemctl enable nginx
部署 Python 接口服务
-
上传代码
通过git clone
下载项目到服务器:git clone <你的Python接口仓库地址> /www/api cd /www/api
-
创建 Python 虚拟环境并安装依赖
sudo yum install python3-venv -y # CentOS python3 -m venv venv source venv/bin/activate pip install -r requirements.txt
-
运行服务测试
假设使用 FastAPI 框架:uvicorn main:app --host 0.0.0.0 --port 8000
访问
http://<服务器IP>:8000/docs
验证是否运行成功。 -
使用
systemd
配置为后台服务
创建/etc/systemd/system/api.service
文件:[Unit] Description=Python API Service After=network.target [Service] User=root WorkingDirectory=/www/api ExecStart=/www/api/venv/bin/uvicorn main:app --host 0.0.0.0 --port 8000 Restart=always [Install] WantedBy=multi-user.target
启动服务:
sudo systemctl daemon-reload sudo systemctl start api.service sudo systemctl enable api.service
部署 Vue 前端服务
-
上传前端代码并打包
git clone <你的Vue项目仓库地址> /www/vue cd /www/vue npm install npm run build
生成的静态资源通常在
/www/vue/dist/
目录下。 -
配置 Nginx 代理
编辑/etc/nginx/conf.d/vue.conf
:server { listen 80; server_name yourdomain.com; # 替换为实际域名或IP location / { root /www/vue/dist; index index.html; try_files $uri $uri/ /index.html; } location /api/ { proxy_pass http://127.0.0.1:8000/; 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; } }
-
重启 Nginx
sudo nginx -t # 检查配置是否正确 sudo systemctl restart nginx
验证服务
- 打开浏览器访问
http://yourdomain.com
查看 Vue 页面是否正常。 - 使用浏览器调试工具或 Postman 测试
/api/
接口是否能正常访问。
优化与安全
-
启用 HTTPS
安装 Certbot 并申请 SSL 证书:sudo yum install certbot python3-certbot-nginx -y sudo certbot --nginx
-
性能优化
- Python 后端可以使用
gunicorn
+uvicorn.workers.UvicornWorker
。 - Nginx 启用缓存和压缩。
- Python 后端可以使用
完成这些步骤后,你的 Python 接口服务和 Vue 前端服务将成功运行在服务器上。