Docker golang包导入错误:导入path不以主机名开头

我正在testingdocker工人,并去项目。 这是我的dockerfile

FROM golang ARG app_env ENV APP_ENV $app_env COPY ./ /go/src/github.com/user/myProject/app WORKDIR /go/src/github.com/user/myProject/app RUN go get ./ RUN go build CMD if [ ${APP_ENV} = production ]; \ then \ app; \ else \ go get github.com/pilu/fresh && \ fresh; \ fi EXPOSE 8080 

它运行良好。 然后我添加了一个包“testpack”到我的去程序。

 package main import( "fmt" "time" "testpack" ) var now = time.Now() var election = time.Date(2016, time.November, 8, 0, 0, 0, 0, time.UTC) func main() { //get duration between election date and now tillElection := election.Sub(now) //get duration in nanoseconds toNanoseconds := tillElection.Nanoseconds() //calculate hours from toNanoseconds hours := toNanoseconds/3600000000000 remainder := toNanoseconds%3600000000000 //derive minutes from remainder of hours minutes := remainder/60000000000 remainder = remainder%60000000000 //derive seconds from remainder of minutes seconds := remainder/1000000000 //calculate days and get hours left from remainder days := hours/24 hoursLeft := hours%24 fmt.Printf("\nHow long until the 2016 US Presidential election?\n\n%v Days %v Hours %v Minutes %v Seconds\n\n", days, hoursLeft, minutes, seconds) } 

现在我跑=> docker build ./

我收到一个错误

包testpack:无法识别的导入path“testpack”(导入path不以主机名开头)

我试过这个错误'导入path不以主机名开始'当build立docker与本地包,但无法解决

任何帮助表示赞赏。

很明显,它试图从Internet上加载它,因为它没有在你的GOPATH中find“testpack”。

您没有向我们展示您的GOPATH设置或您复制“testing包”的位置,所以除了说“我错过了”之外,我只能告诉您。

阅读https://golang.org/cmd/go/#hdr-Relative_import_paths

试试

  • import "./testpack"
  • 在你的Dockerfile中设置GOPATH为“/ go”
    import "github.com/user/myProject/app/testpack"

这听起来像是在docker build过程中docker build应用程序时遇到问题。 这可能是一个依赖性问题(您有一个依赖项安装在您的本地$ GOPATH不安装在图像的去环境中)。 您可以在Dockerfile中的build命令之前安装依赖项,但我会非常认真地考虑在Dockerfile之外构build应用程序,并将可执行文件复制到构build的映像中。

Golang的最大优点之一是静态编译的可执行文件。 编译完成后,您应该能够在任何等效的体系结构中运行它。 默认情况下,go会尝试编译一个静态的可执行文件,但是如果你想强制执行它,你可以使用CGO_ENABLED env var来设置0,如下所示: CGO_ENABLED=0 go build -o <output.name> <file.to.build>

在这一点上,你的Dockerfile变得更简单了(而SMALLER,检查结果图像的图像大小),如下所示:

 FROM scratch #copy executable into container ADD <output.name> <output.name> #set entrypoint ENTRYPOINT [./<output.name>] #set exposed port EXPOSE 8080 

这应该解决您的依赖性问题,并使您的运行时容器更小(可能<20MB),这将减less构build时间,提高部署速度。