项目介绍
go项目模板(https://github.com/miguno/golang-docker-build-tutorial)
是一个用于创建一个Go应用的Docker镜像的模板项目。这个示例应用程序公开了一个HTTP端点。
Java开发者?请查看https://github.com/miguno/java-docker-build-tutorial
特点:
- Docker构建使用多阶段构建设置来最小化生成的Docker镜像的大小,它的大小为5MB。
- 支持Docker BuildKit
- Golang 1.19
- Golang和Docker的GitHub Actions工作流
- 可选地,只需用justfile方便地运行常见命令,参见justfile。
- 使用.env作为中心配置来设置由justfile和该项目中的其他辅助脚本使用的变量。
要求
必须在本地计算机上安装Docker。仅此而已。您不需要安装Go。
用法和演示
- 步骤1:根据Dockerfile创建Docker镜像。此步骤构建,测试和打包Go应用程序。生成的镜像大小为5MB。
# ***创建镜像可能需要几分钟时间!***
$ docker build --build-arg PROJECT_VERSION=1.0.0-alpha -t miguno/golang-docker-build-tutorial:latest .
您也可以使用新的BuildKit构建。
# https://docs.docker.com/build/
$ docker buildx build --build-arg PROJECT_VERSION=1.0.0-alpha -t miguno/golang-docker-build-tutorial:latest .
您还可以选择检查生成的Docker镜像的大小:
$ docker images miguno/golang-docker-build-tutorial
REPOSITORY TAG IMAGE ID CREATED SIZE
miguno/golang-docker-build-tutorial latest 2de05b854c1b 11分钟前 4.78MB
- 步骤2:为Docker镜像启动容器。
$ docker run -p 8123:8123 miguno/golang-docker-build-tutorial:latest
- 步骤3:打开另一个终端并访问正在运行的容器的示例API端点。
$ curl http://localhost:8123/status
{"status": "idle"}
just命令使用
如果有安装just可以测试如下:
$ just
Available recipes:
audit # detect known vulnerabilities (requires https://github.com/sonatype-nexus-community/nancy)
build # build executable for local OS
coverage # show test coverage
default # print available targets
deps # show dependencies
docker-image-create # create a docker image (requires Docker)
docker-image-run # run the docker image (requires Docker)
docker-image-size # size of the docker image (requires Docker)
evaluate # evaluate and print all just variables
explain lint-identifier # explain lint identifier (e.g., "SA1006")
format # format source code
lint # run linters (requires https://github.com/dominikh/go-tools)
outdated # detect outdated modules (requires https://github.com/psampaz/go-mod-outdated)
release # build release executables for all supported platforms
run # run executable for local OS
send-request-to-app # send request to the app's HTTP endpoint (requires running container)
system-info # print system information such as OS and architecture
test *FLAGS # run tests with colorized output (requires https://github.com/kyoh86/richgo)
test-vanilla *FLAGS # run tests (vanilla), used for CI workflow
tidy # add missing module requirements for imported packages, removes requirements that aren't used anymore
vulnerabilities # detect known vulnerabilities (requires https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck)
举例:
$ just docker-image-create
笔记
- just工具介绍
- 编译构建示例
# Build
$ go build -trimpath -ldflags="-w -s" -v -o app cmd/golang-docker-build-tutorial/main.go
# Test
$ go test -cover -v ./...
# Run
$ ./app