はじめに

イメージが肥大化しているhugoDockefileを修正して、イメージの軽量化を実践してみる。

環境

1
2
3
Mac OS Sonoma 14.5
Docker Desktop 4.30.0 (149282)
hugo v0.122.0+extended linux/amd64 BuildDate=unknown

現状

作成したイメージが2.29GBとかなり大きい・・・!
何回もイメージを作成したり、違うバージョンのhugoのイメージも使うとなると容量をかなり使ってしまっている。

イメージのサイズ

1
2
3
4
docker images | grep hugo
blog-hugo-hugo.slim   latest    390353669295   2 days ago     118MB
blog-hugo-hugo        latest    03b7c5dd095c   3 months ago   2.29GB
blog-hugo-tcardgen    latest    ee9b3f491796   3 months ago   1.52GB

Dockerfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
FROM alpine:3.19.1

# https://github.com/gohugoio/hugo/releases
ARG HUGO_VERSION=v0.122.0

# https://gohugo.io/installation/linux/
RUN apk add --update --no-cache go g++
RUN CGO_ENABLED=1 go install -tags extended github.com/gohugoio/hugo@${HUGO_VERSION}

ENV PATH="/root/go/bin:${PATH}"
WORKDIR /src

EXPOSE 1313
ENTRYPOINT [ "hugo", "server", "--bind", "0.0.0.0", "--port", "1313"]

修正

ChatGPTに聞いて修正してもらう。
幸い、マルチステージビルドを使えることを知っているので、これをキーワードに軽量化をする。

マルチステージビルドを使う

マルチステージビルドを使い、最終的な成果物のみをコピーしたイメージを作成する。
今回は、1つ目のステージでhugoに必要なものを入れてバイナリを作成しており、 2つ目のステージでhugoバイナリおよび起動に必要なランタイムであるlibstdc++を入れている。

Dockerfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Build stage
FROM golang:1.22-alpine3.19 AS build

# https://github.com/gohugoio/hugo/releases
ARG HUGO_VERSION=v0.122.0

# Install dependencies
RUN apk add --update --no-cache g++ git

# Build Hugo
RUN go install -tags extended github.com/gohugoio/hugo@${HUGO_VERSION}

# Final stage
FROM alpine:3.19.1

# Install necessary runtime dependencies
RUN apk add --no-cache libstdc++

# Copy Hugo binary from the build stage
COPY --from=build /go/bin/hugo /usr/local/bin/hugo

# Set up the environment and working directory
ENV PATH="/usr/local/bin:${PATH}"
WORKDIR /src

# Expose the port Hugo server will run on
EXPOSE 1313

# Set the entrypoint for the container
ENTRYPOINT [ "hugo", "server", "--bind", "0.0.0.0", "--port", "1313"]

https://chatgpt.com/share/3c691552-3ad3-41f0-955a-f33251d5b563

イメージ

1
2
3
4
docker images | grep hugo
blog-hugo-hugo        latest    41d66490712f   About a minute ago   127MB
blog-hugo-tcardgen    latest    31cd83d37a0e   22 minutes ago       1.58GB
blog-hugo-hugo.slim   latest    390353669295   2 days ago           118MB

めっちゃ削減できている・・・!
2.29GB→127MB

これがマルチステージビルドか〜
tcardgenの方も後で削減してみよう・・・!

参考

おわりに

今回はマルチステージビルドの理解を含めて軽量化を行なった。
今まで使ったことがなかった(というより理解できていなかった)が、ChatGPTのおかげでだいぶ楽に使えたし、具体的な完成したコードを見ることで理解が深まった。
軽量化の方法やマルチステージビルドの使い方が少しわかった気になれたので満足。