共计 1595 个字符,预计需要花费 4 分钟才能阅读完成。
1. Dockerfile 一些额定留神点
- 抉择最简略的镜像
比方 alpine,整个镜像 5M 左右
-
设置镜像时区
RUN apk add --no-cache tzdata ENV TZ Asia/Shanghai
2. 多阶段构建
- 第一阶段构建否则构建出可执行文件,确保构建过程独立于宿主机
- 第二阶段将第一阶段的输入作为输出,构建出最终的极简镜像
3. 残缺 Dockerfile 编写过程
- 首先装置
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 ├── Dockerfile ├── 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
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache 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":""}
4. 总结
goctl
工具极大简化了 Dockerfile
文件的编写,提供了开箱即用的最佳实际,并且反对了模板自定义。
如果感觉工具有帮忙,欢送 star ????
5. 我的项目地址
https://github.com/tal-tech/go-zero
我的项目地址:
https://github.com/tal-tech/go-zero