英文:
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
。
要解决这个问题,有两种简单的方法:
- 找出二进制文件安装的路径,并调整
COPY
命令使用该路径作为源路径COPY --from=build /app/tool-web/main /app/tool-web
- 或者,将
-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:
- Figure out the path your binary is installed as, and adjust
COPY
to use that path as the sourceCOPY --from=build /app/tool-web/main /app/tool-web
- Or, change the
-o
to write to a different filename, and then adjustCOPY
to use that name as the source-o tool-web-binary
COPY --from=build /app/tool-web-binary /app/tool-web
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论