skip to Main Content

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

2

Answers


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

    Login or Signup to reply.
  2. 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:
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search