I am pretty new to GoLang. I have a pretty simple dockerFile that is trying to build a goLang webservice.
FROM golang:alpine
WORKDIR /app/webservice_refArch
ADD . /app/webservice_refArch
RUN apk add git
RUN apk upgrade
RUN cd /app/webservice_refArch/ && go get webservice_refArch/restapi
RUN cd /app/webservice_refArch/cmd/reference-w-s-server && go build -o ../../server
ENTRYPOINT ./goapp
When the build runs it cannot find a local import.
go get webservice_refArch/restapi
The error that I get is:
package webservice_refArch/restapi: unrecognized import path "webservice_refArch/restapi" (import path does not begin with hostname)
When I run that same command on my local (in the same folder) it runs just fine. I am sure that I am missing something stupid but any thoughts on why it fails when running from docker would be appreciated.
It was because I wasn't copying over to my GOROOT location. As a result, when it was trying to find the local resource it wasn't in the GOROOT spot.
Changing the dockerFile to look like this worked...
FROM golang:alpine
WORKDIR /go
ADD . /go/src/webservice_refArch
RUN apk add git
RUN apk upgrade
RUN cd /go/src/webservice_refArch/ && go get ./...
RUN cd /go/src/webservice_refArch/cmd/reference-w-s-server && go build -o ../../server
ENTRYPOINT ./goapp
What is missing is to put your project under $GOPATH
and if you have local namespace it should also be under the same namespace $GOPATH/domain.com/
.
A proper way also to do that is to have a multi-stage builds. The basic principle involved with Multi-stage involves invoking a temporary container which can facilitate the application build, then copying the built assets out of that space into a container image that has the least amount of components required to run the app.
# builder
FROM golang:1-alpine AS builder
RUN apk add git ca-certificates --update
ENV SERVICE_NAME my_project
ENV NAMESPACE mydomain #if you don't use namespace space just ignore it and remove it from the following lines
ENV APP /src/${NAMESPACE}/${SERVICE_NAME}/
ENV WORKDIR ${GOPATH}${APP}
WORKDIR $WORKDIR
ADD . $WORKDIR
RUN go build
###############################################################
#image
FROM alpine
RUN apk add ca-certificates --update
ENV SERVICE_NAME webservice_refArch
ENV NAMESPACE my_domain #if you don't use namespace space just ignore it and remove it from the following lines
ENV APP /src/${NAMESPACE}/${SERVICE_NAME}/
ENV GOPATH /go
ENV WORKDIR ${GOPATH}${APP}
COPY --from=builder ${WORKDIR}${SERVICE_NAME} $WORKDIR
CMD ${WORKDIR}${SERVICE_NAME}
It isn't surely very nice, but if you have difficulties the first times you could copy only the executable file doing something like this:
FROM golang:alpine
RUN apk upgrade
COPY goapp .
CMD ./goapp
It is surely better to compile code inner the image, but it isn't necessary. So you could compile locally your code, and then move only the executable, and you won't have anymore problem like that.