docker build 不使用 ENV 设置环境变量

docker build not setting up environment variables using ENV

尝试使用 golang 和 React 代码构建 docker 图像。未设置环境变量 JWT_SECRET_KEY。

# Build the Go API
FROM golang:latest AS builder
ADD . /app
WORKDIR /app/server
ENV JWT_SECRET_KEY=DefaultKey
RUN go mod download
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w" -a -o /main .

# Build the React application
FROM node:alpine AS node_builder
COPY --from=builder /app/client ./
RUN npm install
RUN npm run build

# Final stage build, this will be the container
# that we will deploy to production
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /main ./
COPY --from=node_builder /build ./web
RUN chmod +x ./main
EXPOSE 8080
CMD ./main

要构建这个我 运行 命令

docker build -t webapp .

如果您希望在生产阶段设置 JWT_SECRET_KEY,您需要将其移至该阶段。或者,如果您在两者中都需要它,请复制它。因此,将 docker 文件更改为

# Build the Go API
FROM golang:latest AS builder
ADD . /app
WORKDIR /app/server
RUN go mod download
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w" -a -o /main .

# Build the React application
FROM node:alpine AS node_builder
COPY --from=builder /app/client ./
RUN npm install
RUN npm run build

# Final stage build, this will be the container
# that we will deploy to production
FROM alpine:latest
RUN apk --no-cache add ca-certificates
ENV JWT_SECRET_KEY=DefaultKey 
COPY --from=builder /main ./
COPY --from=node_builder /build ./web
RUN chmod +x ./main
EXPOSE 8080
CMD ./main