I need to run Golang application on Docker machine.
I'm working on Mac OSX and Docker is working on top of Linux virtual machine, so binaries builded on Mac are not runnable on Docker.
I see two ways here:
First one is hard because of CGO (it is used in some imported libraries).
Second is very slow because of 'go get' operation.
Can you please tell me, which way is the most common in that situation? Or maybe I'm doing something wrong?
docker run golang go get -v github.com/golang/example/hello/... This will pull the golang image (unless you have it already; then it will start right away), and create a container based on that image. In that container, go will download a little “hello world” example, build it, and install it. But it will install it in the container …
Write a multi-purpose Makefile to both setup the build environment inside Docker and statically compile the Go application (read more about it below). Create a Dockerfile to build the statically linked Go binary (called “ Dockerfile.build “). Run it and extract the Linux binary using “ docker cp “.
We’ll copy the go.mod and go.sum file into our project directory /app which, owing to our use of WORKDIR, is the current directory (.) inside the image. COPY go.mod ./ COPY go.sum ./ Now that we have the module files inside the Docker image that we are building, we can use the RUN command to execute the command go mod download there as well.
When you want to work on a piece of code and build it within a container, you can mount a local directory to /go in the golang container, so that the $GOPATH is persisted across invocations: docker run -v $HOME/go:/go golang ....
Here a solution to make cross-compile super easy even with CGO.
I stumbled upon it recently after wasting a lot of time getting a new windows build server to build my Go app. Now I just compile it on my Mac and will create a Linux build server with it:
https://github.com/karalabe/xgo
Many thanks to Péter Szilágyi alias karalabe for this really great package!
How to use:
There are lots more options!
-- edit --
Almost 3 Years later I'm not using this any more, but my docker image to build my application in a linux based CD pipeline is still based on the docker images used in xgo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With