Docker 安装MySQL数据库并开启远程连接

docker安装MySQL数据库并开启远程连接

1.使用docker命令拉取镜像 这里以MySQL5.7版本为例

docker pull mysql:5.7

注: 如果要安装最新版本MySQL 执行命令

docker pull mysql:latest

2.查看镜像

docker images

3.在home目录下创建mysql文件夹

cd /home
mkdir mysql
cd /home/mysql

4.安装mysql

docker run -p 3306:3306 --name mysql --privileged=true \-v $PWD/conf:/etc/mysql/conf.d \-v $PWD/logs:/var/log/mysql \-v $PWD/data:/var/lib/mysql \-e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7
#命令解释:

	-p 3306:3306 暴露端口 将容器内3306端口映射到服务器端口
	--name mysql 设置容器名称
	--privileged=true 给容器加上特定权限
	-v PWD/conf:/etc/mysql/conf.d \
    -v PWD/logs:/var/log/mysql \
    -v $PWD/data:/var/lib/mysql   挂载容器文件目录到服务器文件目录
    -e MYSQL_ROOT_PASSWORD=123456 设置root用户密码
	-d mysql:5.7  后台运行
# Ubuntu 安装 非root账户要加上sudo
docker run -d --name mysql -v /home/sizhenpeng/data/mysql/data:/var/lib/mysql -p 3306:3306 --restart=always -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7 --character-set-server=utf8 --collation-server=utf8_general_ci 

为root账号开启远程连接权限

1.查看容器id

[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
bf9f65de3169        mysql:5.7           "docker-entrypoint..."   25 seconds ago      Up 24 seconds       0.0.0.0:3306->3306/tcp, 33060/tcp   mysql

2.进入容器

[root@localhost ~]# docker exec -it bf9f65de3169 /bin/bash

3.使用root用户登录MySQL数据库

root@bf9f65de3169:/# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, 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> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

4.修改root用户权限

mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
Query OK, 0 rows affected (0.00 sec)

5.刷新权限

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

你可能感兴趣的:(docker,常见问题,docker,mysql,docker,数据库)