Go packages are typically stored in a remote repository, such as on GitHub or a similar service, and can be easily downloaded and installed on a local machine using the go get
command. While this may prove to be effective, the package manager experiences trouble while accessing private repositories. Golang does not give a good documentation on how to work around this, making developers frustrated.
To get started, you need to get a personal access token from Github. Head over to https://github.com/settings/tokens, and select the right permissions for your use-case.
Once a token has been generated, store it in an environment file or anywhere you keep your secrets. In this tutorial, we use a .env
file, which will look like this;
Next, set-up the Dockerfile by configuring GOPRIVATE
environment variable and passing the tokens to the container. Here is my Dockerfile
The file starts by installing git and adding CA certificates using the apk package manager. Then it sets up the Go compiler by setting the CGO_ENABLED
, GOOS
and GOARCH
environment variables.
It then defines two build-time arguments, GIT_USERNAME
and GIT_PASSWORD
, which will be passed as arguments when building the image. It uses these arguments to set the GOPRIVATE
environment variable, which allows the use of private Go modules from Github.
The file then updates the credentials for Github by configuring the Git URL and adding the credentials to the .netrc file. It then sets the permissions on the .netrc file to only allow the owner to read it.
The file then copies the go.mod and .go.sum files to the image and runs the command "go mod download" to download the dependencies for the application. At this point any private repositories can be accessed.
You can pass the arguments to the docker build
command using the --env-file
or --build-arg
options
$ docker build --env-file=path/to/env/file -t my-awesome-image .
# OR
docker build --build-arg GIT_USERNAME=myusername --build-arg GIT_PASSWORD=mypassword -t my-awesome-image .
With that, you can now import private packages without worrying about someone else accessing it. Cheers!