shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.95k stars 509 forks source link

多阶段构建并不需要 docker-compose #785

Closed hkongm closed 2 years ago

hkongm commented 2 years ago

按照这篇 https://q.shanyue.tech/deploy/cra-docker.html

经过实验,一个 Dockerfile 就搞定多阶段构建

docker build 就是分步就出来一个 20 多 M 的 image

用不到 docker-compose.yaml

$ docker build -t hkongm/nodespa:step -f ./simple.Dockerfile .
[+] Building 17.5s (14/14) FINISHED                                                                     
 => [internal] load build definition from simple.Dockerfile                                        0.0s
 => => transferring dockerfile: 51B                                                                0.0s
 => [internal] load .dockerignore                                                                  0.0s
 => => transferring context: 34B                                                                   0.0s
 => [internal] load metadata for docker.io/library/nginx:alpine                                    1.1s
 => [internal] load metadata for docker.io/library/node:14-alpine                                  1.2s
 => [builder 1/6] FROM docker.io/library/node:14-alpine@sha256:6b87d16e4ce20cacd6f1f662f66c821e4c  0.0s
 => [stage-1 1/2] FROM docker.io/library/nginx:alpine@sha256:a74534e76ee1121d418fa7394ca930eb6744  0.0s
 => [internal] load build context                                                                  0.0s
 => => transferring context: 2.19kB                                                                0.0s
 => CACHED [builder 2/6] WORKDIR /code                                                             0.0s
 => CACHED [builder 3/6] ADD package.json package-lock.json /code/                                 0.0s
 => CACHED [builder 4/6] RUN npm i                                                                 0.0s
 => [builder 5/6] ADD . /code                                                                      0.0s
 => [builder 6/6] RUN npm run build                                                               15.3s
 => CACHED [stage-1 2/2] COPY --from=builder code/build /usr/share/nginx/html                      0.0s 
 => exporting to image                                                                             0.0s 
 => => exporting layers                                                                            0.0s 
 => => writing image sha256:c7d200ef1d0d62075c6de5e63df1d1b1c5c4cfdb9794e25dd144e88baeeb1291       0.0s 
 => => naming to docker.io/hkongm/nodespa:step                                                     0.0s 

实测 build 后 serve 的镜像文件 304.51 MB

分布构建的镜像文件 23.97 MB

shfshanyue commented 2 years ago

这个确实不需要 docker-compose,docker-compose 只不过是 docker build 不用写那么多参数,如同 webpack.config.js 与 webpack-cli 对比