简体   繁体   中英

Bash script for creating default user in docker MySQL

I am developing a "one file script" for run MySQL database inside Docker and many useful thinks. The script should create a container with MySQL and after that create a new user with maximum privileges.

The problem occurs when I try to connect to MySQL command line from the bash script . Part of the script:

#!/bin/bash

mysqlContainerName=project-mysql
mysqlRootUsername=root
mysqlRootPassword=root_pass
mysqlUsername=db_user
mysqlPassword=db_pass
mysqlDb=project_db

echo -e "Creating container \e[31m$mysqlContainerName\e[0m"
docker run --rm -d \
  --name=$mysqlContainerName \
  --network api-network \
  -p 3306:3306 \
  -v /opt/docker-data/mysql-volumes:/var/lib/mysql \
  -e MYSQL_ROOT_PASSWORD=$mysqlRootPassword \
  -e MYSQL_DATABASE=$mysqlDb \
  -t mysql:8.0.19

docker exec $mysqlContainerName \
  mysql -h 127.0.0.1 -P 3306 --protocol=tcp \
  -uroot -p$mysqlRootPassword -e "CREATE USER '$mysqlUsername'@'localhost' IDENTIFIED BY 
'$mysqlPassword';"

So, container successfully created, but all the time I get an error message: ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111) Any suggestions?

So, after a few hours of searching, I found a solution. Added bash -c parameter and in quotes connection to MySQL and query.

docker exec $mysqlContainerName bash -c "mysql -h172.21.0.1 -P 3306 --protocol=tcp -u$mysqlRootUsername -p$mysqlRootPassword -e \"CREATE USER '$mysqlUsername'@'localhost' IDENTIFIED BY '$mysqlPassword';\"; exit;"

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