Next.jsをDocker Multi Stage Build
code:Dockerfile
FROM node:12.18.2-alpine as builder
WORKDIR /app
COPY package.json .
COPY yarn.lock .
COPY tsconfig.json .
RUN yarn install --production
FROM node:12.18.2-alpine
COPY --from=builder /app/node_modules /app/node_modules
COPY . .
EXPOSE 3000
Multi Stage Buildを利用しない場合
code:sh
$ docker build -f Dockerfile_dev .
Sending build context to Docker daemon 139.6MB
Step 1/9 : FROM node:12.18.2-alpine as builder
---> 057fa4cc38c2
Step 2/9 : WORKDIR /app
---> Running in f53a1b123569
Removing intermediate container f53a1b123569
---> 485a44f0ebd3
Step 3/9 : COPY package.json .
---> 5b58fb396840
Step 4/9 : COPY yarn.lock .
---> 8fbd886ebe49
Step 5/9 : COPY tsconfig.json .
---> dd9ea9f86d64
Step 6/9 : RUN yarn install --production
---> Running in 997d0a1b080d
yarn install v1.22.4
1/4 Resolving packages... info fsevents@1.2.13: The platform "linux" is incompatible with this module.
info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
info fsevents@2.1.3: The platform "linux" is incompatible with this module.
info "fsevents@2.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
3/4 Linking dependencies... 4/4 Building fresh packages... Done in 39.21s.
Removing intermediate container 997d0a1b080d
---> df1be46b2ed3
Step 7/9 : COPY . .
---> d91d29256d71
Step 8/9 : EXPOSE 3000
---> Running in f6db73858185
Removing intermediate container f6db73858185
---> ef8b3ac6a59f
---> Running in 003480d5135e
Removing intermediate container 003480d5135e
---> f9590e7cb54e
Successfully built f9590e7cb54e
$ docker image ls | grep f9590e7cb54e
<none> <none> f9590e7cb54e 16 seconds ago 431MB
<none> <none> f9590e7cb54e 16 seconds ago 431MB
Multi Stage Buildを利用
code:sh
$ docker build -f Dockerfile_dev .
Sending build context to Docker daemon 139.6MB
Step 1/11 : FROM node:12.18.2-alpine as builder
---> 057fa4cc38c2
Step 2/11 : WORKDIR /app
---> Using cache
---> 485a44f0ebd3
Step 3/11 : COPY package.json .
---> Using cache
---> 5b58fb396840
Step 4/11 : COPY yarn.lock .
---> Using cache
---> 8fbd886ebe49
Step 5/11 : COPY tsconfig.json .
---> Using cache
---> dd9ea9f86d64
Step 6/11 : RUN yarn install --production
---> Using cache
---> df1be46b2ed3
Step 7/11 : FROM node:12.18.2-alpine
---> 057fa4cc38c2
Step 8/11 : COPY --from=builder /app/node_modules /app/node_modules
---> fd4d5616ed40
Step 9/11 : COPY . .
---> 8964cefa6942
Step 10/11 : EXPOSE 3000
---> Running in 16526606b919
Removing intermediate container 16526606b919
---> e5a03c34f700
---> Running in a74809ecc5d4
Removing intermediate container a74809ecc5d4
---> 5ca7bf661d87
Successfully built 5ca7bf661d87
$ docker image ls | grep 5ca7bf661d87
<none> <none> 5ca7bf661d87 28 seconds ago 284MB
147MBイメージサイズが違っていることが確認できる。