I am attempting to create a mariadb container, and want to have a SQL script start at the beginning.
Base Dockerfile
FROM mariadb:10.5.6
# Copy a "creation.sql" script to the container
COPY /sql/* /sql/
Manual Execution Works
If I wait 10-20 seconds after the container is started, then do a command line docker exec -it my_container_name mysql -e "source sql/creation.sql;" -uroot -pMyPasswordHere
then the script runs fine. But I would rather have this part of the build or run processes, rather than requiring a manual step and a guess at waiting time.
RUN - Doesn't work
I tried using RUN
in the Dockerfile:
RUN mysql -e "source sql/creation.sql;" -uroot -p$MYSQL_ROOT_PASSWORD`
but it fails with: Can't connect to local MySQL server through socket during the build. I assume this is because the service hasn't started yet.
CMD - Doesn't work
I also tried executing creation.sql with mysql using ENTRYPOINT
and CMD
, but they seems to fail during the run. An example of CMD solution that should call mysqld
(matching what's in the mariadb Dockerfile) and then run the sql, but fails when running the container:
FROM mariadb:10.5.6
COPY /sql/* /sql/
CMD mysqld && mysql -e "source sql/creation.sql;" -uroot -p$MYSQL_ROOT_PASSWORD
CMD with shell script - Doesn't work
An example of a script-based solution which also fails:
FROM mariadb:10.5.6
COPY /sql/* /sql/
COPY /scripts/* /scripts/
CMD ["./scripts/start.sh"]
start.sh:
exec mysqld
echo "Running start script\n" > start.log
for i in {1..20}
do
sleep 3
echo "Attempt $i"
echo "Attempt $i" &>> start.log
mysql -e "source sql/creation.sql;" -uroot -p$MYSQL_ROOT_PASSWORD &>> start.log
done
echo "Done" &>> start.log
Is there a simple solution?
Is there any way to run a SQL script file just with the Dockerfile, or maybe a small shell script?