my .env file not seen in my railway deployed server
I am using docker to deploy the go lang server, my server uses environment variables which i have defined in the shared variables section in my railway project.
My go server loads my env file when the app starts, but it cant load because i have it gitignored so it is not part of the files being sent to github which railway uses.
how do i make my railway server see my .env file without me having to push it to github?
my dockerfile:
Builder Stage
FROM golang:1.19 AS builder
WORKDIR /app
COPY go.mod .
COPY go.sum .
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -o /app/main main.go
Run Stage
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/main .
EXPOSE 8080
CMD [ "./main" ]
============================================================================
my main.go:
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file", err)
}
PORT := os.Getenv("PORT")
if PORT == "" {
log.Fatal("port could not be found in env")
}
r := router.Router()
allowedOrigins := handlers.AllowedOrigins([]string{"http://localhost:5173", "https://bookverse.vercel.app"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})
allowedHeaders := handlers.AllowedHeaders([]string{"Content-Type", "Authorization"})
fmt.Println("Go server running on port " + PORT)
log.Fatal(http.ListenAndServe(":"+PORT, handlers.CORS(allowedOrigins, allowedMethods, allowedHeaders)(r)))
}
This is my project Id: fd18ba09-7bb7-4922-b5d1-7e12b7d51b88
So when the docker build finishes successfully i get this error being logged out: "Error loading .env file fileopen .env: no such file or directory", which i have printed out to the console in my server.
How can i get around this?
Thanks
Solution:Jump to solution
you want your variables as service variables, not shared variables, please read this https://docs.railway.app/guides/variables#service-variables
then once you have all the needed variables in the service, do not
log.Fatal()
on godotenv.Load()
because when on railway, railway will load the service variables into the environment automatically...2 Replies
Project ID:
fd18ba09-7bb7-4922-b5d1-7e12b7d51b88
Solution
you want your variables as service variables, not shared variables, please read this https://docs.railway.app/guides/variables#service-variables
then once you have all the needed variables in the service, do not
log.Fatal()
on godotenv.Load()
because when on railway, railway will load the service variables into the environment automatically