程序员开发实例大全宝库

网站首页 > 编程文章 正文

基于docker的go语言构建环境(go dockerfile)

zazugpt 2024-08-27 23:56:53 编程文章 19 ℃ 0 评论

一个简单的go程序。

package main
import "fmt"
func main(){
  fmt.Println("hello world")
}

通过Dockerfile来进行go程序构建

FROM --platform=${BUILDPLATFORM} golang:1.16.7-alpine AS build
WORKDIR /src
ENV CGO_ENABLED=0
COPY . .
ARG TARGETOS
ARG TARGETARCH
RUN go mod init hello
RUN GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -o /out/example .
FROM scratch AS bin-unix
COPY --from=build /out/example /
FROM bin-unix AS bin-linux
FROM bin-unix AS bin-darwin
FROM scratch AS bin-windows
COPY --from=build /out/example /example.exe
FROM bin-${TARGETOS} AS bin

编写Makefile简化操作。

all: bin/example
PLATFORM=local
#PLATFORM=windows/amd64
.PHONY: bin/example
bin/example:
	@docker build . \
	--target bin \
	--output bin/ \
	--platform ${PLATFORM}

执行make命令,构建成功,并copy可执行文件到当前目录下的bin目录中。上面的dockerfile使用到了buildx多平台交叉编译功能,可参考https://github.com/docker/buildx

CGO_ENABLED=0,结果二进制文件不会链接任何的c库,

当指定PLATFORM=windows/amd64,可以编译出windows下的可执行文件example.exe。

可在.dockerignore文件中指定需要忽略的文件,从而减少不必要的复制工作。

bin/
.git/

上面对在容器中进行go语言进行编译打包进行了简单描述,任何大型项目对离不开对包的依赖和管理,下面看看如何在容器环境中增加对包的依赖和通过容器的cache技术提升打包效率。

go源码中增加包的依赖。

package main
import (
    "fmt"
    "os"
    "strings"
    "github.com/pkg/errors"
)
func echo(args []string) error {
  if len(args) < 2 {
    return errors.New("no message")
  }
  _, err := fmt.Println(strings.Join(args[1:], " "))
  return err
}
func main(){
  if err := echo(os.Args); err != nil {
    fmt.Fprintf(os.Stderr, "%+v\n", err)
    os.Exit(1)
  }
}

dockerfile中通过将包的下载和编译打包分为两个阶段,并将下载的依赖包进行缓存。

# syntax = docker/dockerfile:1-experimental
FROM --platform=${BUILDPLATFORM} golang:1.16.7-alpine AS base
WORKDIR /src
COPY . .
ENV CGO_ENABLED=0
ENV GOPROXY=https://goproxy.cn
RUN go mod init hello
RUN go mod tidy
RUN go mod download
FROM base AS build
ARG TARGETOS
ARG TARGETARCH
RUN --mount=type=cache,target=/root/.cache/go-build \
  GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -o /out/example .
FROM base AS test
RUN --mount=type=cache,target=/root/.cache/go-build \
 go test -v .
FROM scratch AS bin-unix
COPY --from=build /out/example /
FROM bin-unix AS bin-linux
FROM bin-unix AS bin-darwin
FROM scratch AS bin-windows
COPY --from=build /out/example /example.exe
FROM bin-${TARGETOS} AS bin

增加代码的单元测试代码,如hello_test.go。

package main
import (
  "testing"
  "github.com/stretchr/testify/require"
)
func TestEcho(t *testing.T) {
  err := echo([]string{"bin-name", "hello", "world"})
  require.NoError(t, err)
}
func TestEchoErrorNoArgs(t *testing.T) {
  err := echo([]string{})
  require.NoError(t, err)
}

上面dockerfile中同样增加了test阶段,并通过对base阶段的依赖,共享下载的包并进行缓存。

Makefile中增加测试目标。

all: bin/example
PLATFORM=local
#PLATFORM=windows/amd64
.PHONY: bin/example
bin/example:
	@docker build . \
	--target bin \
	--output bin/ \
	--platform ${PLATFORM}
.PHONY: test
test: 
	@docker build . --target test

这样,通过make test就可以对源码进行单元测试了。

附docker安装相关。

由于自己是在virtualbox安装的CentOS-8.3.2011-x86_64-minimal.iso,所以需要安装docker。

cd /etc/yum.repos.d/
wget http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum repolist
yum --disablerepo="*" --enablerepo="docker-ce-stable" list available 
yum install docker-ce -y
systemctl enable docker
# 默认docker通过unix socket与docker引擎通讯,只有root和docker组的用户才可访问
# 创建docker用户组,并将需要的用户增加的docker用户组
groupadd docker
usermod -aG docker zhangsan 
# 配置镜像加速,登陆:https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://adadafaf.mirror.aliyuncs.com"]
}
EOF
#或者
vi /etc/systemd/system/multi-user.target.wants/docker.service
# ExecStart=/usr/bin/dockerd --registry-mirror=https://registry.docker-cn.com
sudo systemctl daemon-reload
sudo systemctl restart docker

# 启用buildx

docker run --rm --privileged docker/binfmt:66f9012c56a8316f9244ffd7622d7c21c1f6f28d
ls -al /proc/sys/fs/binfmt_misc/
cat /proc/sys/fs/binfmt_misc/qemu-aarch64
docker buildx create --name xbuilder --use
docker buildx inspect xbuilder --bootstrap
export DOCKER_BUILDKIT=1
docker buildx install

安装VBoxLinxAdditions实现文件夹共享。

ls -l /lib/modules/$(uname -r)/build
ls /usr/src/kernels/
# 若build指向的文件夹不存在则安装对应内核的header版本或创建对应的文件夹并复制正确的header文件
yum install binutils gcc make patch libgomp glibc-headers glibc-devel elfutils-libelf-devel kernel-headers kernel-devel
yum install xorg-x11-drivers xorg-x11-utils
init 6
mount /dev/cdrom /mnt/cdrom
/mnt/cdrom/VBoxLinxAdditions.run
init 6

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表