Golang Docker 示例

2018年11月08日

源代码 hello.go

1package main
2
3import "fmt"
4
5func main() {
6	fmt.Println("Hello World")
7}

Dockerfile

一步构建

1FROM golang:1.11-alpine
2WORKDIR /go/src/helloworld
3COPY . .
4RUN go install -v ./
5CMD ["helloworld"]

多阶段构建

优点是最终生成的 image 很小。

 1FROM golang:1.11-alpine
 2WORKDIR /go/src/helloworld
 3COPY . .
 4RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
 5
 6FROM alpine:latest
 7RUN apk --no-cache add ca-certificates
 8WORKDIR /root
 9COPY --from=0 /go/src/helloworld/app .
10CMD ["./app"]

打包命令

docker build -t go-helloworld .

运行实例

docker run --rm go-helloworld