How to install mysql with vagrant

修改Vagrantfile


1
2
3
4
5
6
# 把客户机器(ubuntu)的port 3306 映射到宿主机器上的port 3306
config.vm.network :forwarded_port, guest: 3306, host: 3306

# 执行安装程序
config.vm.provision :shell :path => "install_mysql.sh"

mysql安装程序


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash
echo "Setup mysql-server-5.5 if not exists.."
sudo debconf-set-selections <<< 'mysql-server-5.5
mysql-server/root_password password root'
sudo debconf-set-selections <<< 'mysql-server-5.5
mysql-server/root_password_again password root'
sudo apt-get update
sudo apt-get -y install mysql-server-5.5

if [ ! -f /var/log/databasesetup ];
then
echo "CREATE USER 'codeeker' IDENTIFIED BY 'codeeker'" | mysql -uroot -proot
echo "CREATE DATABASE mall" | mysql -uroot -proot
echo "GRANT ALL ON mall.* TO 'codeeker'@'%'" | mysql -uroot -proot
echo "flush privileges" | mysql -uroot -proot

touch /var/log/databasesetup #为了不重复执行创建用户的操作

if [ -f /vagrant/data/initial.sql ];
then
mysql -uroot -proot codeeker < /vagrant/data/initial.sql
fi
fi

陷阱

错误一

  • 报错误Lost connection to MySQL server at 'reading initial communication packet', system error: 0
  • 原因是 /etc/mysql/my.cnf中有bind-address = 127.0.0.1,会拒绝非localhost的访问,包括vagrant映射port到的宿主主机上
  • 解决的方法是修改bind-address = 0.0.0.0,表示接受本网络中所有的ip登录

错误二

echo "CREATE USER 'codeeker' IDENTIFIED BY 'codeeker'" | mysql -uroot -proot

如果写成了

echo "CREATE USER 'codeeker'@'localhost' IDENTIFIED BY 'codeeker'" | mysql -uroot -proot

那么在宿主的机器上,会报access deny错误。

  • 原因是这样创建的用户,只能在localhost上登录
  • 解决的方法是去掉@'localhost'