在docker越来越流行的今天,身为一名开发人员,也要跟上节奏。
用docker来模拟环境,切换环境都非常方便,今天我们先把mysql用docker跑起来。
安装
首先需要注意的是,使用的镜像为mysql/mysql-server
,这个镜像是在linux环境下使用的,其他系统可能会有问题。
我们使用--mount
参数,来映射data目录和my.cnf配置文件,可以保证以后更换docker镜像的时候比较方便。
使用-p 3306:3306
来将端口从容器中映射出来。
1
2
3
4
5
|
docker run --name=mysql1 \
--mount type=bind,src=/data/mysql/my.cnf,dst=/etc/my.cnf \
--mount type=bind,src=/data/mysql/data,dst=/var/lib/mysql \
-p 3306:3306 \
-d mysql/mysql-server:5.7
|
贴上一份默认的my.cnf,便于以后使用。
默认的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html
[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
skip-host-cache
skip-name-resolve
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
secure-file-priv=/var/lib/mysql-files
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
|
安装之后
初始化完成之后,随机密码会被记录在log里,可以使用下面的命令查询:
1
|
docker logs mysql1 2>&1 | grep GENERATED
|
当服务启动以后,我们可以从刚启动的容器中进入客户端,然后修改密码:
1
2
3
|
docker exec -it mysql1 mysql -uroot -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password';
|
使用如下命令,可以启动一个容器中的shell:
1
|
docker exec -it mysql1 bash
|
远程访问
远程访问需要做两件事,一件是打开端口,一件是付给用户权限。
由于我是在虚拟机中运行的,所以直接用了方便的方式–关闭防火墙。
付给权限因为是自己测试使用,所以直接付给了roor
用户,使用如下命令:
1
2
3
|
use mysql;
grant all privileges on *.* to root@'%' identified by "password";
flush privileges;
|
如果放在服务器运行,一定要控制好权限哦~
后记
docker化以后,mysql的管理明显方便多了。经测试,使用docker rm
删除容器之后,再次新建数据也不会丢失。
对于mysql的一般使用已经足够。