Search code examples
mysqlsqlimportdocker-composesql-scripts

Docker compose does not execute .sql


Trying to use docker compose for my application, so using official mysql images and my own Dockerfile to create my app image. I think some how my initdb.sql is not executed during docker compose up.

Running this as :

docker-compose up --build

But I can not see that initdb.sql is executed.

My docker compose looks like this:

version: "3"
services:
  db:
    image: mysql:5.7
    restart: always
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_DATABASE: "MYDB"
      MYSQL_USER: "myuser"
      MYSQL_PASSWORD: "mypassword"
      MYSQL_ROOT_PASSWORD: "mypassword"
    ports:
      - "3306:3306"
    expose:
      - "3306"
    volumes:
      - my-db:/var/lib/mysql
      - ./sqlinit:/docker-entrypoint-initdb.d/initdb.sql
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
  app:
    restart: always
    build: .
    ports:
      - 5000:5000
    volumes:
      - .:/app
    depends_on:
      - db
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

volumes:
  my-db:

networks:
  vpcbr:
    driver: bridge
    ipam:
      config:
        - subnet: 10.5.0.0/16
        #  gateway: 10.5.0.1

As you can see I have my initdb.sql in this directory ./sqlinit and after I login to mysql container I can see this file in /docker-entrypoint-initdb.d/initdb.sql

But looks like is not executed because when I login to my app I can see:

pymysql.err.OperationalError: (1044, "Access denied for user 'myuser'@'%' to database 'MYDB'")

and on container mysql

2019-09-15T13:17:59.361447Z 2 [Note] Access denied for user 'myuser'@'%' to database 'MYDB

Of course I'm doing something wrong, I found some similar problems here but I still haven't fixed my issue


Solution

  • The problem should be in the way you are mapping the volume. You should map the source file into the target file instead of a source folder into a file, like so:

    - ./sqlinit/initdb.sql:/docker-entrypoint-initdb.d/initdb.sql