This question already has an answer here:
I'm new to Go, and wonder if I can build my application on my computer, then put on target machines with different Linux systems and run without having to compile it or its dependencies?
How do I figure out on what target systems what binaries can run?
</div>
If you build the go program on a Linux machine, it should just work elsewhere, if you mark it as executable chmod +x /path/to/main.go
.
You can specify the build using env
and the go build
cmd tool which architecture to build for (or which OS), for example:
env GOARCH=arm go build main.go
If you want, you can specify Linux with
env GOOS=linux go build main.go
Note, these are the target environments:
Note that $GOARCH and $GOOS identify the target environment, not the environment you are running on. In effect, you are always cross-compiling. By architecture, we mean the kind of binaries that the target environment can run: an x86-64 system running a 32-bit-only operating system must set GOARCH to 386, not amd64.
see here for a full list of distros and architectures: https://golang.org/doc/install/source#environment
Note that Go binaries compiled on a Linux OS would work on other Linux distro.
If Docker is an option, you can consider using one of the Go Docker images on DockerHub. You can either create a Dockerfile based on one of the <go-version>-onbuild
images or build your application on your computer, then COPY
the binary over to one the images that is based off the Linux distro of your choice.
The onbuild
images builds and runs your application. You can check out its Dockerfile here. I have seen team uses the second approach of building and running the application binary separately in golang-alpine Docker containers to reduce the size of production images.
Otherwise, you can use Go built-in cross-compilation support, which boils down to:
GOOS
and GOARCH
environmental variables to be the values for the target operating system and architecture.go build -v YOURPACKAGE
Refer here for a list of supported GOOS
and GOARCH
values.