Build Static Go App with Musl

Build Static Go App with Musl

September 24, 2023

Discover how to build a static Go App with Musl for better portability and easier distribution

In the world of software development, portability and ease of distribution are important. With static compilation you will get binary file independent of Linux distribution and library versions.

Install Musl

Musl is an implementation of the C standard library. It implements an interface layer between Linux kernel and Go standard library. With Musl, you can achieve truly statically compiled binary files, even when CGO is enbaled.

Install musl toolchain and other build tools on your Ubuntu:

sudo apt update
sudo apt install build-essential musl-tools pkg-config libssl-dev

Build Go App

Point Go to the Musl compiler with the CC environmet variable:

CC=/usr/bin/musl-gcc go build \
    -ldflags "-s -w -linkmode external -extldflags -static" \

The ldflags attribute provides options for linker to build a static binary file. After compilation, you will find binary file in the current directory. In our case, the binary file name is example.

Check binary file

You can check any binary file with the ldd command:

ldd example

For statically compiled binary files, result will be:

not a dynamic executable

For dynamically compiled binary files, result will be a list of the linked libraries.