Building Go binaries for different architectures
October 19, 2016
go
docker
While this tutorial uses a Docker container, the entire process can be performed
on any system with the go
binary installed.
Configuring Docker
To start off, let’s create a docker-compose.yml
file.
version: "2"
services:
go:
image: golang
volumes:
- ./:/src
command: "/src/build.sh"
All we really need to do is map our project root directory to /src
directory
inside the container and to execute the script build.sh
inside that /src
directory.
We will create the script build.sh
shortly, but first lets create a simple Go
program.
Go
In case you do not have any Go
code laying around, create the file simple.go
in your project root directory.
package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}
Let’s build some binaries
The trick to cross-compiling Go to different architectures is to setup environment
variables GOOS
and GOARCH
to your specific needs. The list of specific values and
combinations for them can be found at golang.org.
To compile a Windows 64-bit
executable we would run the following command.
env GOOS=windows GOARCH=amd64 go build simple.go
This would give us a file named simple.exe
.
env
allows us to set environment variables only for the duration of the execution
of the command. Both GOOS
and GOARCH
get reverted back to their original values
after go build
is finished.
build.sh
To make life easier for us, lets create a script file called build.sh
inside the
project root directory.
#!/usr/bin/env bash
cd /src
echo "Building for Windows 32-bit"
env GOOS=windows GOARCH=386 go build -o simple_32bit.exe simple.go
echo "Building for Windows 64-bit"
env GOOS=windows GOARCH=amd64 go build -o simple_64bit.exe simple.go
echo "Building for Linux 32-bit"
env GOOS=linux GOARCH=386 go build -o simple_32bit simple.go
echo "Building for Linux 64-bit"
env GOOS=linux GOARCH=amd64 go build -o simple_64bit simple.go
Running the container
We have our Docker configuration, our Go code and our builder script. Time to build some binaries.
docker-compose run --rm go
That’s it. The new files are ready and waiting in the project root directory.
Building Alpine binaries
You might have come across a problem when deploying your Go code to an Alpine Linux
distribution. It doesn’t run. With our setup, this problem can be fixed in a second.
In your docker-compose.yml
file change image: golang
to image: golang:alpine
and run the container once again. Your Linux binaries will now run on Alpine.