说一说Golang 如何打包到Docker运行 ?

在Golang中,将程序打包到Docker容器并运行涉及到以下几个步骤:

  1. 编写Dockerfile:Dockerfile定义了如何构建你的Docker镜像。以下是一个简单的Dockerfile示例,它从官方的Golang基础镜像开始,复制源代码到容器内,构建可执行文件,然后设置容器启动时应运行的命令。
# Start from a Debian-based Golang 1.16 image
FROM golang:1.16-buster as builder

# Set Working Directory inside the Docker container
WORKDIR /app

# Copy go mod and sum files 
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed 
RUN go mod download 

# Copy the source from the current directory to the Working Directory inside the Docker container
COPY . .

# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

######## Start a new stage from scratch #######
FROM alpine:latest  

RUN apk --no-cache add ca-certificates

WORKDIR /root/

# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/main .

# Expose port 8080 to the outside
EXPOSE 8080

# Command to run the executable
CMD ["./main"] 
  1. 构建Docker镜像:在包含Dockerfile的目录中,运行以下命令以构建Docker镜像:
docker build -t my-golang-app .

这个命令会创建一个名为my-golang-app的Docker镜像。

  1. 运行Docker容器:使用以下命令运行你的应用:
docker run -p 8080:8080 -d my-golang-app

这个命令会启动一个新的Docker容器,并将本地的8080端口映射到容器的8080端口。

这就是如何在Golang中将程序打包到Docker并运行的基本步骤。

发表评论

后才能评论