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

标签 postgresql docker docker-compose dockerfile

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

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

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

如果在 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" ]

这是我的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

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

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

最佳答案

entrypoint.sh (in here I get createdb: command not found)

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

如果在 postgres 容器上指定 POSTGRES_DB: pg_development env var,数据库将为 created automatically when the container starts .因此,无论如何都不需要在安装在 nodejs 容器中的 entrypoint.sh 中运行 createdb

为了使 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/postgresql/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

# package.json

{
  ...
  "dependencies": {
    ...
    "pg": "^7.9.0",
    "pg-hstore": "^2.3.2",
    "sequelize": "^5.2.9",
    "sequelize-cli": "^5.4.0"
  }
}
# entrypoint.sh

npm install
npx sequelize db:migrate
npm run dev

关于postgresql - 如何在 docker-compose up 时创建 postgres 数据库并运行迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483781/

相关文章:

Docker、docker-compose 和在项目之间复制文件

linux - 如何在前台运行 docker-compose start ?

Docker 检查文件是否存在于 healthcheck 中

regex - Postgres 正则表达式字符串匹配

SQL 查询 : Iterate over values in table and use them in subquery

postgresql - 在我的情况下,bcrypt && bcryptjs 比较密码总是返回 false

MySQL 镜像忽略 docker-compose.yml 的卷配置

sql - 找到每个键的最新合格行

maven - Dockerfile-ARG SHA和Curl

docker - 如何在 Docker 中处理持久存储(例如数据库)