如何在容器内创建postgres扩展?

Sar*_*rit 8 postgresql docker

我必须安装hstore到我的docker postgres
这是我在shell中的普通命令来执行我的需要

psql -d template1 -c 'create extension hstore';
Run Code Online (Sandbox Code Playgroud)

如果我删除该行我的容器,它可以工作,但我自己执行hstore安装,我必须告诉我的项目中的每个人都这样做,这不是一个好的做法

这是我的 yml file

  postgres:
    build:
      context: .
      dockerfile: dockerfiles/devdb.dockerfile
    environment:
      POSTGRES_USER: uih
      POSTGRES_PASSWORD: uIhbod!
      POSTGRES_DB: uih_portal
    ports:
        - "5433:5432"
Run Code Online (Sandbox Code Playgroud)

这是我的docker文件 devdb.dockerfile

FROM postgres:9.5

RUN mkdir -p /var/lib/postgresql-static/data
ENV PGDATA /var/lib/postgresql-static/data

# psql -d template1 -c 'create extension hstore;'
CMD ["psql", "-d", "template1", "-c", "'create extension hstore;'"]

RUN echo "hstore extension installed"
Run Code Online (Sandbox Code Playgroud)

构建后我无法运行它

$ docker-compose up postgres
Recreating uihportal_postgres_1
Attaching to uihportal_postgres_1
postgres_1       | psql: could not connect to server: No such file or directory
postgres_1       |      Is the server running locally and accepting
postgres_1       |      connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
uihportal_postgres_1 exited with code 2
Run Code Online (Sandbox Code Playgroud)

题:

如何hstore从dockerfile 安装?
我想制作一个图像并将其重新用于我的团队的整个项目

Elt*_*man 17

它失败了,因为Postgres在构建期间没有在容器中运行,它只在CMD容器运行时才开始.

Docker镜像入口点脚本支持运行安装步骤 - /docker-entrypoint-initdb.d当容器启动时,将执行目录中的任何.sql或.sh文件.

因此,您可以通过将扩展设置放在SQL脚本中,并将脚本复制到init目录中的映像来完成此操作:

> cat hstore.sql
create extension hstore
> cat Dockerfile
FROM postgres:9.5
COPY hstore.sql /docker-entrypoint-initdb.d
Run Code Online (Sandbox Code Playgroud)

构建该映像时,SQL脚本将在正确的位置执行,因此每当容器从映像运行时,它将安装扩展.

  • 如果您通过 compose 中的环境变量预先指定数据库,那么这实际上不起作用。docker-entrypoint-initdb.d 文件在“CREATE DATABASE”之后运行,因此它仅安装在模板(我假设)数据库上,而不是您想要的数据库上。尚未弄清楚如何在 sql 文件中实际指定数据库名称的情况下解决此问题。编辑:虽然我刚刚重新审查了 Docker 映像并将 --dbname 传递给 psql,所以我不确定。 (3认同)