简体   繁体   English

用于 postgres 数据的 docker 中的卷挂载

[英]Volume mount in docker for postgres data

I am trying to insert data into postgres using docker.我正在尝试使用 docker 将数据插入到 postgres 中。

I have a folder in my code named data which has insert commands and has one file named init.sql .我的代码中有一个名为 data 的文件夹,其中包含insert命令和一个名为init.sql的文件。
I want to insert the data from init.sql present in folder data to tables present in docker.我想将文件夹数据中存在的 init.sql 中的数据插入init.sql中存在的表中。

version: '3.1'

services:
  postgres:  
    image: postgres:11.6-alpine 
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tables:/docker-entrypoint-initdb.d/
      - ./data:/var/lib/postgresql/data
volumes:
  data: {}

I am trying this but I get the error:我正在尝试这个,但我得到了错误:

initdb: directory "/var/lib/postgresql/data" exists but is not empty initdb:目录“/var/lib/postgresql/data”存在但不为空

I think I am not using the correct use case, I am new to docker compose.我想我没有使用正确的用例,我是 docker 组合的新手。
But is there any way, my use case can get satisfied?但是有什么办法可以让我的用例得到满足吗?

This is caused by an improper usage of the volumes syntax for your named volume .这是由于命名卷volumes语法使用不当造成的。
In order to mount a named volume you have to just use its name like this:为了挂载一个命名卷,你必须像这样使用它的名字:

    volumes:
      - data:/var/lib/postgresql/data

If your syntax begins with a .如果您的语法以. then it will be a bind mount from your host.那么它将是来自您的主机的绑定挂载

    volumes:
      - ./data:/var/lib/postgresql/data

The above code is mounting the host folder data relative to where you your docker-compose.yml is located.上面的代码是相对于您的docker-compose.yml所在位置安装主机文件夹data

This docker-compose.yml should do what you expect.这个docker-compose.yml应该符合您的预期。

version: '3.1'

services:
  postgres:  
    image: postgres:11.6-alpine 
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tables:/docker-entrypoint-initdb.d/
      - data:/var/lib/postgresql/data
volumes:
  data:

If for some reason your volume has been created already, with an empty or no database, your first step should be running:如果由于某种原因已经创建了您的卷,并且数据库为空或没有数据库,那么您的第一步应该运行:

docker-compose down --volumes

From the documentation:从文档中:

-v, --volumes           Remove named volumes declared in the `volumes`
                        section of the Compose file and anonymous volumes
                        attached to containers.

From: https://docs.docker.com/compose/reference/down/来自: https://docs.docker.com/compose/reference/down/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM