Docker Build not working


(Northern Elephant Consulting) #1

Hi, I hope this is the right place to post this in case anyone knows the answer to what might be a simple question.
I’m a beginner with Go and Docker. I have written a simple webapp that connects to a MySQL PaaS on GCP. When I run the code locally it works fine. I would like to containerize the application and run it as a container.
I get the following error;
main.go:16:5: cannot find package “go-sql-driver/mysql” in any of:
** /usr/local/go/src/go-sql-driver/mysql (from $GOROOT)**
** /go/src/go-sql-driver/mysql (from $GOPATH)**
The command ‘/bin/sh -c CGO_ENABLED=0 go build -o /bin/demo’ returned a non-zero code: 1
For the following dockerfile
FROM golang:1.11-alpine AS build

WORKDIR /src/
COPY main.go /form/ /src/*

RUN apk update -qq && apk add git
RUN go get -d github.com/go-sql-driver/mysql
RUN CGO_ENABLED=0 go build -o /bin/demo

FROM scratch
COPY --from=build /bin/demo /bin/demo
ENTRYPOINT ["/bin/demo"]

Thanks for any tips to stop me going mad!
Anthony


(Jakob Borg) #2

Is your code using modules? Why use a so old Go image?


(Northern Elephant Consulting) #4

I think this is the relevant code.

`import (
“database/sql”
“log”
“net/http”
“text/template”

_ "github.com/go-sql-driver/mysql"

)func dbConn() (db *sql.DB) {
dbDriver := “mysql”
dbUser := “root”
dbPass := “qwerty”
dbName := “go”
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@tcp(1.2.3.4:3306)/"+dbName)
if err != nil {
panic(err.Error())
}
return db
}`


(Karl Benedict) #5

Well clearly mysql driver isn’t in the container, are you installing the driver when you create the container?


(Northern Elephant Consulting) #6

Thanks for the response. As it’s the first time I’ve done this, I think I need a hand getting this done in the dockerfile.
`FROM golang:1.11-alpine AS build

WORKDIR /src/
COPY main.go /form/* /src/

RUN apk update -qq && apk add git
RUN go get -d github.com/go-sql-driver/mysql
RUN CGO_ENABLED=0 go build -o /bin/demo

FROM scratch
COPY --from=build /bin/demo /bin/demo
ENTRYPOINT ["/bin/demo"]`


(Northern Elephant Consulting) #7

Update. Got it to work with this. Now I would like to work on the scratch build.
`FROM golang:1.11-alpine AS build

WORKDIR /src/
COPY . /src/

RUN apk update -qq && apk add git
RUN go get “github.com/go-sql-driver/mysql

CMD go run /main.go
`


(Northern Elephant Consulting) #8

Doesn’t work. When I run the container I get this.
C:\Users\sesa82231\Desktop\Ant\go\testapi>docker container run -p 8080:8080 testapi main.go:16:5: cannot find package "go-sql-driver/mysql" in any of: /usr/local/go/src/go-sql-driver/mysql (from $GOROOT) /go/src/go-sql-driver/mysql (from $GOPATH)


(Karl Benedict) #9

There was a good question about using modules, are you using modules or there is a reason not to and to use GOPATH-based way of installing things?