• Linux 下使用 Docker 安装 MySQL


    1、下载 mysql

    docker pull mysql:5.7.36
    
    • 1

    2、启动 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=123456 \
    -d mysql:5.7.36
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    命令解析:

    -p 指定容器端口到主机端口的映射
    –name 指定容器名称
    -v 将主机上的对应目录挂载到容器的对应目录
    -e 设置环境变量
    -d 让容器在后台运行


    3、修改 mysql 配置文件 my.cnf

    vim /mydata/mysql/conf/my.cnf
    
    • 1

    更新配置文件

    [client]
    port = 3306
    password = 123456
    default-character-set=utf8
    
    [mysql]
    default-character-set=utf8
    
    [mysqld]
    port = 3306
    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    4、重启 mysql

    docker restart mysql
    
    • 1

    5、docker 查看日志

    docker logs mysql
    docker logs -f mysql  # 实时查看
    
    • 1
    • 2

    6、进入 mysql,连接 mysql 命令行

    [root@xxx ~]# docker exec -it mysql /bin/bash
    root@e83a22cd6197:/# mysql -uroot -p123456
    mysql> exit
    Bye
    root@e83a22cd6197:/# exit
    # 连接成功,即安装成功。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    7、设置 mysql 自动启动

    # 开启自启
    sudo docker update mysql --restart=always
    # 关闭自启
    sudo docker update mysql --restart=no
    
    • 1
    • 2
    • 3
    • 4

    8、mysql 权限设置语句

    use mysql;
    
    show tables;
    select user, host from user;
    
    # 允许远程访问
    update user set host = '%' where user = 'root' and host = 'localhost';
    
    # 添加一个指定 ip 的 root 用户
    create user 'root'@'xxx.xxx.xxx.xxx' identified by '123456';
    grant all privileges on *.* to 'root'@'xxx.xxx.xxx.xxx' with grant option;
    
    # 更新
    update user set host = 'xxx.xxx.%.%' where user = 'root' and host = 'xxx.xxx.xxx.xxx';
    flush privileges;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    9、注意,如果不指定 mysql 版本为 5.7.36,而是 5.7。可能出现错误

    mysqld: Can't read dir of '/etc/mysql/conf.d/' (Errcode: 2 - No such file or directory)
    
    • 1

    因为 mysql 新版本 5.7.43,配置文件路径改了,用原来的方式挂载目录会失效。


  • 相关阅读:
    Leetcode 386. 字典序排数
    《国际服务贸易》期末复习题 及答案参考
    C++ -- 类型转换
    @ControllerAdvice
    PyScript:让Python在HTML中运行
    CoreWCF 1.0.0 发布,微软正式支持WCF
    【css】如何实现自定义滚动悬浮置顶、固定表头
    Map集合之HashMap细说
    Codeforces Round #833 (Div. 2)A — C
    Redis-高性能原理剖析
  • 原文地址:https://blog.csdn.net/qq_44290077/article/details/133938066