shuttsy
shuttsy

Reputation: 1645

Docker mysql - run update command/script on image startup

I wish to build a docker image with an initialised database. This initial data will contain a default client ref value 'XXX'.

Here's my Dockerfile:

FROM mysql/mysql-server:5.7
COPY data.sql /docker-entrypoint-initdb.d/

When starting up the container of this image, I need to replace the ref value with the user's particular value, 'ABCD', which will come from an environment variable set by a docker compose file.

So the update query to run is something like:

update client set ref='ABCD' where ref='XXX'

How do I get the Dockerfile to do this? I don't think it can be a RUN command as I don't want the update to be part of the image build, but part of the startup of the image (it's fine if it runs this update on every startup).

I have all the usual mysql env varibles set (MYSQL_ROOT_PASSWORD/MYSQL_ROOT_HOST/MYSQL_DATABASE/MYSQL_USER/MYSQL_PASSWORD) and hope to refer to another env var for the desired ref to be setting. Keen to see this could be done as raw commands as well as a script.

Upvotes: 1

Views: 7069

Answers (1)

Alejandro Galera
Alejandro Galera

Reputation: 3691

You're right, Everything that you want to be persistent should be in the Dockerfile or in build: section of your docker-compose file.

As you want to have the update only in docker run or docker-compose up phase, you can use CMD or ENTRYPOINT to execute it. There are several ways, but let me recommend the following one:

docker-compose.yml

version: '3'

services:
  your-service:
    env_file: ./your-mysql-env-file.env
    image: mysql/mysql-server:5.7
    volumes:
      - ./data.sql:/docker-entrypoint-initdb.d/data.sql
      - ./your-init-sql-commands.sql:/docker-entrypoint-initdb.d/your-init-sql-commands.sql
    container_name: your-container-name
    command:
      - /bin/bash
      - -c
      - |
          /etc/init.d/mysqld start
          mysql -u ${MYSQL_USER} -p ${MYSQL_PASSWORD} -h ${MYSQL_ROOT_HOST} ${MYSQL_DATABASE} < your-init-sql-commands.sql
          [other commands if needed...]
  • Note that your update client set ref='ABCD' where ref='XXX' should be defined inside your-init-sql-commands.sql. So, if you want to change updates, you won't need to rebuild image.

  • your-mysql-env-file.env just define inside it your MYSQL env variables if you need them inside.

  • Note that I've changed your dockerfile by image:section and COPY by volumes: in docker-compose.yml, but all this steps can be also done with Dockerfile and docker run.
  • If you don't need a multiple command, just change all lines by a single one.

I hope this can be helpful for you.

Upvotes: 0

Related Questions