24

I am trying to set up a mysql docker container and execute init sql script. Unfortunately the sql script is not executed. What am I doing wrong?

version: '3.3'
services:
  api:
    container_name: 'api'
    build: './api'
  ports:
    - target: 8080
      published: 8888
      protocol: tcp
      mode: host
  volumes:
    - './api:/go/src/app'
  depends_on:
    - 'mysql'
 mysql:
  image: 'mysql:latest'
  container_name: 'mysql'
  volumes:
    - ./db_data:/var/lib/mysql:rw
    - ./database/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
  restart: always
  environment:
    MYSQL_USER: test
    MYSQL_PASSWORD: test
    MYSQL_ROOT_PASSWORD: test
    MYSQL_DATABASE: test
  ports:
    - '3306:3306'
volumes:
  db_data:

I execute file with docker-compose up -d --build

2
  • 3
    The db_data folder probably has data from a previous run of the container. Try cleaning up the containers, removing the data folder and start again Commented Nov 11, 2018 at 14:02
  • Thank you! Deleting db_data folder solved it! Commented Nov 11, 2018 at 14:08

3 Answers 3

27

The docker-entrypoint-initdb.d folder will only be run once while the container is created (instantiated) so you actually have to do a docker-compose down -v to re-activate this for the next run.

If you want to be able to add sql files at any moment you can look here at a specialized MySql docker image... http://ivo2u.nl/o4

Update for M1 arch: Here an almost drop-in replacement in MariaDB: http://ivo2u.nl/V1

Sign up to request clarification or add additional context in comments.

1 Comment

"docker compose down -v" helped me deleting the volumes
15

Many containerized applications, especially stateful ones, have a way of running init scripts (like the sql scripts here) and they are supposed to run only once.

And since they are stateful, the volumes are a source of truth for the containers on whether to run the init scripts or not on container restart.

Like in your case, deleting the folder used for bind mount or using a new named volume should re-run any init scripts present.

2 Comments

How do you find out what the bind mount folder is?
In most cases it is the folder which is mounted to /var/lib/mysql. This is the default for mysql and can be changed (mounted) in mysql.cnf file. In the example above the bind is ./db_data.
1

These scripts run when you create the container, not every time you start it.

You can docker-compose up --force-recreate mysql to force those scripts to re-run.

Additionally, if you have a volume like this ./db_data:/var/lib/mysql:rw, then you also need to remove ./db_data before recreating the container.

I'm not a docker expert, but this worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.