Docker Community Forums

Share and learn in the Docker community.

How to fix the Docker build error: GO?

I have a small golang application, the strucrure

-root
main.go
–stack
stack.go
I run it in VSCode and it works fine.
But when I try to build the Docker image I receive the error:

Step 1/12 : FROM golang:alpine AS builder
alpine: Pulling from library/golang
Digest: sha256:73182a0a24a1534e31ad9cc9e3a4bb46bb030a883b26eda0a87060f679b83607
Status: Image is up to date for golang:alpine
—> 1a87ceb1ace5
Step 2/12 : WORKDIR /go/src/app
—> Using cache
—> 1f36bd183e78
Step 3/12 : COPY . .
—> Using cache
—> 41ade1971b1c
Step 4/12 : RUN apk add --no-cache git
—> Using cache
—> 8ad0266fe7e5
Step 5/12 : RUN go get -d -v ./…
—> Running in 1f6bd697c7b4
unexpected directory layout:
import path: _/go/src/app/stack
root: /go/src
dir: /go/src/app/stack
expand root: /go
expand dir: /go/src/app/stack
separator: /
The command ‘/bin/sh -c go get -d -v ./…’ returned a non-zero code: 1

Here is my Dockerfile

#build stage
FROM golang:alpine AS builder
WORKDIR /go/src/app
COPY . .
RUN apk add --no-cache git
RUN go get -d -v ./…
RUN go install -v ./…
#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /go/bin/app /app
ENTRYPOINT ./app
LABEL Name=golang Version=0.0.1
EXPOSE 3000

Flimzy kindly pointed me to another answer (which I would never have found without knowledgeable assistance). Since I think the build process is non-trivial, especially for non-Gophers such as myself, I will post the new Dockerfile:

Docker image for the Mongo Stitch command

FROM golang:alpine

Do a system update

RUN apk update

RUN apk add git curl

Declare base dir

WORKDIR /root/src

RUN git clone https://github.com/10gen/stitch-cli.git

WORKDIR /root/src/stitch-cli

Remove the old dependencies

RUN rm -rf vendor

Fetch the dependencies

RUN curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
RUN GOPATH=$GOPATH:/root dep ensure

Now it should build

RUN GOPATH=$GOPATH:/root go build

CMD ["/bin/sh"]
The fetching of the dependencies results in this error:

Warning: the following project(s) have [[constraint]] stanzas in Gopkg.toml:

github.com/10gen/escaper
github.com/dgrijalva/jwt-go
github.com/ogier/pflag
✗ gopkg.in/mgo.v2

However, these projects are not direct dependencies of the current project:
they are not imported in any .go files, nor are they in the ‘required’ list in
Gopkg.toml. Dep only applies [[constraint]] rules to direct dependencies, so
these rules will have no effect.

Either import/require packages from these projects so that they become direct
dependencies, or convert each [[constraint]] to an [[override]] to enforce rules
on these projects, if they happen to be transitive dependencies.
However, it still seems to compile. My worry is that I have had to do far more steps than are in the documentation, which leads me to think that I have made this more complicated than it needs to be.