How can I import a .sql file once I start up my docker-compose file?

Everything else is working for me except that aspect

There are 3 ways you can do it.

Method 1 - Docker Volumes

In your docker-compose file, map the .sql file to the init.d folder for MySQL.

mysql:
  volumes:
    - ./docker/mysql/data:/var/lib/mysql:rw
    - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro

Method 2 - Use Docker EXEC Command

If Method 1 didn’t work and only created the /docker-entrypoint-initdb.d/schema.sql file in the container, you can run the following command to execute the import command.

docker exec -it mysql_container mysql -u root -p database_name < /docker-entrypoint-initdb.d/schema.sql

Please note, that the root password needs to be the same as the root password you set as the MYSQL_ROOT_PASSWORD environmental variable for the container.

Method 3 - Create a Custom MySQL Image

Create a new image from the MySQL image and add the .sql to the MySQL init.d folder.

From mysql:latest

Copy ./database/schema.sql /docker-entrypoint-initdb.d/schema.sql
1 Like