第一步:首先安装docker 和docker-compose

这里使用快速安装脚本进行安装

1
curl -sSL https://get.daocloud.io/docker | sh

第二步:新建/data/mysql目录    data文件是我以后存放所有安装的容器地址

新建一个docker-compose.yml文件夹 

1
version: '3'services:  mysql:    image: mysql:5.7    restart: always    container_name: mysql    environment:      MYSQL_ROOT_PASSWORD: chen    command:      --default-authentication-plugin=mysql_native_password      --character-set-server=utf8mb4      --collation-server=utf8mb4_general_ci      --explicit_defaults_for_timestamp=true      --lower_case_table_names=1      --max_allowed_packet=128M;    ports:      - 3306:3306    volumes:      - /data/mysql:/var/lib/mysql      - /etc/localtime:/etc/localtime:ro~                                        

默认数据库是账号是root

密码自己修改  MYSQL_ROOT_PASSWORD

进入到docker compose文件的目录下面   命令启动mysql 使用 docker compose up -d  (启动容器命令,一定要在需要启动容器目录下面去执行这个命令 都在他会把这个目录下面所有的容器都会启动)

-d 代表后台运行

问题:

这里可能会遇到没有权限的情况

1
[root@localhost ~]# docker compose up -d-bash: /usr/local/bin/docker-compose: 权限不够

解决方法

1
chmod +x /usr/local/bin/docker-compose

执行后等待安装完成

1
[root@localhost ~]# docker-compose up -dPulling mysql (mysql:5.7)...5.7: Pulling from library/mysqle048d0a38742: Pull completec7847c8a41cb: Pull complete351a550f260d: Pull complete8ce196d9d34f: Pull complete17febb6f2030: Pull completed4e426841fb4: Pull completefda41038b9f8: Pull completef47aac56b41b: Pull completea4a90c369737: Pull complete97091252395b: Pull complete84fac29d61e9: Pull completeDigest: sha256:8cf035b14977b26f4a47d98e85949a7dd35e641f88fc24aa4b466b36beecf9d6Status: Downloaded newer image for mysql:5.7Creating mysql ... done

使用docker命令看一下mysql容器是否已经启动 docker ps 

1
[root@localhost ~]# docker psCONTAINER ID   IMAGE       COMMAND                   CREATED         STATUS         PORTS                                                  NAMES3023aafe6fff   mysql:5.7   "docker-entrypoint.s…"   4 seconds ago   Up 2 seconds   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql

如果要打命令我们可以进入容器内

1
docker exec -it 容器名 /bin/bash
1
bash-4.2# mysql -u root -pchenmysql: [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 3Server version: 5.7.41 MySQL Community Server (GPL) Copyright (c) 2000, 2023, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>  mysql> show databases;+--------------------+| Database           |+--------------------+| information_schema || mysql              || performance_schema || sys                |+--------------------+4 rows in set (0.00 sec)

到这里我们就成功的使用docker compose安装了mysql

在windows下我们也是可以正常连接到mysql的

如果在外部连接不上可以关闭下防火墙

1
systemctl stop firewalld