For example alpine
, it's only about 5MB.
RUN apk add --no-cache tzdata
ENV TZ America/New_York
- the first stage to build the binary, ensure the binary is dev box independent
- use the binary in the first stage to build the final image
-
first of all, install the tool
goctl
GO111MODULE=on go get -u github.com/tal-tech/go-zero/tools/goctl
-
in project
greet
, create a service calledhello
goctl api new hello
file structure listed below:
greet ├── go.mod ├── go.sum └── service └── hello ├── etc │ └── hello-api.yaml ├── hello.api ├── hello.go └── internal ├── config │ └── config.go ├── handler │ ├── hellohandler.go │ └── routes.go ├── logic │ └── hellologic.go ├── svc │ └── servicecontext.go └── types └── types.go
-
in dir
hello
, one shot to generateDockerfile
goctl docker -go hello.go
the content of
Dockerfile
like:FROM golang:alpine AS builder LABEL stage=gobuilder ENV CGO_ENABLED 0 ENV GOOS linux WORKDIR /build/zero ADD go.mod . ADD go.sum . RUN go mod download COPY . . COPY service/hello/etc /app/etc RUN go build -ldflags="-s -w" -o /app/hello service/hello/hello.go FROM alpine RUN apk update --no-cache && apk add --no-cache ca-certificates tzdata ENV TZ America/New_York WORKDIR /app COPY --from=builder /app/hello /app/hello COPY --from=builder /app/etc /app/etc CMD ["./hello", "-f", "etc/hello-api.yaml"]
-
in dir
greet
,build
the final imagedocker build -t hello:v1 -f service/hello/Dockerfile .
-
check the image
hello v1 5455f2eaea6b 7 minutes ago 18.1MB
the image size is like 18MB.
-
start the service
docker run --rm -it -p 8888:8888 hello:v1
-
test the service
$ curl -i http://localhost:8888/from/you HTTP/1.1 200 OK Content-Type: application/json Date: Thu, 10 Dec 2020 06:03:02 GMT Content-Length: 14 {"message":""}
goctl
greatly simplifies the writing of Dockerfile
. The generated Dockerfile
is state-of-art and can be used directly. Also, you can customized the Dockerfile
template in $HOME/.goctl/docker
if necessary.
If it helps, welcome to star the project. 🤝