简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM