Knox
Knox
Explore posts from servers
RRailway
Created by Knox on 6/14/2023 in #✋|help
Release Go app with Docker and godotenv
func LoadEnvVariables() (ServerConfig, error) {
cnf := ServerConfig{}
err := envconfig.Process("", &cnf)
return cnf, err
}
func LoadEnvVariables() (ServerConfig, error) {
cnf := ServerConfig{}
err := envconfig.Process("", &cnf)
return cnf, err
}
I have this function that I use on my server setup to load the .env variable and on my main.go I do a simple load
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
Locally it works but when hosting with a Dockerfile the app crashes because it can't load the env variable
# Start from golang base image
FROM golang:alpine as builder

# Add Maintainer info
LABEL maintainer="a11199"

# Install git.
RUN apk update && apk add --no-cache git

# Set the current working directory inside the 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 the go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the working Directory inside the 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. Observe we also copied the .env file
COPY --from=builder /app/main .

# Expose port 8080 to the outside world
EXPOSE 8080

#Command to run the executable
CMD ["./main"]
# Start from golang base image
FROM golang:alpine as builder

# Add Maintainer info
LABEL maintainer="a11199"

# Install git.
RUN apk update && apk add --no-cache git

# Set the current working directory inside the 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 the go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the working Directory inside the 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. Observe we also copied the .env file
COPY --from=builder /app/main .

# Expose port 8080 to the outside world
EXPOSE 8080

#Command to run the executable
CMD ["./main"]
The app is deployed but eventually crashes with
2023/06/14 09:44:30 Error loading .env file
open .env: no such file or directory
2023/06/14 09:44:30 Error loading .env file
open .env: no such file or directory
Any clue ? I know this isn't a railway problem more but any feedback would be appreciated.
11 replies