如何在docker中运行postgres的sql脚本

Jwq*_*wqq 5 postgresql node.js docker docker-compose

我正在关注这篇文章来运行sql脚本来创建默认表.

这是我的docker撰写文件

version: "3"
services:
  web:
    build: .
    volumes:
      - ./:/usr/src/app/
      - /usr/src/app/node_modules
    ports:
      - “3000:3000”
    depends_on:
      - postgres
  postgres:
    container_name: postgres
    build:
      context: .
      dockerfile: pgDockerfile
    environment:
      POSTGRES_PASSWORD: test
      POSTGRES_USER: test
    ports:
      - 5432:5432
Run Code Online (Sandbox Code Playgroud)

这是我的pgDockerfile

FROM postgres:9.6-alpine

# copy init sql
ADD 00-initial.sql /docker-entrypoint-initdb.d/
Run Code Online (Sandbox Code Playgroud)

这是我的sql脚本

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE IF NOT EXISTS test (
    id text NOT NULL,
    title varchar(200) NOT NULL
);
Run Code Online (Sandbox Code Playgroud)

我可以构建和运行docker-compose up,我看到以下消息:

postgres    | CREATE DATABASE
postgres    | 
postgres    | CREATE ROLE
postgres    | 
postgres    | 
postgres    | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/00-initial-data.sql
postgres    | CREATE EXTENSION
postgres    | CREATE TABLE
postgres    | 
postgres    | 
postgres    | LOG:  received fast shutdown request
postgres    | LOG:  aborting any active transactions
postgres    | waiting for server to shut down....LOG:  autovacuum launcher shutting down
postgres    | LOG:  shutting down
postgres    | LOG:  database system is shut down
postgres    |  done
postgres    | server stopped
postgres    | 
postgres    | PostgreSQL init process complete; ready for start up.
postgres    | 
postgres    | LOG:  database system was shut down at 2017-03-22 21:36:16 UTC
postgres    | LOG:  MultiXact member wraparound protections are now enabled
postgres    | LOG:  database system is ready to accept connections
postgres    | LOG:  autovacuum launcher started
Run Code Online (Sandbox Code Playgroud)

在创建表之后,似乎关闭了db.我认为这是postgres docker的标准流程,但是当我登录postgres时,我看不到我的桌子应该在那里.

我登录了

docker exec -it $(my postgres container id) sh

#su - postgres

#psql

# \d => No relations found. 
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是为postgres创建默认数据的正确方法.任何人都可以帮我吗?非常感谢!

Nor*_*ing 0

我认为你的泊坞窗按预期工作,但它并没有完全按照你的想法工作。当设置POSTGRES_USER,而不设置POSTGRES_DB时,系统会默认使用用户名作为数据库名,所以你的表在数据库中test

使用\l列出您的数据库将显示数据库,然后您可以使用\c test连接到数据库。连接后,\d将列出您的关系!