docker 如何在postgresql中导入和管理数据库?

How to import and manage the database in postgresql on the docker?

我的 Django 项目的结构如下:

myapp/
    manage.py
    Dockerfile
    docker-compose.yml
    my-database1.sql
    my-database2.sql
    requirements.txt
    pgadmin/
    pgadmin-data/
    myapp/
        __init__.py
        settings.py
        urls.py
        wsgi.py

这是我的 docker-compose.yml 文件:

version: "3.9"
   
services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
      - ./my-database1.sql:/docker-entrypoint-initdb.d/my-database1.sql
      - ./my-database2.sql:/docker-entrypoint-initdb.d/my-database2.sql
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - PGDATA=/var/lib/postgresql/data
  
  pgadmin:
    image: dpage/pgadmin4:4.18
    restart: unless-stopped
    environment:
      - PGADMIN_DEFAULT_EMAIL=admin@domain.com
      - PGADMIN_DEFAULT_PASSWORD=admin
      - PGADMIN_LISTEN_PORT=80
    ports:
      - "8090:80"
    volumes:
      - ./pgadmin-data:/var/lib/pgadmin
    links:
      - "db:pgsql-server"


  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

volumes:
  db-data:
  pgadmin-data:

我的应用程序存在三个问题:

1 - 如何将我的 my-database1.sqlmy-database2.sql 数据库导入 postgresql?我的代码中的解决方案(我的意思是 ./my-database1.sql:/docker-entrypoint-initdb.d/my-database1.sql)不起作用。 2 - 从上一步成功导入数据库后,如何在 pgadmin 中看到它们? 3 - 我的代码应该在 my-database1.sql 的表中写一些东西。导入postgresql后如何连接?

postgres 图像将仅尝试 运行 /docker-entrypoint-initdb.d 目录中提供的文件,同时 运行 在空文件夹上。根据您的 docker-compose.yml 配置,您拥有数据库数据的持久卷。这意味着 Postgres 不会在以后的部署中考虑对 SQL 文件的更新。当其中一个脚本失败时,会发生类似的事情。以下是 documentation 的摘录:

Warning: scripts in /docker-entrypoint-initdb.d are only run if you start the container with an empty data directory; any pre-existing database will be left untouched on container startup. One common problem is that if one of your /docker-entrypoint-initdb.d scripts fails (which will cause the entrypoint script to exit) and your orchestrator restarts the container with the already initialized data directory, it will not continue with your scripts.

查看站点文档,了解如何使初始化脚本更健壮,以便它们能够处理故障。

要解决您的问题,请尝试手动删除卷或在 运行 宁 docker-compose down 时使用 -v 标志,然后重新部署您的应用程序:

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