如何在 docker-compose up 时创建 postgres 数据库并运行迁移

Ash*_*kan 14 postgresql docker dockerfile docker-compose

我正在设置一个简单的后端,它使用 postgres 数据库执行 CRUD 操作,并希望在 docker-compose up 运行时自动创建数据库和迁移。

我已经尝试将以下代码添加到Dockerfileentrypoint.sh但它们都不起作用。

createdb --host=localhost -p 5432 --username=postgres --no-password pg_development
createdb db:migrate
Run Code Online (Sandbox Code Playgroud)

如果在 docker 完全启动后单独运行,此代码将起作用

我已经尝试添加- ./db-init:/docker-entrypoint-initdb.d到卷中,但这也不起作用

这是Dockerfile

FROM node:10.12.0

# Create app directory
RUN mkdir -p /restify-pg
WORKDIR /restify-pg

EXPOSE 1337

ENTRYPOINT [ "./entrypoint.sh" ]
Run Code Online (Sandbox Code Playgroud)

这是我的 docker-compose.yml

version: '3'
services:
  db:
    image: "postgres:11.2"
    ports:
      - "5432:5432"
    volumes:
      - ./pgData:/var/lib/psotgresql/data
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD:
      POSTGRES_DB: pg_development

  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    volumes:
      - .:/restify-pg
    environment:
      DB_HOST: db
Run Code Online (Sandbox Code Playgroud)

entrypoint.sh(在这里我得到createdb: command not found

#!/bin/bash

cd app

createdb --host=localhost -p 5432 --username=postgres --no-password pg_development
sequelize db:migrate

npm install
npm run dev
Run Code Online (Sandbox Code Playgroud)

我希望当我运行 docker 时,会发生迁移和数据库创建。

Art*_*kov 8

entrypoint.sh(在这里我得到了 createdb: command not found)

createdb在 nodejs 容器中运行将不起作用,因为它是 postgres 特定命令,并且默认情况下未安装在 nodejs 映像中。

如果POSTGRES_DB: pg_development在 postgres 容器上指定env var,则在容器启动时自动创建数据库。因此,createdb无论如何都不需要在entrypoint.sh安装在 nodejs 容器中的情况下运行。

为了sequelize db:migrate工作,您需要:

  • 添加sequelize-cli到依赖项package.json
  • 运行npm install以便安装
  • npx sequelize db:migrate

这是一个提议:

# docker-compose.yml

version: '3'
services:
  db:
    image: "postgres:11.2"
    ports:
      - "5432:5432"
    volumes:
      - ./pgData:/var/lib/psotgresql/data
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD:
      POSTGRES_DB: pg_development

  app:
    working_dir: /restify-pg
    entrypoint: ["/bin/bash", "./entrypoint.sh"]
    image: node:10.12.0
    ports:
      - "3000:3000"
    volumes:
      - .:/restify-pg
    environment:
      DB_HOST: db

Run Code Online (Sandbox Code Playgroud)
# package.json

{
  ...
  "dependencies": {
    ...
    "pg": "^7.9.0",
    "pg-hstore": "^2.3.2",
    "sequelize": "^5.2.9",
    "sequelize-cli": "^5.4.0"
  }
}
Run Code Online (Sandbox Code Playgroud)
# entrypoint.sh

npm install
npx sequelize db:migrate
npm run dev
Run Code Online (Sandbox Code Playgroud)