03 build go docker image - xiaoxin01/Blog GitHub Wiki

本文介绍如何将go project构建到docker image中

直接上dockerfile(实际使用时,可以将基础镜像的版本替换为合适的版本):

···Dockerfile

Start from the latest golang base image

FROM golang:1.13.4 as builder

Add Maintainer Info

LABEL maintainer="Your name [email protected]"

Set go proxy in china

ENV GOPROXY=https://goproxy.io

Set the Current Working Directory inside the container

WORKDIR /app

Copy go mod and sum files

COPY go.mod go.sum ./

Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed

RUN go mod download

Copy the source from the current directory to the Working Directory inside the container

COPY . .

Build the Go app

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

######## Start a new stage from scratch ####### FROM alpine:3.10.3

RUN apk --no-cache add ca-certificates

WORKDIR /root/

Copy the Pre-built binary file from the previous stage

COPY --from=builder /app/main *.conf .

# Expose port 8080 to the outside world

EXPOSE 8080

Command to run the executable

CMD ["./main"]


利用multiple stage构建的image镜像仅包含需要的内容,会非常的小,节省大量空间。

## 参考

* [Building Docker Containers for Go Applications](https://www.callicoder.com/docker-golang-image-container-example/)
⚠️ **GitHub.com Fallback** ⚠️