Golang: Build Linux binary from MacOS

Today I was write a Golang script for a client. I was using MacOS for development. And need to deploy into a Linux environment.

Firstly, I didn’t do anything special for build the binary. Just use “go build” and it creates a binary. It works fine on my MacOS. But when I move the binary into Linux server it pops error.

golang cannot execute binary file: Exec format error

After the investigation I realised I should give more ENV to build the binary for my Linux server. Then I run the following.

env GOOS=linux GOARCH=amd64 go build -v

This time it builds the binary specifically for Linux server. And it works. Golang makes cross platform compile very easy and straight forward.