Golang 程序使用 Docker 部署

起因

最近换了一台内存大点的服务器,就想着把之前写的 Go 程序放到 Docker 里,这样以后迁移也简单

编译

1.编写 Dockerfile 文件

FROM golang:alpine AS builder

ENV CGO_ENABLED 0
ENV GOOS linux

WORKDIR /build
ADD go.mod .
ADD go.sum .
RUN go mod download
COPY . .
RUN apk add --no-cache git
RUN go build -ldflags="-s -w" -o appname .

FROM alpine

ENV TZ Asia/Tokyo

WORKDIR /apps
#从编译阶段的中拷贝编译结果到当前镜像中

COPY --from=builder /build/appname /apps/appname 

CMD ["./appname"]

2.编译

docker build -t appname:latest .

运行

1.编写 docker compose 文件

version: "3.7"

services:
    appname:
        image: appname:latest
        container_name: appname
        restart: unless-stopped
        volumes:
            - ~/server/logs/appname:/var/log/appname

2.启动

docker compose up -d

总结

很简单

参考

构建 Go 应用 docker 镜像的十八种姿势


comments powered by Disqus