简体   繁体   中英

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:

在此处输入图像描述

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

然后它应该工作。

It doenst work for me, still getting

[6/6] RUN go build -o bin/app cmd/app/main.go:
#10 0.171 go: github.com/gin-gonic/gin@v1.8.1 requires
#10 0.171 github.com/go-playground/validator/v10@v10.10.0: missing go.sum entry; to add it: #10 0.171 go mod download github.com/go-playground/validator/v10


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM