Go镜像可以怎么玩
将go程序打包成docker镜像部署
FROM golang:1.19
WORKDIR /usr/src/app
# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
COPY go.mod go.sum ./
RUN go mod download && go mod verify
COPY . .
RUN go build -v -o /usr/local/bin/app ./...
CMD ["app"]
docker build -t my-golang-app .
docker run -it --rm --name my-running-app my-golang-app
在容器内编译程序
docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang:1.19 go build -v
# compile with Makefile
$ docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang:1.19 make
在容器内交叉编译程序
$ docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp -e GOOS=windows -e GOARCH=386 golang:1.19 go build -v
$ docker run --rm -it -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang:1.19 bash
$ for GOOS in darwin linux; do
> for GOARCH in 386 amd64; do
> export GOOS GOARCH
> go build -v -o myapp-$GOOS-$GOARCH
> done
> done
多阶段构建容器(减小体积)
FROM golang:1.19-alpine as builder
RUN apk --no-cache add git && export GOPRIVATE=github.com/xxx/xxx && \
export GOPROXY=https://goproxy.cn,direct
COPY . /root/build
WORKDIR /root/build
RUN go mod download && go build -o server main.go
FROM alpine:latest as prod
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /root/build/server .
CMD ["./server"]
其实还有更多的玩法我这里没有说到,就留待各位大佬自行探索了~~~