一 安装
1 拉取镜像
[root@slave1 ~]# docker pull mysql:5.6
5.6: Pulling from library/mysql
b4f470726ddc: Pull complete
8ea446d3dd1a: Pull complete
a12b9de3971c: Pull complete
0cece02ee84c: Pull complete
81584261ce18: Pull complete
a511d4a68448: Pull complete
8e2451f19813: Pull complete
c1d341343e37: Pull complete
cde17f57816b: Pull complete
7a542d7e95c6: Pull complete
a06fd3c106ae: Pull complete
Digest: sha256:d0822b1b059e59fef7571b1a96224fb59fb0a84dffa59d8f3859281bde675a85
Status: Downloaded newer image for mysql:5.6
docker.io/library/mysql:5.6
2 运行容器
[root@slave1 ~]# docker run --name dockermysql -p 3307:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.6
04c144bd58c8cfa92ebf08d68ae77c29d04ae6424f09b6b5b5b595538946819e
# --name 为mysql的实例设置别名。
# -p 3307为对外暴露的端口。3306是内部端口
# -e MYSQL_ROOT_PASSWORD 设置mysql登录密码
# -d 以守护进程运行(后台运行) 最后的mysql是镜像名称
# 镜像如果不指定是之前拉取的镜像版本,会去拉取最新版本的
3 查看容器
[root@slave1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
04c144bd58c8 mysql:5.6 "docker-entrypoint.s…" 22 seconds ago Up 20 seconds 0.0.0.0:3307->3306/tcp dockermysql
4 进入容器进行远程登陆许可
# dockermysql 是上边运行时为容器取的别名 也可以用id替代
[root@slave1 ~]# docker exec -it dockermysql bash
root@04c144bd58c8:/# mysql -u root -p
Enter password: # 然后直接输入密码即可 密码是在运行时设置的
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
# 注意此处连接id为1
Server version: 5.6.51 MySQL Community Server (GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
# 给用于授予权限
# GRANT ALL PRIVILEGES ON *.* ‘root’@’%’ identified by ‘123123’ WITH GRANT OPTION; 这是网上流传较多的写法。实际上可能会报错的。
mysql> grant all privileges on *.* to 'root'@'%';
Query OK, 0 rows affected (0.00 sec)
# 刷新权限
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
# 退出数据库
mysql> exit
Bye
二 返回宿主机进行登陆数据库
返回宿主机使用组合键 Ctrl+P+Q
# Ctrl+P+Q从docker返回到宿主机
root@04c144bd58c8:/# read escape sequence
# 远程登陆127.0.0.1更改为宿主机IP地址即可
[root@slave1 ~]# mysql -h 127.0.0.1 -u root -p -P 3307
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 2
# 注意这个id是2
Server version: 5.6.51 MySQL Community Server (GPL)
# 版本为我们docker内安装的5.6
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
三 命令行登陆数据库
1 本地登陆
# 1.本地登录MySQL
命令:mysql -u root -p
//root是用户名,输入这条命令按回车键后系统会提示你输入密码
# 2.指定端口号登录MySQL数据库
将以上命令:mysql -u root -p
改为 mysql -u root -p -P 3306
# 注意指定端口的字母P为大写,而标识密码的p为小写。MySQL默认端口号为3306
2 远程登陆
# 3.指定IP地址和端口号登录MySQL数据库
命令格式为:mysql -h ip -u root -p -P 3306
例如:mysql -h 127.0.0.1 -u root -p -P 3306
例如: 在shell终端或者ssh终端,或者cmd窗口远程登录 端口为3308,用户名为user1,ip为 182.167.12.3 的mysql服务器的命令是
$ mysql -h 182.167.12.3 -u user1 -p -P 3308