dockerfile
||

dokcerfile 之缓存 node_modules

如果直接拷贝代码到 /app 目录,由于每次编译时,代码都会改变,所以都需要重新下载依赖。

如果将依赖下载提到前面,就可以利用docker编译的缓存机制,达到加速编译的效果。

如果 package.json 改变,则会重新下载依赖。

Dockerfile 文件

FROM node:16.15.0 as build
# 将依赖文件拷贝到 tmp 文件夹
COPY ./package.json /tmp/package.json
# 下载依赖
RUN npm config set registry https://registry.npm.taobao.org && cd /tmp && npm install
# 将依赖拷贝到 /app
RUN mkdir /app && cp -a /tmp/node_modules /app/
WORKDIR /app
COPY ./ /app
RUN npm run build

FROM nginx
RUN mkdir /app
COPY --from=build /app/dist /app
COPY nginx.conf /etc/nginx/nginx.conf

nginx.conf 文件

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
  worker_connections  1024;
}
http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log  /var/log/nginx/access.log  main;
  sendfile        on;
  keepalive_timeout  65;
  server {
    listen       80;
    server_name  localhost;
    location / {
      root   /app;
      index  index.html;
      try_files $uri $uri/ /index.html;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }
}

类似文章