Skip to content

Instantly share code, notes, and snippets.

@embano1
Created September 23, 2019 14:54
Show Gist options
  • Save embano1/ce7ae7f6c8e268495085ce734eea961b to your computer and use it in GitHub Desktop.
Save embano1/ce7ae7f6c8e268495085ce734eea961b to your computer and use it in GitHub Desktop.
Dockerfile for Go modules and built cache efficiency

Also works across git branches if you keep the intermediate build images around, e.g. those <none> images in the docker images output.

FROM golang:1.12 AS builder

# enable Go modules support
ENV GO111MODULE=on

WORKDIR $GOPATH/src/github.com/myrepo/myapp

# manage dependencies
COPY go.mod .
COPY go.sum .
RUN go mod download

# Copy src code from the host and compile it
COPY cmd cmd
COPY pkg pkg
RUN CGO_ENABLED=0 GOOS=linux go build -a -o /myapp cmd/main.go

FROM alpine:3.9
RUN apk --no-cache add ca-certificates
COPY --from=builder /myapp /bin
CMD ["/bin/myapp"]
@vaniakov
Copy link

# manage dependencies
COPY go.mod .
COPY go.sum .
RUN go mod download

that's awesome, thanks!

@BoscoDomingo
Copy link

May I suggest this for security's sake:

# Don't run production as root
RUN addgroup --system --gid 1001 gogroup
RUN adduser --system --uid 1001 gouser
USER gouser

COPY --chown=gouser:gogroup --from=builder /myapp /bin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment