Copy file and not dir with the same name in docker 2-stage build

huangapple go评论91阅读模式
英文:

Copy file and not dir with the same name in docker 2-stage build

问题

在下面的Dockerfile中:

WORKDIR /app
RUN go build -ldflags "-s -w" -a -installsuffix cgo -o tool-web ./tool-web

...

FROM scratch
COPY --from=build /app/tool-web /app/tool-web

结果显示COPY指令复制的是目录tool-web而不是二进制文件。

有没有办法指定COPY指令只复制二进制文件?

英文:

In the following Dockerfile

WORKDIR /app
RUN go build -ldflags "-s -w" -a -installsuffix cgo -o tool-web ./tool-web

...

FROM scratch
COPY --from=build /app/tool-web /app/tool-web

turns out the COPY directive copies the directory tool-web and not the binary.

Is there a way to specify to the COPY that the binary is to be copied?

答案1

得分: 1

根据go命令的文档

-o标志强制构建将生成的可执行文件或对象写入指定的输出文件或目录,而不是最后两段描述的默认行为。如果指定的输出是一个已存在的目录,或者以斜杠或反斜杠结尾,那么任何生成的可执行文件都将被写入该目录。

因此,如果你使用了-o tool-web并且./tool-web/是一个已存在的目录,你的输出二进制文件将被写入tool-web目录中的一个文件。一个合理的猜测是你的二进制文件可能已安装为./tool-web/main

要解决这个问题,有两种简单的方法:

  1. 找出二进制文件安装的路径,并调整COPY命令使用该路径作为源路径
    • COPY --from=build /app/tool-web/main /app/tool-web
  2. 或者,将-o更改为写入不同的文件名,然后调整COPY命令使用该名称作为源路径
    • -o tool-web-binary
    • COPY --from=build /app/tool-web-binary /app/tool-web
英文:

Per the go command documentation:

> The -o flag forces build to write the resulting executable or object to the named output file or directory, instead of the default behavior described in the last two paragraphs. If the named output is an existing directory or ends with a slash or backslash, then any resulting executables will be written to that directory.

Thus, if you use -o tool-web and ./tool-web/ is an existing directory, your output binary will be written as a file within the tool-web directory. A decent guess is your binary may have been installed as ./tool-web/main.

To fix this, two easy approaches would be:

  1. Figure out the path your binary is installed as, and adjust COPY to use that path as the source
    • COPY --from=build /app/tool-web/main /app/tool-web
  2. Or, change the -o to write to a different filename, and then adjust COPY to use that name as the source
    • -o tool-web-binary
    • COPY --from=build /app/tool-web-binary /app/tool-web

huangapple
  • 本文由 发表于 2022年5月19日 02:06:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/72294014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定