Docker新建MySQL容器時自動初始化資料

riba2534發表於2020-09-30

場景

需要寫一個 Dockerfile 來實現建立 mysql 容器的時候,匯入已經準備好的 .sql 檔案.

解決

剛開始自己模擬過程寫,最後發現不行,仔細看文件,原來官方已經寫了。 文件

Initializing a fresh instance
When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

所以可以寫以下 Dockerfile

FROM mysql:latest
ENV MYSQL_ROOT_PASSWORD 123456
ENV MYSQL_USER=example
ENV MYSQL_PASSWORD=123456
COPY example.sql /docker-entrypoint-initdb.d/

然後 docker build -t mysql-test . && docker run -d mysql-test,此時進入容器中已經可以看見 example.sql 已經匯入到了資料庫

在實際使用中,這麼簡單的東西往往不需要使用 Dockerfile,可以在編寫 docker-compose.yml 檔案中加上:

volumes:
  - ./docker/mysql/scripts:/docker-entrypoint-initdb.d
  - ./mysql_data:/var/lib/mysql

參考資料

  1. https://stackoverflow.com/questions/38504257/mysql-scripts-in-docker-entrypoint-initdb-are-not-executed

相關文章