5.2 数据持久化之Data Volume

使用场景:mysql容器在被销毁之后,数据可以持久化

初始化一个mysql容器

# 为了便于测试,设置root密码为空
docker run -d --name mysql1 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mysql:latest

查看mysql容器对应的volume

Mountpoint 的值 /var/lib/docker/volumes/5bcd1cb1088a71fbf595fb817ea9511501f794ac17971529cd3451102f872a87/_data,就是mysql容器保存数据到虚拟机的地方了


[vagrant@docker-node1 ~]$ docker volume ls
DRIVER VOLUME NAME
local 5bcd1cb1088a71fbf595fb817ea9511501f794ac17971529cd3451102f872a87


[vagrant@docker-node1 ~]$ docker volume inspect 5bcd1cb1088a71fbf595fb817ea9511501f794ac17971529cd3451102f872a87
[
    {
        "CreatedAt": "2018-07-03T12:12:36Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/5bcd1cb1088a71fbf595fb817ea9511501f794ac17971529cd3451102f872a87/_data",
        "Name": "5bcd1cb1088a71fbf595fb817ea9511501f794ac17971529cd3451102f872a87",
        "Options": null,
        "Scope": "local"
    }
]

删除mysql容器

docker container stop mysql1
docker container rm mysql1

删除之后发现该容器对应的volume还是存在的,这也就是mysql数据的持久化了

如果是降级mysql的版本,由于volume data的存在,可能低版本的mysql不兼容,导致出现问题,此时还需要删除volume data。

命名Volume

[vagrant@docker-node1 ~]$ docker run -d -v mysql:/var/lib/mysql --name mysql2 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mysql:latest
028c9a31c4b1bbe0ef1aa40517e881fb655d2efb81d5591460c323b320ac2e84
[vagrant@docker-node1 ~]$ docker volume ls
DRIVER VOLUME NAME
local mysql
[vagrant@docker-node1 ~]$ docker volume inspect mysql
[
    {
        "CreatedAt": "2018-07-03T12:25:48Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/mysql/_data",
        "Name": "mysql",
        "Options": null,
        "Scope": "local"
    }
]

持久化数据的使用

进入到mysql2容器,创建一个数据库,名称为docker

docker exec -it mysql2 /bin/sh
mysql -u root
mysql> create database docker;
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| docker |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)

然后删除mysql2容器

docker container stop mysql2
docker container rm mysql2

创建一个mysql3容器

docker run -d -v mysql:/var/lib/mysql --name mysql3 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mysql:latest
docker exec -it mysql3 /bin/sh
mysql -u root
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| docker |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)

nice!发现docker数据库在容器mysql3中依然是可以使用的。

你可能感兴趣的:(docker)