比如 alpine,整个镜像 5M 左右
RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai
goctl
工具GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/tal-tech/go-zero/tools/goctl
greet
项目下创建一个 hello
服务goctl api new hello
文件结构如下:
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
hello
目录下一键生成 Dockerfile
,命令如下goctl docker -go greet.go
Dockerfile
内容如下:
FROM golang:alpine AS builder
LABEL stage=gobuilder
ENV CGO_ENABLED 0
ENV GOOS linux
ENV GOPROXY https://goproxy.cn,direct
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 Asia/Shanghai
WORKDIR /app
COPY --from=builder /app/hello /app/hello
COPY --from=builder /app/etc /app/etc
CMD ["./hello", "-f", "etc/hello-api.yaml"]
greet
目录下 build
镜像docker build -t hello:v1 -f service/hello/Dockerfile .
hello v1 5455f2eaea6b 7 minutes ago 18.1MB
可以看出镜像大小约为 18M。
docker run --rm -it -p 8888:8888 hello:v1
$ 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
工具极大简化了 Dockerfile
文件的编写,提供了开箱即用的最佳实践,并且支持了模板自定义。
如果觉得工具有帮助,欢迎 star 🤝
https://github.com/tal-tech/go-zero