express

安装 express

1
npm i express

如果 vue-router 路由模式为 history,需额外安装 connect-history-api-fallback 中间件

新建文件 serve/main.js

1
2
3
4
5
6
7
8
9
const express = require('express')
const app = express()
const path = require('path')
+ const history = require('connect-history-api-fallback')

+ app.use(history())
app.use(express.static(path.resolve(__dirname, '../dist')))

app.listen(5678)

package.json

1
2
3
4
5
{
"scripts": {
"prod": "pm2 serve/main.js"
}
}

docker

确保已经安装 docker

1
2
docker -v
Docker version 20.10.12, build e91ed57

拉取 nginx 镜像

1
docker pull nginx

配置

vue-router + nginx,使用 history 模式刷新会报404错误,需更改 nginx 配置文件
https://router.vuejs.org/zh/guide/essentials/history-mode.html#nginx

拉取默认配置文件

1
docker run -d -p 8888:80 --name nginx nginx

新建文件夹 serve/confserve/logs

1
2
3
# 将 nginx 默认配置文件拷贝到本机
docker cp nginx:/etc/nginx/nginx.conf $PWD/serve/conf
docker cp nginx:/etc/nginx/conf.d/default.conf $PWD/serve/conf

修改 default.conf 文件

1
2
3
4
5
location / {
root /usr/share/nginx/html;
index index.html index.htm;
+ try_files $uri $uri/ /index.html;
}

部署容器

将配置文件挂载到项目容器内

1
2
3
4
5
6
7
docker run -d -p 8848:80 \
--name vue-music \
-v $PWD/dist:/usr/share/nginx/html \
-v $PWD/serve/conf/nginx.conf:/etc/nginx/nginx.conf \
-v $PWD/serve/conf/default.conf:/etc/nginx/conf.d/default.conf \
-v $PWD/serve/logs:/var/log/nginx
nginx