I have the following project directory structure:
myapp/
docker/
docker-compose.yml
.env
src/
<my source code here>
config.properties
Here is my .env file:
ENV=local
SERVICE_DB_HOST=0.0.0.0
SERVICE_DB_PORT=3306
SERVICE_DB_ROOT_PASSWORD=12345
SERVICE_DB_APP_USER=my-service-user
SERVICE_DB_APP_PASSWORD=23456
Here is my docker/docker-compose.yml:
version: "3.7"
services:
myapp-main-db:
env_file:
- ../.env
image: mysql:8
container_name: myapp-main-db
command: --default-authentication-plugin=mysql_native_password
restart: always
ports:
- $SERVICE_DB_PORT:$SERVICE_DB_PORT
environment:
MYSQL_ROOT_PASSWORD: $SERVICE_DB_ROOT_PASSWORD
MYSQL_DATABASE: myapp_service_db_$ENV
MYSQL_USER: $SERVICE_DB_APP_USER
MYSQL_PASSWORD: $SERVICE_DB_APP_PASSWORD
volumes:
- myapp-service-db-data:/var/lib/mysql
volumes:
myapp-service-db-data:
When I run docker-compose -f docker/docker-compose.yml up -d from the project root directory, I see the MySQL container spin up without issue, and verify its running via docker ps.
However I am unable to connect to it using the expected connection string and credentials, which I am sure are correct. This leads me to believe that Docker Compose is not loading the ../.env file as I was expecting it to, and so none of the variables defined in ../.env are being injected as env vars.
Can anybody spot where I'm going awry?
Update
When I run docker-compose config I get:
$ docker-compose config
WARNING: The SERVICE_DB_PORT variable is not set. Defaulting to a blank string.
WARNING: The SERVICE_DB_ROOT_PASSWORD variable is not set. Defaulting to a blank string.
WARNING: The ENV variable is not set. Defaulting to a blank string.
WARNING: The SERVICE_DB_APP_USER variable is not set. Defaulting to a blank string.
WARNING: The SERVICE_DB_APP_PASSWORD variable is not set. Defaulting to a blank string.
ERROR: The Compose file './docker-compose.yml' is invalid because:
services.myapp-main-db.ports contains an invalid type, it should be a number, or an object
docker-compose configto display the whole, implied configuration (with the variables substituted…)./.envand re-run the command I getERROR: Couldn't find env file: /Users/myuser/workspace/myapp-service/docker/.env, so I do believe../.envis correct.docker-compose config. So it seems my suspicions are correct, that its not loading the variables defined in the../.envfile.env_fileand.envare somewhat entangled, while there are definitely different notions! Maybe the SO thread Docker Compose extra_hosts from env_file and not from default .env file could be useful to you?