When installing mysql in ubuntu with apt-get install mysql-server
, the mysql username and password are asked during the installation.
But when using a dockerfile to build a mysql image, how can the username and password be provided?
I tried using the dockerfile as follows:
FROM ubuntu:14.04
apt-get update
apt-get install -y mysql-server
But when building the image, I found out we can login in the mysql without username and password.
How can I set the username and password when I use dockerfile to build my images?
If you take a look at the official Docker MySQL image Dockerfile, you will discover how they did it using debconf-set-selections.
The relevant instructions are:
RUN { \
echo mysql-community-server mysql-community-server/data-dir select ''; \
echo mysql-community-server mysql-community-server/root-pass password ''; \
echo mysql-community-server mysql-community-server/re-root-pass password ''; \
echo mysql-community-server mysql-community-server/remove-test-db select false; \
} | debconf-set-selections \
&& apt-get update && apt-get install -y mysql-server
debconf-set-selections
is a tool that allows you to prepare the answers for the questions that will be asked during the later installation.
tutumcloud/mysql
Dockerfile
ADD run.sh /run.sh
ENV MYSQL_USER=admin \
MYSQL_PASS=**Random** \
ON_CREATE_DB=**False** \
REPLICATION_MASTER=**False** \
REPLICATION_SLAVE=**False** \
REPLICATION_USER=replica \
REPLICATION_PASS=replica
run.sh
StartMySQL ()
{
/usr/bin/mysqld_safe ${EXTRA_OPTS} > /dev/null 2>&1 &
# Time out in 1 minute
LOOP_LIMIT=60
for (( i=0 ; ; i++ )); do
if [ ${i} -eq ${LOOP_LIMIT} ]; then
echo "Time out. Error log is shown as below:"
tail -n 100 ${LOG}
exit 1
fi
echo "=> Waiting for confirmation of MySQL service startup, trying ${i}/${LOOP_LIMIT} ..."
sleep 1
mysql -uroot -e "status" > /dev/null 2>&1 && break
done
}
CreateMySQLUser()
{
if [ "$MYSQL_PASS" = "**Random**" ]; then
unset MYSQL_PASS
fi
PASS=${MYSQL_PASS:-$(pwgen -s 12 1)}
_word=$( [ ${MYSQL_PASS} ] && echo "preset" || echo "random" )
echo "=> Creating MySQL user ${MYSQL_USER} with ${_word} password"
mysql -uroot -e "CREATE USER '${MYSQL_USER}'@'%' IDENTIFIED BY '$PASS'"
mysql -uroot -e "GRANT ALL PRIVILEGES ON *.* TO '${MYSQL_USER}'@'%' WITH GRANT OPTION"
echo "=> Done!"
echo "========================================================================"
echo "You can now connect to this MySQL Server using:"
echo ""
echo " mysql -u$MYSQL_USER -p$PASS -h<host> -P<port>"
echo ""
echo "Please remember to change the above password as soon as possible!"
echo "MySQL user 'root' has no password but only allows local connections"
echo "========================================================================"
}
StartMySQL
CreateMySQLUser
.....helpful for u