mjwrazor
mjwrazor

Reputation: 1964

How to execute a Bash script into a mysql docker container every time it starts

I need to execute these commands on every startup since it looks to be overwritten every time I set and restart it

mysql -uroot -padmin;
set global general_log = 1;

I start the docker container with docker-compose for development purposes only and it looks like this.

version: "3.8"
services:
  mysql_service:
    container_name: db_container
    build:
        context: .
        dockerfile: ./db/Dockerfile.dev
    # needed for mysql 8+
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    hostname: db
    ports:
      - target: 3306
        published: 3306
        protocol: tcp
        mode: host
    environment:
      - MYSQL_ROOT_PASSWORD=admin
      - MYSQL_DATABASE=example
      - MYSQL_ROOT_HOST=localhost
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - ./db/:/docker-entrypoint-initdb.d/
      - data_volume:/var/lib/mysql/
    cap_add:
      - ALL
      
volumes:
  data_volume:
    driver: local

and the Dockerfile

FROM mysql:8.0

COPY ./DevOps/Docker/db/set_logging.sh /usr/local/bin
ENTRYPOINT ["docker-entrypoint.sh", "./usr/local/bin/set_logging.sh"]

However the copy goes through but the script is never executed. Where the script looks like

#!/bin/bash
mysql -uroot -padmin -e "set global general_log = 1"

Any suggestions on getting this command to go through? This is only for development

Upvotes: 1

Views: 3646

Answers (1)

Affes Salem
Affes Salem

Reputation: 1649

In order to tell MYSQL container to run that script once it starts you can either mount the script into the image's /docker-entrypoint-initdb.d folder using docker file, or docker-compose file using bind mount volume.

Dockerfile

FROM mysql:8.0
COPY ./DevOps/Docker/db/script.sh /docker-entrypoint-initdb.d/script.sh
ENTRYPOINT ["docker-entrypoint.sh"]

docker-compose

version: "3.8"
services:
  mysql_service:
    container_name: db_container
    build:
        context: .
        dockerfile: ./db/Dockerfile.dev
    # needed for mysql 8+
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    hostname: db
    ports:
      - target: 3306
        published: 3306
        protocol: tcp
        mode: host
    environment:
      - MYSQL_ROOT_PASSWORD=admin
      - MYSQL_DATABASE=example
      - MYSQL_ROOT_HOST=localhost
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - "./DevOps/Docker/db/script.sh:/docker-entrypoint-initdb.d/script.sh"  
      - data_volume:/var/lib/mysql/
    cap_add:
      - ALL
      
volumes:
  data_volume:
    driver: local

You can check how scripts are launched in /docker-entrypoint-initdb.d read the Initializing a fresh instance Section

Upvotes: 0

Related Questions