Search code examples
mysqldatabasedockerdocker-composeenvironment

Docker Set Up mysql db environment


Hello guys im setting up an new wordpress docker machine im on the point to configure my sql db :

  db:
    build:
      context: ./Docker/mysql
      dockerfile: Dockerfile
    container_name: mysql
    volumes:
       - db_data:/var/lib/mysql
    environment:
        MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}"
        MYSQL_DATABASE: "${DB_NAME}"
        MYSQL_USER: "${DB_USERNAME}"
        MYSQL_PASSWORD: "${DB_PASSWORD}"
    networks:
      - back

Dockerfile for sql:

FROM mysql:latest

this also works fine problem is i don't realy know where i should set the environment props like db name user and so on. any suggestions?


Solution

  • You could set that as environment vars on the server, but if you don't want to do that you could set them for the compose command:

    DB_ROOT_PASSWORD=asdf DB_NAME=mydb DB_USERNAME=user DB_PASSWORD=pw docker compose
    

    In the comments you said that you wanted to set the vars in the Dockerfile. Below is an example:

    FROM mysql:latest
    
    ENV MYSQL_ROOT_PASSWORD=asdf
    ENV MYSQL_DATABASE=mydb
    ENV MYSQL_USER=user
    ENV MYSQL_PASSWORD=pw
    

    If you do not want these hardcoded in the Dockerfile, you could combine them with build time arguments.

    FROM mysql:latest
    
    ENV MYSQL_ROOT_PASSWORD=$db_root_pw
    ENV MYSQL_DATABASE=$db_name
    ENV MYSQL_USER=$db_username
    ENV MYSQL_PASSWORD=$db_pw
    

    Make sure to include the arguments when building the image:

    docker build --build-arg db_root_pw=rootpw --build-arg db_name=mydb --build-arg db_username=user --build-arg db_pw=pw # [...]