baicai

白菜

一个勤奋的代码搬运工!

docker golang:alpine The correct way to build images with CGO

When a program needs to import C/C++ libraries (such as for supporting Sqlite databases), the compilation environment needs to enable CGO. Otherwise, the program will not run smoothly after packaging (database initialization failure).

In this case, the build-base package needs to be installed to configure the compilation environment.

Refer to the Dockerfile below:

FROM golang:alpine as builder
ENV CGO_ENABLED=1
WORKDIR /app
COPY . .
RUN apk add --no-cache --update git build-base
RUN go mod tidy \
	&& go build -o api_client_linux ./cmd/api_client/


FROM alpine:latest as runner
ENV TZ=Asia/Shanghai
RUN apk --no-cache add ca-certificates tzdata libc6-compat libgcc libstdc++
WORKDIR /app

COPY --from=builder /app/api_client_linux .
VOLUME /app/conf
EXPOSE 8080

ENTRYPOINT ["./api_client_linux" ,"-c","/app/conf/config.yaml"]

When running the image, we also use Alpine. Because Alpine is extremely minimal, it does not include common time zones, certificates, etc., which can cause unpredictable errors. So we need to install these things:

Package NamePurpose
ca-certificates:CA certificates for TLS
tzdata:Time zone configuration
libc6-compat:C standard library
libgcc:GCC-related libraries, required for CGO compilation
libstdc++:C++ standard library
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.