Vue+Django+Ngnix部署教程
一、背景介绍
- 我已经在本地调好了代码,并有一台linux系统的服务器/主机,想要将代码部署上去,保持持久运行,我该怎么做?
二、部署步骤
- LInux下载所需软件 ——> 配置Nginx转发 ——> 打包前端代码,上线前端代码 ——>拉取后端代码,运行
(一)Linux下载所需软件
- Nginx
- mysql
- python
注意:这里不再介绍如何下载这些软件,网上教程比比皆是,注意Mysql和Python版本应与开发环境保持一致,避免后续因版本不同报错。对Nginx版本没有特殊的要求。
(二)配置Nginx转发
- 打开
[Nginx目录]/conf
下的 nginx.conf文件,根据自己的需求,参照下面的代码进行配置
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8080;
server_name localhost;
location / {
root html/dist; # Vue打包后的路径
index index.html index.htm;
try_files $uri $uri/ /index.html; # 解决Vue页面刷新不保持原页面问题
}
# ↓ nginx收到/api开头的请求,转发到本机的5000端口,替换为你的后端服务器地址、端口
location /api {
proxy_pass http://localhost:5000/;
}
# ↑
# ↓ 这段为我自己对nginx转发的特殊需求
location ^~ /statics/screenshot/ {
root /home/project/vueProject/center-project/center-project/;
}
# ↑
#error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
(三)前端代码上线
- 使用
npm run build
打包Vue代码,在项目路径下会有一个dist文件夹,找到它,例如我的是E:\project\vueProject\center-project\center-project\dist
- 将上面的dist文件夹放入
[Nginx目录]/html/
目录下(当然!你可能也想到了,将上面的Nginx配置中的dist目录配置换成代码的位置,这样拉取代码就自动拉取了dist,对的,可以的)
(四)后端代码上线
- 拉取后端代码,可以先运行看下是否会报错,因为我没用docker,所以运行没问题的话,我直接简单放后台运行了,下面是运行的脚本和停止的脚本。
start.py 创建之后要给脚本赋权限之后才能使用
nohup python3 manage.py runserver 0.0.0.0:5000 > /dev/null 2>djo.out &
stop.sh 创建之后要给脚本赋权限之后才能使用
ps -aux | grep python3 | xargs kill -9
三、常见问题以及注意事项
(一)防火墙端口
- 一般CentOS默认打开防火墙,我们要对使用的端口放开限制
afirewall-cmd --state # 查看防火墙状态
firewall-cmd --zone=public --list-ports # 查看当前开放的端口
firewall-cmd --zone=public --add-port=8080/tcp --permanent # 开放8080端口,这里根据你前后端端口进行开放
systemctl restart firewalld.service # 重启防火墙,开放或关闭端口后需要重启防火墙
firewall-cmd --zone=public --remove-port=8080/tcp --permanent # 关闭8080端口