1、镜像优化
镜像优化:
- 减少层数
- 多阶段构建
- 利用构建缓存
- 运行的指令放到一层
镜像区分:
- Slim:通常只安装运行特定工具所需的最小包
- Alpine: 专门为容器构建的操作系统,体积较小,对 glibc 的支持有限
- Debian:功能齐全的操作系统,体积比上面两个大些
2、多阶段构建
Java 多阶段构建样例:
FROM harbor.bgxwz.com/base/openjdk:17-build as builder
RUN mkdir /build
ADD . /build/
RUN cd /build && gradle assemble
FROM harbor.bgxwz.com/base/openjdk:17-jdk
ARG workdir=app
WORKDIR /$workdir
COPY --from=builder /build/build/libs/app.jar /$workdir/app.jar
Node 多阶段构建样例:
FROM harbor.bgxwz.com/base/node:14 as builder
RUN mkdir /build
ADD . /build/
RUN cd /build && yarn install && yarn run build
FROM harbor.bgxwz.com/base/nginx:1.23-alpine
RUN sed -i 's/worker_processes 1/worker_processes auto/;/gzip/a\ server_tokens off;' /etc/nginx/nginx.conf
COPY --from=builder /build/dist/ /usr/share/nginx/html/
CMD /bin/sh -c 'nginx -g "daemon off;"'
Go 多阶段构建样例:
FROM harbor.bgxwz.com/base/golang:1.18 as builder
WORKDIR /build
COPY . /build/
RUN go build -mod=vendor -o app
FROM harbor.bgxwz.com/base/alpine:3.16
WORKDIR /app
COPY --from=builder /app/build/app bin/
ENTRYPOINT ["/app/bin/app"]
Python 多阶段构建样例:
FROM harbor.bgxwz.com/base/python:3.9-slim AS builder
WORKDIR /build
ADD requirements.txt /build/
RUN pip install --no-cache-dir -r requirements.txt --install-option="--prefix=/build/"
FROM harbor.bgxwz.com/base/python:3.9-alpine
WORKDIR /app
COPY --from=builder /build /app
ENTRYPOINT ["python3", "app.py"]
评论区