title: How to run a query in docker container after mariadb has started?
body: <p>I am attempting to create a mariadb container, and want to have a SQL script start at the beginning.</p>
  <p><strong>Base Dockerfile</strong></p>
  <pre><code>FROM mariadb:10.5.6
  # Copy a &quot;creation.sql&quot; script to the container
  COPY /sql/* /sql/
  </code></pre>
  <p><strong>Manual Execution Works</strong></p>
  <p>If I wait 10-20 seconds after the container is started, then do a command line <code>docker exec -it my_container_name mysql -e &quot;source sql/creation.sql;&quot; -uroot -pMyPasswordHere</code> 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.</p>
  <p><strong>RUN - Doesn't work</strong></p>
  <p>I tried using <code>RUN</code> in the Dockerfile:</p>
  <pre><code>RUN mysql -e &quot;source sql/creation.sql;&quot; -uroot -p$MYSQL_ROOT_PASSWORD`
  </code></pre>
  <p>but it
  fails with: <em>Can't connect to local MySQL server through socket</em> during the build. I assume this is because the service hasn't started yet.</p>
  <p><strong>CMD - Doesn't work</strong></p>
  <p>I also tried executing creation.sql with mysql using <code>ENTRYPOINT</code> and <code>CMD</code>, but they seems to fail during the run. An example of CMD solution that should call <code>mysqld</code> (matching what's in the <a href="https://github.com/MariaDB/mariadb-docker/blob/master/10.5/Dockerfile" rel="nofollow noreferrer">mariadb Dockerfile</a>) and then run the sql, but fails when running the container:</p>
  <pre><code>FROM mariadb:10.5.6
  COPY /sql/* /sql/
  CMD mysqld &amp;&amp; mysql -e &quot;source sql/creation.sql;&quot; -uroot -p$MYSQL_ROOT_PASSWORD
  </code></pre>
  <p><strong>CMD with shell script - Doesn't work</strong></p>
  <p>An example of a script-based solution which also fails:</p>
  <pre><code>FROM mariadb:10.5.6
  COPY /sql/* /sql/
  COPY /scripts/* /scripts/
  CMD [&quot;./scripts/start.sh&quot;]
  </code></pre>
  <p>start.sh:</p>
  <pre class="lang-sh prettyprint-override"><code>exec mysqld
  echo &quot;Running start script\n&quot; &gt; start.log
  for i in {1..20}
  do
      sleep 3
      echo &quot;Attempt $i&quot;
      echo &quot;Attempt $i&quot; &amp;&gt;&gt; start.log
      mysql -e &quot;source sql/creation.sql;&quot; -uroot -p$MYSQL_ROOT_PASSWORD &amp;&gt;&gt; start.log
  done
  echo &quot;Done&quot; &amp;&gt;&gt; start.log
  </code></pre>
  <p><strong>Is there a simple solution?</strong></p>
  <p>Is there any way to run a SQL script file just with the Dockerfile, or maybe a small shell script?</p>