如何在不运行的情况下从Docker构建中复制结果

I want to do some compilations of my go files etc and I want to transfer the resulting binaries etc to host. So everybody don't need to do local setup and they can just run docker command and output is compiled in docker and transferred to host.

FROM golang:1.11-alpine as builder
COPY src /go/src/project/src
RUN cd /go/src/project/src && go build -o myBin

Now I want myBin to be transferred to host. Any ideas? PS: I want it done without running a container. If just running the build can do it, it's best!

You don't have to run a container, but you have to create one in order to be able to cp (copy) the binary from that container afterwards. The 2 commands needed are:

  • docker container create ...
  • docker container cp $container_name:/path/in/container /path/on/host

Example:

main.go:

package main

import "fmt"

func main() {
  fmt.Println("hello world")
}

Dockerfile:

FROM golang:1.10-alpine3.7

WORKDIR /go/src/app
COPY . .

RUN go get -d -v ./...
RUN go install -v ./...

CMD ["app"]

Build - create temp container - copy binary - cleanup:

docker build -t go-build-test .
docker container create --name temp go-build-test
docker container cp temp:/go/bin/app ./
docker container rm temp

The binary has been copied to your current folder:

~/docker_tests/go-build-test$ ls
app  Dockerfile  main.go
~/docker_tests/go-build-test$ ./app
hello world