赞
踩
Linux、Docker、云服务器
默认拉取最新版docker pull mysql
,指定版本docker pull mysql:版本号
[root@VM-4-15-centos ~]# docker pull mysql
拉取成功的话,输入docker images
会出现如下情况
[root@VM-4-15-centos local]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql latest 99afc808f15b 5 weeks ago 577MB
首先开放安全组
输入docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 --name my_mysql mysql
[root@VM-4-15-centos local]# docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 --name my_mysql mysql
abac92103cc8412888bc49c15b99c20acd4d9a4817732793fa96ec03d326deea
参数解读
run -d // 后台运行
-p 3306:3306 // 宿主机端口:容器内部端口 云服务器需要开放端口
-e MYSQL_ROOT_PASSWORD=123456 // 设置默认root用户密码为 123456
--name my_mysql // 容器名称
mysql // 镜像名
输入docker ps
,运行成功返回如下
[root@VM-4-15-centos local]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
abac92103cc8 mysql "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp my_mysql
首先 docker exec -it my_mysql bash
,进入容器
[root@VM-4-15-centos local]# docker exec -it my_mysql bash
bash-4.4#
登录mysqlmysql -uroot -p123456
[root@VM-4-15-centos local]# docker exec -it my_mysql bash
bash-4.4# mysql -uroot -p123456
进入成功返回如下
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.1.0 MySQL Community Server - GPL
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
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.
mysql>
添加远程连接用户alter user 'root'@'%' identified with mysql_native_password by '123456';
mysql> alter user 'root'@'%' identified with mysql_native_password by '123456';
Query OK, 0 rows affected (0.01 sec)
如果安装的是Mysql5.6左右的版本,使用如下语句
添加远程连接用户GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)
刷新权限flush privileges;
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
测试连接
现在当我们重启服务器,数据库远程连接时会出现
这是因为我们并没有设置开机自启动,服务器每次重启需要我们手动启动mysql容器docker start 容器id
。但是每次都手动启动未免也太麻烦了。
设置mysql容器自启动docker update --restart=always 容器id
[root@VM-4-15-centos ~]# docker update --restart=always 60b0da3e5819
60b0da3e5819
现在服务器重启时,就不需要我们再手动启动了
重启服务器,测试连接,成功
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。