baicai

白菜

一个勤奋的代码搬运工!

The correct way to create an image using CGO in the docker golang:alpine environment.

title: "The Correct Way to Build Images with CGO in Docker Golang: Alpine"
slug: "docker_golang_alpine_cgo_build"
date: 2023-09-04T23:23:09+08:00
type: posts
draft: false
categories: ["Applications", "Interesting Websites", "Bits and Pieces", "Collection and Organization"]
tags: ["Technical Sharing", "Golang"]

description: ""#


When a program needs to import C/C++ libraries (such as for supporting the Sqlite database), the compilation environment needs to have CGO enabled. Otherwise, the program cannot run successfully 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"]

We also use Alpine to run the image. However, Alpine is extremely minimal and does not include common items such as time zones and certificates, which can lead to unpredictable errors. Therefore, we need to install these items:

PackagePurpose
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.