第一步:首先安装docker 和docker-compose
这里使用快速安装脚本进行安装
curl -sSL https://get.daocloud.io/docker | sh
第二步:新建/data/mysql目录 data文件是我以后存放所有安装的容器地址
新建一个docker-compose.yml文件夹
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 代表后台运行
这里可能会遇到没有权限的情况
[root@localhost ~]# docker compose up -d
-bash: /usr/local/bin/docker-compose: 权限不够
解决方法
chmod +x /usr/local/bin/docker-compose
执行后等待安装完成
[root@localhost ~]# docker-compose up -d
Pulling mysql (mysql:5.7)...
5.7: Pulling from library/mysql
e048d0a38742: Pull complete
c7847c8a41cb: Pull complete
351a550f260d: Pull complete
8ce196d9d34f: Pull complete
17febb6f2030: Pull complete
d4e426841fb4: Pull complete
fda41038b9f8: Pull complete
f47aac56b41b: Pull complete
a4a90c369737: Pull complete
97091252395b: Pull complete
84fac29d61e9: Pull complete
Digest: sha256:8cf035b14977b26f4a47d98e85949a7dd35e641f88fc24aa4b466b36beecf9d6
Status: Downloaded newer image for mysql:5.7
Creating mysql ... done
使用docker命令看一下mysql容器是否已经启动 docker ps
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3023aafe6fff 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
如果要打命令我们可以进入容器内
docker exec -it 容器名 /bin/bash
bash-4.2# mysql -u root -pchen
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 3
Server 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 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>
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
到这里我们就成功的使用docker compose安装了mysql
在windows下我们也是可以正常连接到mysql的
如果在外部连接不上可以关闭下防火墙
systemctl stop firewalld