2

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!

mayankcpdixit
  • 2,456
  • 22
  • 23
  • 3
    Why don't you want to run a container? Whats the difference? `docker run build-my-go-project`. – tkausl Nov 30 '18 at 11:35
  • Do you need to build an image? Or are you just trying to use docker to perform your compile? – BMitch Nov 30 '18 at 12:23
  • 1
    Related questions: **(1)** [How to copy files from dockerfile to host?](https://stackoverflow.com/questions/33377022/how-to-copy-files-from-dockerfile-to-host). **(2)** [Docker - how can I copy a file from an image to a host?](https://stackoverflow.com/questions/25292198/docker-how-can-i-copy-a-file-from-an-image-to-a-host) – tgogos Nov 30 '18 at 12:39
  • If I do choose to run docker, I'll have to write bash script to 1. run it and then 2. copy bin to host 3. kill container Is that what you suggest @tkausl ? Also is there any other way? – mayankcpdixit Dec 03 '18 at 07:25
  • You don't need to do 2 and 3. A single run can do all three things. – tkausl Dec 03 '18 at 07:33

1 Answers1

1

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
tgogos
  • 23,218
  • 20
  • 96
  • 128
  • yes, @tgogos This is one way of doing it. For this I'll be writing a bash script and run it. Wanted to know if I can do it just in `Dockerfile`. So I don't have to write a bash script? – mayankcpdixit Dec 03 '18 at 07:31
  • 1
    @mayankcpdixit until now, there is no way of doing this by just using a `Dockerfile`. – tgogos Dec 03 '18 at 08:51