Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Mac OSX build for Docker machine

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:

  1. cross-compile binaries on Mac for linux OS
  2. copy project sources to docker, run 'go get' and 'go build' on it

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?

like image 364
i.van Avatar asked Mar 14 '16 21:03

i.van


People also ask

How do I run Golang from Docker container?

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 …

How do I build a Go application in Docker?

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 “.

How to install go mod inside a docker image?

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.

How do I mount a local directory in a Golang container?

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 ....


1 Answers

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:

  • have Docker running
  • go get github.com/karalabe/xgo
  • xgo --targets=windows/amd64 ./

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.

like image 53
TehSphinX Avatar answered Sep 19 '22 02:09

TehSphinX