学习Golang在容器中运行Go(附代码)

245 阅读2分钟

学习Golang在容器中运行Go

可重复的构建和运行环境

多年来,同一语言的不同项目对所需工具和库的版本有不同的要求,这种情况并不少见。

例如,我了解到GO111MODULE 环境变量的行为在Go 1.12和1.13版本中存在差异。

这就是为什么当我为一个新项目启动存储库时,我首先要做的是设置脚本,以可重复的方式构建和运行代码。

Docker容器是一个非常有效的工具。因此,当我为我的learning-go项目创建GitHub repo时,我设置了一个快速脚本来运行代码。这样我就知道,除了安装了Docker之外,几年后我就能运行它,而不需要任何特殊的设置。

我希望这是对开源项目的普遍做法。安装他们的构建需求可能是件麻烦事,尤其是在与其他项目有版本冲突时。

在Docker容器中运行Go

这是我用来运行第一批Go程序的脚本:

 #!/bin/bash
#
# Runs Go.
#
set -o nounset -o errexit -o pipefail                     # Abort the script on errors

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)  # Absolute directory where this script is stored
BASE_DIR=$(cd "$SCRIPT_DIR/.." && pwd)                    # Parent directory of this script
GO_VERSION="1.15-buster"                                  # Docker image tag of the Go version that will be used

mkdir -p "$BASE_DIR/.cache"                               # Create .cache directory under base directory

docker run                       `# Run a Docker container                               ` \
  --rm                           `# Remove the container when the command exits          ` \
  -it                            `# Set an interactive terminal                          ` \
  -v "$BASE_DIR":"$BASE_DIR"     `# Mount base directory with same name in the container ` \
  -v "$BASE_DIR/.cache":/.cache  `# Mount .cache directory under the container's root    ` \
  -w "$BASE_DIR"                 `# Set base directory as the current working directory  ` \
  --user $(id -u):$(id -g)       `# Use same user ID inside the container as on the host ` \
  golang:$GO_VERSION             `# Use Go's docker image with the specified tag         ` \
  go $@                          `# Run go with the provided command line arguments 

从本质上讲,这个脚本将在Docker容器中运行Go,并使用提供给它的命令行参数。比如说:

bin/go run ascii-art/main.go

关于它如何工作的细节,请看内联评论。我相信,随着时间的推移,我将根据需要发展这个脚本(例如,用于跨平台的构建)。

你呢?你对可重复的构建和运行环境的首选技术是什么?特别是对于Go,你有什么好的建议吗?