Docker Compose not reading env

Viewed 162

This is an often asked question. I have asked it previously but under different error conditions, yet I seem to be doing everything right as per all other posts on this topic so I revert to asking for advice. Again.

I have the the following docker-compose.yml:

version: "3.9"

services:

  projects:
    image: repo/apv_projects:2
    ports:
      - "27035:27035"
    environment:
      - JWT_SECRET_KEY_PROJECTS=${JWT_SECRET_KEY_PROJECTS}
      - PROJECTS_HOST=${PROJECTS_HOST}
      - PROJECTS_PORT=${PROJECTS_PORT}
      - PROJECTS_DB_HOST=${PROJECTS_DB_HOST}
    platform: "linux/amd64"
    depends_on:
      - mongodb
    volumes:
      - projects_data:/app
    links:
      - mongodb

  mongodb:
    image: repo/apv_projects_db:1
#    command: [--auth]
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_DATABASE=$MONGO_INITDB_DATABASE
      - MONGO_INITDB_ROOT_USERNAME=$MONGO_INITDB_ROOT_USERNAME
      - MONGO_INITDB_ROOT_PASSWORD=$MONGO_INITDB_ROOT_PASSWORD
    platform: "linux/amd64"
    volumes:
      - mongodb_data:/app/data/mongodb
volumes:
  projects_data:
  mongodb_data:

I have the following .env file:

PROJECTS_HOST='127.0.0.1'
PROJECTS_PORT=27035
PROJECTS_DB_HOST='mongodb'
PROJECTS_DB_PORT=27017
MONGO_INITDB_DATABASE=apv
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=password

I run the following command:

docker compose --env-file .\.env up --build

But the api (flask) starts up on 127.0.0.1:5000.

The Dockerfile looks like this:

FROM python:3.9.12-slim

RUN apt-get update
RUN apt-get -y install sudo
RUN addgroup app && adduser -system app -ingroup app
RUN usermod -a -G sudo app
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER app

WORKDIR /app
RUN sudo mkdir data

COPY . .

RUN python3 -m pip install --upgrade pip
RUN pip3 install -r requirements.txt

CMD python3 api.py

EXPOSE 27017
EXPOSE 27035

The result is however that the environment variables in the container is not set. when I run:

docker exec container env

I get the following output:

...
PROJECTS_HOST=
PROJECTS_PORT=
PROJECTS_DB_HOST=
...

Previously the error was that I started the api as sudo (post). This is no the issue now though.

1 Answers

I have managed to resolve this issue. It was related to line endings. The .env file was created on a Mac so it had CR line endings but I was building on a linux/amd64 platform so need to have LF line endings. This caused the environment variables to be read as a single string and hence were not set at all.

Related