# docker 数据备份和恢复

如果docker容器和宿主机之间已经有目录的映射关系的话，直接将容器中需要备份的内容直接存储到映射的目录下即可。

但我们也提供一种没有作映射情况下数据备份和恢复的方法。

![](/files/-MBRm-t6O9q3flYMVlvo)

这是备份和恢复的原理图，下面我们看看具体的实现步骤。

## 数据备份

启动一台数据卷容器

```bash
$ docker run -it -v /data --name testvol centos bash
b7dd298e27bfceaecf1242ecfe3b6fb8bc8ade37c912f963980c7bad511d849f
```

在容器目录中写入数据

```bash
[root@b7dd298e27bf /]# echo "123" > /data/123     
[root@b7dd298e27bf /]#
```

创建宿主机备份数据存放目录

```bash
$ mkdir /data/backup
```

新建备份容器

```bash
docker run --volumes-from testvol -v /data/backup/:/backup centos tar cvf /backup/data.tar /data/
```

说明：首先我们需要使用testvol数据卷新开一个容器，同时我们还需要把本地的`/data/backup/`目录挂载到该容器的`/backup`下，这样在容器中`/backup`目录里面新建的文件，我们就可以直接在`/data/backup/`目录中看到了。 然后再把`/data/`目录下面的文件打包到成data.tar文件放到`/backup`目录下面。

## 恢复

思路： 先新建一个数据卷容器，再建一个新的容器并挂载该数据卷容器，然后再把tar包解包

新建数据卷容器

```bash
docker run -itd -v /data/ --name testvol2 centos bash
```

挂载数据卷新建容器，并解包

```bash
docker run --volumes-from testvol2  -v /data/backup/:/backup centos tar xf /backup/data.tar
```

> 注：如果容器和宿主机之间有映射关系直接复制就可以了，不需要这么麻烦！！


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lack.gitbook.io/operation-and-maintenance/rong-qi-yu-xu-ni-hua/docker-shu-ju-bei-fen-he-hui-fu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
