- 拉取镜像(mysql:5.7)
$ docker pull mysql:5.7
- 查看镜像
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE mysql 5.7 84164b03fa2e 11 days ago 456MB
- 创建一个临时的mysql,以便复制出my.cnf等数据
docker run --rm \
--name mysqlTemp \
-it \
-v /usr/local/mysql/:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=123456 \
mysql:5.7 \
/bin/bash
命令说明:
1. -v /usr/local/mysql/:/var/lib/mysql 将主机目录/usr/local/mysql/映射到Docker中的/var/lib/mysql目录
2. -- rm 退出后就删除该容器
3. -it 交互模式
4. /bin/bash 进入 bash 命令模式
- 复制出docker中的配置文件
复制docker容器中的配置到/var/lib/mysql目录中,也就是/usr/local/mysql中,因为这两个目录已经作了映射
cp /etc/mysql/my.cnf /var/lib/mysql
cp -R /etc/mysql/conf.d/ /var/lib/mysql/
cp -R /etc/mysql/mysql.conf.d/ /var/lib/mysql/
- 到/usr/local/mysql目录中修改mysql配置(略)
- 运行镜像
-v 挂载本地目录到docker中 -d 表示以守护进程模式运行 -m 限制容器可以使用的内存
docker run \
--name mysql \
-p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=123456 \
-m 512M --memory-swap=1024M \
-v /usr/local/mysql/data:/var/lib/mysql \
-v /usr/local/mysql/my.cnf:/etc/mysql/my.cnf \
-v /usr/local/mysql/conf.d:/etc/mysql/conf.d \
-v /usr/local/mysql/mysql.conf.d:/etc/mysql/mysql.conf.d \
-d mysql:5.7
- 进入运行着的mysql容器
#查询当前 mysql 容器id
[root@xiaodxserver local]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2ee0aadc1cc2 mysql:5.7 "docker-entrypoint.s…" 12 minutes ago Up 12 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysql
#进入容器中执行命令
[root@xiaodxserver local]# docker exec -it 2ee0aadc1cc2 /bin/bash
root@2ee0aadc1cc2:/#
root@2ee0aadc1cc2:/# 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 2
Server version: 5.7.29 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, 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.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
mysql> exit
准备文件
docker-compose.yml
# docker-compose --compatibility up -d
version: "3.1"
services:
mysql:
image: mysql:5.7
container_name: mysql
environment:
MYSQL_ROOT_PASSWORD: "yourpassword"
MYSQL_USER: 'test'
MYSQL_PASS: 'yourpassword'
restart: always
ports:
- 3306:3306
volumes: #不允许使用'/'根目录,
- /usr/local/mysql/data:/var/lib/mysql
- /usr/local/mysql/my.cnf:/etc/mysql/my.cnf
- /etc/localtime:/etc/localtime:ro
- /usr/local/mysql/conf.d:/etc/mysql/conf.d
- /usr/local/mysql/mysql.conf.d:/etc/mysql/mysql.conf.d
deploy:
resources:
limits:
memory: 512M
networks:
default:
external:
name: net-xiaodx #使用外部网络,要提前创建 docker network create net-xiaodx --driver bridge
注意:本文归作者所有,未经作者允许,不得转载