我有一个使用 go-sqlite3 库的 Go 应用程序。我可以在本地运行我的应用程序。但是,我无法使用以下
Dockerfile
构建任何 docker 映像:
FROM golang:alpine
ENV CGO_ENABLED=1
RUN apk add --no-cache \
gcc \
musl-dev
WORKDIR /src
COPY go.mod go.sum ./
COPY . .
RUN go build -o ./server cmd/main.go
FROM alpine
COPY --from=0 /src/server /usr/bin/server
CMD ["server"]
我收到的错误为:
sqlite3-binding.c:34070:42: error: 'pread64' undeclared here (not in a function); did you mean 'pread'?
sqlite3-binding.c:34088:42: error: 'pwrite64' undeclared here (not in a function); did you mean 'pwrite'?
我使用的是带有 M1 芯片的 MacOS 13.3.1。我不会将任何
platform
参数传递给 docker build
我应该如何修复我的
Dockerfile
?
pread64()
和pwrite64()
函数是GNU libc中的扩展。它们不是 POSIX C 库标准的一部分,并且在 Alpine Linux 中包含的最小 musl libc 中不可用。
在 Docker 环境中,最简单的解决方法是切换到基于 Debian 或 Ubuntu 的设置。这将比基于 Alpine 的设置(数十兆字节)稍大,但可以避免此类兼容性问题。
FROM golang:1.22-bookworm
ENV CGO_ENABLED=1
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive \
apt-get install --no-install-recommends --assume-yes \
build-essential \
libsqlite3-dev
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o ./server cmd/main.go
FROM debian:bookworm
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive \
apt-get install --no-install-recommends --assume-yes \
libsqlite3-0
COPY --from=0 /src/server /usr/bin/server
CMD ["server"]
我已将 Alpine
apk
命令更改为 Debian apt-get
命令,并且确保在构建阶段安装 C 头文件,并在最后阶段安装 C 共享库。我还添加了 RUN go mod download
行来改进重建时的 Docker 缓存。