查找MySQL镜像
镜像仓库
https://hub.docker.com/
下拉镜像
docker pull mysql:5.7
查看镜像
docker images
创建MySQL容器
命令式启动MySQL容器
docker run -p 3306:3306 --name mysql
-v /mydata/mysql/log:/var/log/mysql
-v /mydata/mysql/data:/var/lib/mysql
-v /mydata/mysql/conf:/etc/mysql
-e MYSQL_ROOT_PASSWORD=root
-d mysql:5.7
参数说明
-p 3306:3306: 将容器的3306端口映射到宿主机的3306端口
--name mysql:将容器名字设置为mysql
-v /mydata/mysql/log:/var/log/mysql:将日志文件夹挂载到宿主机
-v /mydata/mysql/data:/var/lib/mysql:将数据文件夹挂载到宿主机
-v /mydata/mysql/conf:/etc/mysql:将配置文件夹挂载到宿主机
-e MYSQL_ROOT_PASSWORD=root:初始化root用户的密码
-d mysql:5.7:后台运行容器,并返回容器ID
docker-compose启动
version: '2'
services:
mysql:
container_name: mysql
image: mysql:5.7
ports:
- "3306:3306"
volumes:
- /mydata/mysql/log:/var/log/mysql
- /mydata/mysql/data:/var/lib/mysql
- /mydata/mysql/conf:/etc/mysql
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
- COMPOSE_PROJECT_NAME=mysql-server
使用docker-compose方式启动可以很方便的查看容器的启动参数,命令启动方式可能会忘记启动参数。
查看容器
docker ps -a
进入容器
docker exec -it mysql /bin/bash
容器中文件
root@3873b46ee9b0:/# ls
bin boot dev docker-entrypoint-initdb.d entrypoint.sh etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
# 退出容器
root@3873b46ee9b0:/# exit;
就是一个linux系统。
配置MySQL
进入挂载数据卷
[root@k8s-master01 ~]# cd /mydata/mysql/
[root@k8s-master01 mysql]# ls
conf data log
[root@k8s-master01 mysql]# cd conf/
[root@k8s-master01 conf]# pwd
/mydata/mysql/conf
创建MySQL配置文件
cat > my.cnf <<-EOF
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
skip-name-resolve
EOF
注意:解决mysql连接慢问题,skip-name-resolve:跳过域名解析
重启MySQL容器
docker restart mysql
进入容器确认配置
[root@k8s-master01 conf]# docker exec -it mysql /bin/bash
root@3873b46ee9b0:/# cd /etc/mysql/
root@3873b46ee9b0:/etc/mysql# ls
my.cnf
root@3873b46ee9b0:/etc/mysql# cat my.cnf
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
skip-name-resolve
测试连接
Docker启动容器自启
docker update mysql --restart=always