首页 > 解决方案 > CGO_Enabled=1 需要在 Alpine Docker 容器中使用 SQLite 构建 Go 二进制文件

问题描述

我正在尝试编译一个使用GORM的 Alpine Go 容器,它是内存数据库的SQLite 驱动程序。这取决于是否启用了 CGO。我的二进制文件使用 构建和执行良好go build .,但是在运行我的 docker 映像(docker build .后跟docker run $imagename)时,我收到错误消息:

standard_init_linux.go:219: exec user process caused: no such file or directory

我正在 Windows 10 64 位上构建。我已经安装了 gcc。两者C:\TDM-GCC-64\binC:\cygwin64\bin在我的 $env:path 中。我已将包中所有文件的行尾更改为 Linux 样式 (LF)。

我的docker文件如下:

FROM golang:1.16.4-alpine AS builder

RUN apk update \
    && apk add --no-cache git \
    && apk add --no-cache ca-certificates \
    && apk add --update gcc musl-dev \
    && update-ca-certificates

# Create a user so that the image doens't run as root
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "100001" \
    "appuser"

# Set the working directory inside the container.
WORKDIR $GOPATH/src/app

# Copy all files from the current directory to the working directory
COPY . .

# Fetch dependencies.
RUN go get -u -d -v

# Go build the binary, specifying the final OS and architecture we're looking for
RUN GOOS=linux CGO_ENABLED=1 GOARCH=amd64 go build -ldflags="-w -s" -o /go/bin/app -tags timetzdata

FROM scratch

# Import the user and group files from the builder.
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/group /etc/group
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Copy our static executable.
COPY --from=builder /go/bin/app/go/bin/app

# Use the user that we've just created, one that isn't root
USER appuser:appuser

ENTRYPOINT ["/go/bin/app"]

您能帮我理解为什么我的 docker 映像无法运行吗?

如果它有任何价值,打开数据库的 Go 代码行就是这样。由于这可以使用 Go 在本地构建或使用go run .,因此我认为这无关紧要。

db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})

标签: dockersqlitegoalpinego-gorm

解决方案


解决方案是使用 Dockerfile 中的 apk 安装 gcc 和 alpine-sdk 软件包。在上面的问题中只安装了 gcc。


推荐阅读