Tino
Tino

Reputation: 3368

Go build fails when building docker image

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.

Upvotes: 4

Views: 1585

Answers (3)

Mureinik
Mureinik

Reputation: 312257

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

Upvotes: 2

Huang Minghe
Huang Minghe

Reputation: 441

go get github.com/gin-gonic/gin

Then it should work.

Upvotes: 0

ngurajeka
ngurajeka

Reputation: 66

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.

Upvotes: 0

Related Questions