加速Docker构建以进行Golang供应

I have a Dockerfile which is FROM golang:1.6-alpine. I’d like to use the docker images cache as much as possible while performing docker build to speed things up.

For this, I thought I’d add ADD vendor /go/src/…/mypackage/vendor as one of the first steps, and eventually run go install -v …/mypackage. However, this causes the vendored packages (which are the bulk of the build time) to only be built then.

Is there anyway to explicitly build all vendored packages (i.e. sources inside a …/vendor dir), but only them?

I'd like my Dockerfile to look something like this:

FROM golang:1.6-alpine

ADD vendor /go/src/github.com/myuser/package/vendor
# missing: magic command to build only the vendored packages above

ADD *.go /go/src/github.com/myuser/package
RUN go install -v "github.com/myuser/package
  • In the host (outside the docker container), the packages are still stored in the /vendor folder. This allows for convenient management of these dependencies. Personally I use godep to manage this.
  • Inside the container, instead of adding the /vendor folder to be a subdir of my package, I add all the packages inside the /vendor folder under the source directory /go/src directly.
  • Since go's vendoring is all about changing import paths, and build artifacts are stored in the /pkg directory regardless of whether they were 'vendored' or not, this solution is stable.
  • In order to enjoy the speed-up, and not having to rebuild all vendored packages unless they were changed, the Dockerfile runs a go install ./... on the src dir after adding the vendor folder, then proceeds with the rest of the build.

Dockerfile:

FROM golang:1.6-alpine

# Add and install all vendored packages.
ADD vendor /go/src/
RUN cd /go/src && go install -v ./...

# ...

# Add and install our package's source files, without the vendor folder
ADD *.go "/go/src/github.com/myuser/mypackage"
RUN go install -v "/go/src/github.com/myuser/mypackage"