Compiling a Go App with SQLite for Linux on Windows Using Docker

If you're developing a Go application on Windows that uses SQLite and need to compile it for Linux, Docker can be a lifesaver. By leveraging Docker, you can create a consistent build environment that mimics a Linux system, ensuring your application runs smoothly on the target platform. Here's how you can do it using a simple docker run
command.
The key to this process is the docker run
command, which allows you to execute commands inside a Docker container. In this case, we're using the official Go image (golang:latest
) to compile our application. The command mounts your current working directory into the container, sets the working directory, and then runs the necessary Go build command. Here's the command in action:
docker run --rm -v ${pwd}:/app -w /app golang:latest sh -c "GOOS=linux GOARCH=amd64 CGO_ENABLED=1 go build -o dist/myapp_linux"
Let's break this down. The --rm
flag ensures the container is removed after the build process, keeping your system clean. The -v ${pwd}:/app
flag mounts your current directory (retrieved using ${pwd}
) to the /app
directory inside the container. The -w /app
flag sets the working directory inside the container to /app
, so the build command runs in the correct location.
The sh -c
part allows you to pass a shell command to the container. Here, we're setting a few environment variables: GOOS=linux
tells Go to compile for Linux, GOARCH=amd64
specifies the architecture, and CGO_ENABLED=1
enables CGO, which is necessary for SQLite. Finally, go build -o dist/myapp_linux
compiles the application and outputs it to the dist
directory with the name myapp_linux
.
Why is CGO_ENABLED=1
important? SQLite is a C library, and the go-sqlite3
package relies on CGO to interact with it. Without enabling CGO, the build process would fail because the Go compiler wouldn't be able to link the SQLite library. This is a crucial step when working with SQLite in Go, especially when cross-compiling for different platforms.
By using this Docker command, you can easily compile your Go application for Linux on a Windows machine without worrying about setting up a cross-compilation environment. It's a clean, efficient way to ensure your application is ready for deployment on Linux servers.
Subscribe to my newsletter
Read articles from Hossein Margani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
