使用Docker卷持久化数据库 [英] Persisting database using docker volumes

查看:121
本文介绍了使用Docker卷持久化数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将postgres数据保留在Docker容器中,以便一旦您 docker-compose down和docker-compose up -d ,您就不会丢失上次会话中的数据。我无法做任何事情-拉下容器并再次备份会定期删除数据。

I'm trying to persist postgres data in a docker container so that as soon as you docker-compose down and docker-compose up -d you don't lose data from your previous session. I haven't been able to make it do much of anything - pulling the container down and back up again routinely deletes the data.

这是我当前的docker-compose.yml :

Here's my current docker-compose.yml:

version: '2'
services:
  api:
    build: .
    ports:
      - '8245:8245'
    volumes:
      - .:/home/app/api
      - /home/app/api/node_modules
      - /home/app/api/public/src/bower_components
    links:
      - db
  db:
    build: ./database
    env_file: .env
    ports:
      - '8246:5432'
    volumes_from:
      - dbdata

  dbdata:
    image: "postgres:9.5.2"
    volumes:
      - /var/lib/postgresql/data

帮助?

推荐答案

根据停泊Docker Compose ,当您编写如下内容时:

According to the Dockment of Docker Compose, when you write something like:

volumes:
  - /var/lib/postgresql/data

它将创建一个新的泊坞窗卷并将其映射到容器内的 / var / lib / postgresql / data 中。
因此,每次您运行 docker-compose up docker-compose down 时,都会创建新卷。您可以使用 docker volume ls 确认行为。

It creates a new docker volume and map it to /var/lib/postgresql/data inside the container. Therefore, each time you run docker-compose up and docker-compose down, it creates new volume. You can confirm the behavior with docker volume ls.

要避免这种情况,您有两种选择:

To avoid it, you have two options:

(A)将主机目录映射到容器中

您可以将主机目录映射到容器中使用< HOST_PATH>:< CONTAINER_PATH>

You can map directory of host into container using <HOST_PATH>:<CONTAINER_PATH>.

volumes:
  - /path/to/your/host/directory:/var/lib/postgresql/data

postgresql的数据将保存到容器主机的 / path / to / your / host /目录

The data of postgresql will be saved into /path/to/your/host/directory of the container host.

(B)使用外部容器

docker-compose具有外部容器
设置为true时,不会总是创建音量。
这是一个示例。

docker-compose has an option of external container. When it is set to true, it won't always create volume. Here's an example.

version: '2'
services:
  dbdata:
    image: postgres:9.5.2
    volumes:
      - mypostgresdb:/var/lib/postgresql/data
volumes:
  mypostgresdb:
    external: true

带有 external:true ,docker-compose不会创建 mypostgredb 卷,因此您必须使用以下命令自行创建卷:

With external: true, docker-compose won't create the mypostgredb volume, so you have to create it by your own using following command:

docker volume create --name=mypostgredb

postgresql的数据将保存到名为 mypostgredb 的Docker卷中。阅读参考以获得更多详细信息。

The data of postgresql will be saved into docker volume named mypostgredb. Read reference for more detail.

这篇关于使用Docker卷持久化数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆