docker 模板如下, 主要步骤如下
- 用 node14 作为镜像,打包前端文件
- 把上一个前端包,打进新的 nginx 镜像中
上述做法 1 点会留下一个无用的打包镜像,需要手动删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| FROM node:14 as build
RUN npm config set registry https://registry.npm.taobao.org/
RUN yarn config set registry https://registry.npm.taobao.org/
WORKDIR /app
COPY package*.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn build
FROM nginx:1.20
COPY --from=build /app/dist /usr/share/nginx/html
COPY ./conf/nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
|
nginx.conf 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| events { worker_connections 1024; }
http { server { listen 80; server_name localhost;
root /usr/share/nginx/html/; # 根目录设置为/usr/share/nginx/html/
include mime.types; default_type application/octet-stream;
#允许客户端跨域访问 # add_header Access-Control-Allow-Origin *; # add_header Access-Control-Allow-Headers X-Requested-With; # add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
sendfile on;
keepalive_timeout 65;
# 忽略favicon.ico请求 location = /favicon.ico { log_not_found off; access_log off; }
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|svg)$ { expires 30d; }
location ~ .*\.(js|css)?$ { expires 12h; }
location ~ /\. { deny all; }
# 路由配置 location / { try_files $uri $uri/ /index.html; }
# gzip压缩 gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; } }
|