我正在尝试使用Docker的Go客户端构建映像。这是我正在运行的Go程序:
func main() {
ctx := context.Background()
cli, err := client.NewEnvClient()
if err != nil {
log.Fatal(err, " :unable to init client")
}
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
defer tw.Close()
dockerFile := "Dockerfile"
dockerFileReader, err := os.Open("./Dockerfile")
if err != nil {
log.Fatal(err, " :unable to open Dockerfile")
}
readDockerFile, err := ioutil.ReadAll(dockerFileReader)
if err != nil {
log.Fatal(err, " :unable to read dockerfile")
}
tarHeader := &tar.Header{
Name: dockerFile,
Size: int64(len(readDockerFile)),
}
err = tw.WriteHeader(tarHeader)
if err != nil {
log.Fatal(err, " :unable to write tar header")
}
_, err = tw.Write(readDockerFile)
if err != nil {
log.Fatal(err, " :unable to write tar body")
}
dockerFileTarReader := bytes.NewReader(buf.Bytes())
imageBuildResponse, err := cli.ImageBuild(
ctx,
dockerFileTarReader,
types.ImageBuildOptions{
Dockerfile: dockerFile,
Tags: []string{"devbuild"},
Remove: true})
if err != nil {
log.Fatal(err, " :unable to build docker image")
}
defer imageBuildResponse.Body.Close()
_, err = io.Copy(os.Stdout, imageBuildResponse.Body)
if err != nil {
log.Fatal(err, " :unable to read image build response")
}
}
它将Dockerfile
(位于当前目录中)放置在tar
文件中,并使用cli.ImageBuild
构建映像。此解决方案来自post,而我的Dockerfile
看起来像这样:
FROM alpine:latest
WORKDIR /gopath/src/build
COPY ./binary_build/ /usr/local/bin/
在最后一步,我不断出错:
{"stream":"Step 3/3 : COPY /binary_build/ /usr/local/bin/"}
{"stream":"\n"}
{"errorDetail":{"message":"COPY failed: stat /var/lib/docker/tmp/docker-builder389608393/binary_build: no such file or directory"},"error":"COPY failed: stat /var/lib/docker/tmp/docker-builder389608393/binary_build: no such file or directory"}
here过去似乎有类似的问题,但似乎已得到修补。我运行了go get github.com/docker/docker@latest
,在go.mod
中的docker版本是github.com/docker/docker v1.13.1
。问题仍然存在。
答案 0 :(得分:0)
如果您仅构建docker映像,则该代码没有任何意义,因为docker构建过程不会运行该程序。 您应该将Dockerfile和可执行文件“ binary_build”放在一个单独的文件夹中,也许Dockerfile应该像这样:
FROM alpine:latest
WORKDIR /gopath/src/build
COPY binary_build /usr/local/bin/