Docker golang包导入错误:导入路径不以hostname开头

时间:2017-09-13 16:23:01

标签: docker go

我正在尝试测试docker并去项目。这是我的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 U.S. Presidential election?\n\n%v Days %v Hours %v Minutes %v Seconds\n\n", days, hoursLeft, minutes, seconds)

}

现在我跑=> docker build ./

我收到错误

package testpack:无法识别的导入路径" testpack" (导入路径不以主机名开头)

我试过这个Error 'import path does not begin with hostname' when building docker with local package但无法解决

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

显然是尝试从Internet加载它,因为它没有在你的GOPATH中找到“testpack”。

您没有向我们展示您的GOPATH设置或您将“testpack”复制到的位置,除了说“它已丢失”之外,我可以告诉您。

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

尝试

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

答案 1 :(得分:0)

听起来很像你在docker build进程中构建应用程序时出现问题。这可能是依赖性问题(您在本地$ GOPATH上安装了依赖项,但未安装在映像的go环境中)。您可以在Dockerfile中的build命令之前安装依赖项,但我会非常认真地考虑在Dockerfile之外构建应用程序,并在构建时将可执行文件复制到映像中。

Golang的一大优势是静态编译的可执行文件。编译完成后,您应该可以在任何等效的体系结构中运行它。默认情况下,go会尝试编译一个静态可执行文件,但是如果你想强制执行它(并且你没有做任何与CGO有关的事情)你可以将CGO_ENABLED env var设置为0,如下所示:CGO_ENABLED=0 go build -o <output.name> <file.to.build> < / p>

此时,您的Dockerfile变得更加简单(并且SMALLER,检查生成的图像的图像大小),如:

FROM scratch

#copy executable into container
ADD <output.name> <output.name>

#set entrypoint
ENTRYPOINT [./<output.name>]

#set exposed port
EXPOSE 8080

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