如何设置将数据从CSV文件加载到Docker容器中的PostgreSQL数据库中的路径?

如何设置将数据从CSV文件加载到Docker容器中的PostgreSQL数据库中的路径?

问题描述:

我想将CSV文件中的数据加载到Docker中的PostgreSQL数据库中。
我运行:

I would like to load data from CSV file into PostgreSQL database in Docker. I run:

docker exec -ti my project_db_1 psql -U postgres

然后我选择我的数据库:

Then I select my database:

\c myDatabase

现在我尝试从 myfile.csv ,它位于Django项目的主目录中,位于 backend_data 表中:

\copy backend_data (t, sth1, sth2) FROM 'myfile.csv' CSV HEADER;

但是我得到了错误:

myfile.csv: No such file or directory

在我看来我尝试了所有可能的路径,但没有任何效果。有什么想法我该如何解决?这是我的docker-compose.yml:

It seems to me that I tried every possible path and nothing works. Any ideas how can I solve it? This is my docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
  django:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db


最简单一种方法是将目录安装到postgres容器中,将文件放入安装的目录中,然后在其中引用。

The easiest way is to mount a directory into the postgres container, place the file into the mounted directory, and reference it there.

我们实际上是在安装 pgdata 目录,以确保即使我们重新创建postgres docker容器,postgres数据也可以存在。因此,我的示例还将使用 pgdata

We are actually mounting the pgdata directory, to be sure that the postgres data lives even if we recreate the postgres docker container. So, my example will also use pgdata:

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
    volumes:
      - "<path_to_local_pgdata>:/var/lib/postgresql/data/pgdata"

放置 myfile.csv 放入< path_to_local_pgdata> (相对于包含配置或绝对路径的目录)。复制命令如下所示:

Place myfile.csv into <path_to_local_pgdata> (relative to directory containing the config or absolute path). The copy command then looks like this:

\copy backend_data (t, sth1, sth2) FROM '/var/lib/postgresql/data/pgdata/myfile.csv' CSV HEADER;