That's the code segment where I load .env file and set the variables.
// init executes the initial configuration.
func init() {
// loads the file for env. variables
if err := godotenv.Load(".env"); err != nil {
log.Printf("failed to load env file: %v\n", err)
}
// env variables are set based values within the .env file.
os.Setenv("dbname", os.Getenv("DB_NAME"))
os.Setenv("username", os.Getenv("DB_USERNAME"))
os.Setenv("pw", os.Getenv("DB_PASSWORD"))
os.Setenv("dbport", os.Getenv("DB_PORT"))
os.Setenv("server_port", os.Getenv("SERVER_PORT"))
os.Setenv("hostname", os.Getenv("DB_CONTAINER_NAME"))
}
When I run docker-compose up --build server everything works despite the error I get as follows:
server_1 | 2022/09/07 11:44:06 failed to load env file: open .env: no such file or directory
However, environments are somehow set.
Here is my docker-compose.yml.
version: '3.8'
services:
db:
image: postgres:14.1-alpine
container_name: ${DB_CONTAINER_NAME}
restart: always
environment:
- POSTGRES_DB=${DB_NAME}
- POSTGRES_USER=${DB_USERNAME}
- POSTGRES_PASSWORD=${DB_PASSWORD}
ports:
- ${DB_PORT}:${DB_PORT}
env_file:
- .env
volumes:
- db:/var/lib/postgresql/data
- ./psql/statements/create-tables.sql:/docker-entrypoint-initdb.d/create_table.sql
server:
build:
context: .
dockerfile: Dockerfile
env_file: .env
depends_on:
- ${DB_CONTAINER_NAME}
networks:
- default
ports:
- ${SERVER_PORT}:${SERVER_PORT}
volumes:
db:
driver: local
And my Dockerfile for go application.
FROM golang:1.18
WORKDIR /src
COPY go.sum go.mod ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /bin/app .
FROM alpine
COPY --from=0 /bin/app /bin/app
ENTRYPOINT ["/bin/app"]
I've altered some of Dockerfile's content I get different errors. What might be the reason for such a problem? Because it fails to load but still works.