Use go mod vendor to copy all your module dependencies into a vendor directory within your project, ensuring your build is isolated from external network issues and specific versions are locked locally. This is essential for reproducible builds in CI/CD pipelines or when working in environments with restricted internet access.
Run the command from your project root to generate the directory:
go mod vendor
To ensure the vendor directory stays in sync with your go.mod and go.sum files, add the -mod=vendor flag to your build commands. This tells the Go toolchain to look for dependencies in the local vendor folder instead of the module proxy:
go build -mod=vendor ./...
If you need to exclude specific packages from the vendor directory (for example, to avoid vendoring test dependencies or internal tools), you can configure this in your go.mod file using the exclude directive or by using the go mod tidy command to clean up unused dependencies before running go mod vendor. Note that go mod vendor only includes dependencies required by your main module; it does not vendor transitive dependencies that are not actually used by your code unless they are explicitly required.
When working with the vendor directory, remember that the Go toolchain expects a vendor/modules.txt file to be present, which maps module paths to their local locations. This file is automatically generated and updated by go mod vendor. If you manually edit the vendor directory, you must run go mod vendor again to regenerate this mapping file, or your builds may fail.
For CI/CD environments, it is common practice to commit the entire vendor directory to your repository. This guarantees that every build uses the exact same dependency versions, regardless of changes in the remote module proxy. However, be aware that this increases your repository size. If repository size is a concern, you can use go mod download to cache dependencies locally in your CI environment without committing the vendor directory, though this approach relies on the network availability of the module proxy.
Always run go mod tidy before go mod vendor to ensure your go.mod file accurately reflects the dependencies your code actually uses. This prevents unnecessary bloat in the vendor directory and ensures that the vendor/modules.txt file is correct. If you encounter errors during vendoring, check that your go.mod file is valid and that all required dependencies are available in the module proxy or your local cache.