我正在尝试测试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
它运行良好 . 然后我在我的go程序中添加了一个包“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”(导入路径不以hostname开头)
我试过Error 'import path does not begin with hostname' when building docker with local package但无法解决
任何帮助表示赞赏 .
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"
听起来很糟糕,就像你在
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>
此时,您的Dockerfile变得更加简单(并且SMALLER,检查生成的图像的图像大小),如:
这应该可以解决您的依赖性问题,并使您的运行时容器更小(可能<20MB),这将减少构建时间并提高部署速度 .