Home > front end >  Cannot interpolate environment variable in docker compose
Cannot interpolate environment variable in docker compose

Time:04-25

I have a simple docker compose file to create a Mysql database for my app. But I cannot interpolate the environment variable MYSQL_PORT to set a custom port. Running docker compose up with the configuration below results in a random port being assigned to mysql.

The path to the env file does work, since I have env variables configuring the database.

docker-compose.yml

version: '3'
services:
  mysql:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    volumes:
      - mysql_data:/var/lib/mysql
    env_file:
      - ../../.env
    ports:
      - ${MYSQL_PORT}:3306

volumes:
  mysql_data:

.env

MYSQL_PORT=3306
MYSQL_ROOT_PASSWORD=root
MYSQL_DATABASE=final_project_database
MYSQL_USER=db_user
MYSQL_PASSWORD=some_db_user_password

CodePudding user response:

Use --env-file option with docker-compose up command. env_file declared in your MySQL service applies only for container env

CodePudding user response:

Move your .env file to the same directory as the docker-compose file and change the env_file to point to it. That way both docker-compose and the container will use the same environment file.

Right now it's only the container that's using it.

version: '3'
services:
  mysql:
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    volumes:
      - mysql_data:/var/lib/mysql
    env_file:
      - ./.env
    ports:
      - ${MYSQL_PORT}:3306

volumes:
  mysql_data:
  • Related