Docker构建Golang项目常见问题
- 1 Dockerfile
- 1.1 dockerfile报错:failed to read expected number of bytes: unexpected EOF
- 1.2 go mod tidy: go.mod file indicates go 1.21, but maximum supported version is 1.17
- 1.3 是否指定启动文件问题
- 2 构建及部署
1 Dockerfile
1.1 dockerfile报错:failed to read expected number of bytes: unexpected EOF
可能是docker拉取的镜像版本导致的问题的出现。
解决办法:
- 使用docker pull {镜像名称},单独拉取构建时所需的基础镜像。
- 更改Dockerfile中的镜像版本。
1.2 go mod tidy: go.mod file indicates go 1.21, but maximum supported version is 1.17
因为Dockerfile中基础镜像是golang:alpine。查看golang:alpine可以看到里面的golang版本是1.17.5
。
解决办法:更改Dockerfile中基础镜像为golang:1.21。
1.3 是否指定启动文件问题
FROM golang:1.21 AS builderLABEL stage=gobuilderENV GOOS linux
ENV GOARCH amd64
ENV CGO_ENABLED 0
ENV GO111MODULE on
ENV GOPROXY https://goproxy.cn,directARG AppDirWORKDIR /buildADD ${AppDir}/go.mod .
ADD ${AppDir}/go.sum .
ADD core .RUN go mod tidy && go mod downloadCOPY . .
COPY ${AppDir}/etc /app/etc# 指定启动文件
RUN #cd ${AppDir} && go build -ldflags="-s -w" -o /app/app ./cmd/main.go
# 不指定1
RUN #cd ${AppDir} && go build -ldflags="-s -w" -o /app/app *.go
# 不指定 构建的时候会自己去找.go文件
RUN cd ${AppDir} && go build -ldflags="-s -w" -o /app/appFROM scratchARG AppDir
LABEL xxx.net.service=${AppDir}
LABEL xxx.net.slslog=trueCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai
ENV TZ Asia/ShanghaiWORKDIR /app
COPY --from=builder /app/app /app/app
COPY --from=builder /app/etc /app/etcCMD ["./app", "-f", "etc/config.yaml"]
2 构建及部署
- 构建
docker build -t ucenter-rpc:0.0.1 -f Dockerfile .
- Docker创建网络
docker network create --driver=bridge zero_bridge_network
- 创建配置文件及日志目录
mkdir -p /opt/soft/go-zero/deploy/ucenter-rpc/etc
mkdir -p /opt/soft/go-zero/deploy/ucenter-rpc/logs
- docker-compose
version: "3.1"
services:ucenter_rpc:container_name: dcv3_ucenter_rpc_serviceimage: 镜像restart: on-failureports:- 8080:8080volumes:- /etc/localtime:/etc/localtime:ro- /opt/soft/go-zero/deploy/ucenter-rpc/etc:/app/etc- /opt/soft/go-zero/deploy/ucenter-rpc/logs:/app/logshealthcheck:test: [ "CMD", "curl", "-f", "http://localhost:6470/healthz" ]interval: 1m30stimeout: 10sretries: 3start_period: 40snetworks:default:external:name: go-zero_bridge_network