creating pg_cron extension within docker-entrypoint-initdb.d fails

蓝咒 提交于 2020-06-28 01:54:43

问题


If I create the pg_cron extension in a docker-entrypoint-initdb.d/init.sql file, the docker image fails to run and docker logs <id> just says "No such container." Here's the relevant .sql snippet:

CREATE DATABASE my_database;
\c my_database;
CREATE EXTENSION IF NOT EXISTS postgis CASCADE;
CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;
CREATE EXTENSION IF NOT EXISTS pg_cron CASCADE;

However, if I create the pg_cron extension after the docker run command completes (i.e. remove the last line above and run it separately with psql --file after docker run completes), the extension gets created successfully (postgis and timescaledb extensions seem to be fine regardless).

Is there a reason I can't create the pg_cron extension from docker-entrypoint-init.d? Is there a correct place?

My docker run command is as follows:

 docker run -d \
        --name my_container --rm \
        -p 5432:5432 \
        -clog_line_prefix="%m [%p]: [%l-1] %u@%d" \
        -clog_error_verbosity=VERBOSE \
        -cshared_preload_libraries='timescaledb,pg_cron' \
        -ccron.database_name='my_database'

回答1:


pg_cron can be loaded only as shared library. You must specify it in postgres.conf file. Since all scripts in docker-entrypoint-init.d are executed after postgres server is started (with pg_ctl start), all changes to shared_preload_libraries in postgres.conf can become available after restart (with pg_ctl restart).

Real world example:

002-setup.sh:

#!/bin/sh

# Remove last line "shared_preload_libraries='citus'"
sed -i '$ d' ${PGDATA}/postgresql.conf

cat <<EOT >> ${PGDATA}/postgresql.conf
shared_preload_libraries='pg_cron,citus'
cron.database_name='${POSTGRES_DB:-postgres}'
EOT

# Required to load pg_cron
pg_ctl restart

003-main.sql:

CREATE EXTENSION pg_cron;

Notice:

  1. script execution order matters and is ordered by file names
  2. pg_cron becomes available in db specified with cron.database_name


来源:https://stackoverflow.com/questions/48069718/creating-pg-cron-extension-within-docker-entrypoint-initdb-d-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!