构建Docker映像时Go构建失败

I'm a little new to golang and I'm still trying to get my head around the difference between go run main.go and go build [-o] main.go.

I've build a little gin app to try out locally with docker and kubernetes.

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {

    r := gin.Default()

    r.GET("/healthz", func(c *gin.Context) {
        c.String(http.StatusOK, "")
    })

    r.GET("/readinez", func(c *gin.Context) {
        c.String(http.StatusOK, "")
    })

    r.Run() // listen and serve on 0.0.0.0:8080
} 

The app runs perfectly fine with go run main.go.

My Dockerfile:

FROM golang:latest
RUN mkdir /app
ADD . /app/
WORKDIR /app
RUN go build -o main .
CMD ["/app/main"]

It fails:

enter image description here

It is definitely in there and it also works when I go run main.go. What is the difference to build?

I'm not sure what to do here. Coming from a node background. This does drive a noobie somewhat mad... Sure there is an easy solution.

The program succeeds on your machine because you probably have the gin package installed. You can't assume a container will have it, and should install it explicitly. Just add the following line to your dockerfile before the go build line:

RUN go get github.com/gin-gonic/gin

It may have failed because you used gin, and the library cannot be found inside the container. Try to use glide or godep to vendoring third party library.

go get github.com/gin-gonic/gin

Then it should work.