两阶段构建golang项目dockerfile

2020年10月18日 评论 82 views 1551字阅读5分10秒

先用vendor格式,缓存你的go引用包

请把${service_name}改成你的service_name

cat <<EOF > Dockerfile
# Building stage
FROM golang:1.14-alpine3.12  AS builder

ARG service_name
ENV service_name=${service_name}

WORKDIR /build/src/${service_name}
RUN adduser -u 10001 -D app-runner

ENV GO111MODULE on
ENV GOPATH /build

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ${service_name} -mod=vendor cmd/server/server.go

# Production stage
FROM alpine:3.12 AS final

ARG service_name
ENV service_name=${service_name}

WORKDIR /app

COPY --from=builder /build/src/${service_name}/${service_name} /usr/bin
COPY --from=builder /build/src/${service_name}/cmd/config/appconfig.json /etc/${service_name}/

RUN adduser -u 10001 -D app-runner
RUN chmod -R 755 /usr

CMD ${service_name} -app.config.path=/etc/${service_name}/appconfig.json
EOF
cat Dockerfile

arm内核

cat <<EOF > Dockerfile-arm
# Building stage
FROM golang:1.14-alpine3.12  AS builder

ARG service_name
ENV service_name=${service_name}

WORKDIR /build/src/${service_name}
RUN adduser -u 10001 -D app-runner

ENV GO111MODULE on
ENV GOPATH /build

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o ${service_name} -mod=vendor cmd/server/server.go

# Production stage
FROM alpine@sha256:a15790640a6690aa1730c38cf0a440e2aa44aaca9b0e8931a9f2b0d7cc90fd65 AS final

ARG service_name
ENV service_name=${service_name}

WORKDIR /app

COPY --from=builder /build/src/${service_name}/${service_name} /usr/bin
COPY --from=builder /build/src/${service_name}/cmd/config/appconfig.json /etc/${service_name}/

RUN adduser -u 10001 -D app-runner
RUN chmod -R 755 /usr

CMD ${service_name} -app.config.path=/etc/${service_name}/appconfig.json
EOF

run

 docker build --build-arg service_name=服务名  -t 服务名:版本号 .
weinxin
公众号
在号内与我交流,回复【资源】获取技术大礼包
Docker最后更新:2020-11-5
小熊