选择合适的基础镜像可以减小镜像大小,并确保基础镜像的安全性和更新性。Alpine、Ubuntu Minimal 等轻量级基础镜像是常用选择。
#阶段1命名为builder
FROM golang:1.16 as builder
WORKDIR /go/src
COPY app.go ./
RUN go build app.go -o myapp
#阶段2
FROM builder as builder_ex
ADD dest.tar ./
...
docker 多阶段构建
比如 node package.json 不变既可以直接使用缓存
FROM node:18.18.2-buster-slim
WORKDIR /data/srv/
ENV TZ Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY package*.json ./
COPY patches ./
RUN npm config set registry <https://registry.npmmirror.com>
RUN npm_config_sharp_binary_host="<https://npmmirror.com/mirrors/sharp>" npm_config_sharp_libvips_binary_host="<https://npmmirror.com/mirrors/sharp-libvips>" npm install sharp
RUN npm install \\
&& npm install pm2 -g
COPY . ./
RUN npm run build
# RUN apt-get update \\
# && apt-get -y install procps \\
# && apt-get install -y vim
COPY ecosystem.config.js .
EXPOSE 3000
CMD ["pm2-runtime", "ecosystem.config.js"]