Search code examples
dockerenvironment-variablesdockerfiledocker-build

docker build not setting up environment variables using ENV


Trying to build a docker image with golang and react code. The environment variable JWT_SECRET_KEY is not being set.

# 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

To build this i ran the command

docker build -t webapp .

Solution

  • If you want JWT_SECRET_KEY to be set in the production stage you need to move it to that stage. Or if you need it in both copy it. So change your docker file to

    # 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