本篇文章主要帮助前端小白解决不会在服务器上部署前端打包的文件问题。以及如何nginx反向代理访问后端接口。主要使用docker+nginx的部署方式。
其中也加入了websocket的代理方式,在nginx.conf文件中的wpi路径代理上
vue项目打包
npm install
npm run build
通过ssh工具连接上服务器
需要确认下服务器中是否已经安装了docker,如没有安装,请参考博主另外的博客;
1. 网上拉取nginx镜像
docker pull nginx
2. 将项目文件放到服务器
#创建项目存放文件
mkdir -p /home/front/
# 将dist文件夹放入到/home/front文件夹下面
3. 编辑nginx.conf
vim /home/front/nginx.conf
server {
listen 80;
server_name localhost;
# 请求体的大小限制
client_max_body_size 50m;
# 日志文件存放地址
access_log /var/log/nginx/host.access.log main;
error_log /var/log/nginx/error.log error;
# 代理前端项目文件
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# 代理后端服务地址 192.168.1.1:9090为后端服务地址
location /api/ {
proxy_pass http://192.168.1.1:9090/;
}
# 代理后端websocket服务地址
location ^~ /wpi/ {
proxy_pass http://192.168.1.1:9090/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
4. 编写Dockerfile
vim /home/front/Dockerfile
FROM nginx:latest
# 将dist文件拷贝到容器内的 /usr/share/nginx/html
COPY dist/ /usr/share/nginx/html
# 将nginx.conf文件拷贝到容器中nginx的默认配置文件存放目录下
COPY nginx.conf /etc/nginx/conf.d/default.conf
生成镜像
# 在/home/front目录下执行命令
# front 为镜像的名称
docker build -t front .
显示successfully即表示部署成功
运行容器
5000为宿主机访问前端页面的端口
–name 表示容器名称
–restart=always 表示容器在宿主机开机自启动
-d 表示后台启动
-d 后面则为镜像名称
docker run --name front --restart=always -p 0.0.0.0:5000:80 -d front
查看容器
docker ps
访问前端
浏览器访问 服务器ip+5000端口,出现页面即表示部署成功。有问题可以留言哦。