如何为postgres docker容器的初始化脚本指定当前的工作数据库? [英] How to specify the current working database for the initialization script of a postgres docker container?

查看:448
本文介绍了如何为postgres docker容器的初始化脚本指定当前的工作数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,可以使用类似于以下命令的docker命令复制要在创建容器时执行的init.sql文件: COPY init.sql / docker-entrypoint-initdb。 d /

It is known that one can copy an init.sql file to be executed on the creation of the container with a docker command similar to this one: COPY init.sql /docker-entrypoint-initdb.d/

让我们考虑使用一个非常简单的create table postgresql语句:

Let's consider that one uses a very simple create table postgresql statement:

CREATE TABLE films (
  code        char(5) CONSTRAINT firstkey PRIMARY KEY,
  title       varchar(40) NOT NULL,
  did         integer NOT NULL,
  date_prod   date,
  kind        varchar(10),
  len         interval hour to minute
);

问题是在此表的位置(在哪个数据库中)创建?

The question is where (in which database) is this table created?

但更重要的是如何设置当前工作数据库,以确切指定我们要在哪个数据库上工作?

不仅用于此语句,而且还用于所有后续语句!

But more importantly is how to set the current working database to specify exactly on which database we are working with??
Not only for this statement but also for all subsequent ones, and they are many!

推荐答案

这将详细说明数据库的初始化。 如何在Docker Postgres的脚本中创建用户/数据库

This explains in detail the initialization of the database. How to create User/Database in script for Docker Postgres.

简单地说,初始化期间创建的数据库的名称以及默认情况下创建表的位置由环境变量<$给出。 c $ c> POSTGRES_DB 。如果未设置变量,则使用默认值 postgres

To put it briefly, the name of the database created during the initialization and where your tables get created by default, is given by the environment variable POSTGRES_DB. If the variable is not set the default value postgres is used instead.

<$ c $中的脚本c> docker-entrypoint-initdb.d 文件夹使用以下命令一个一执行:

The scripts in the docker-entrypoint-initdb.d folder are executed one by one with the following command:

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" -f <your-file>

因此您已连接到 POSTGRES_DB 数据库(看看 docker-entrypoint.sh 脚本)。

therefore you are connected to the POSTGRES_DB database (have a look at the docker-entrypoint.sh script).

在脚本文件中,您仍然可以使用meta命令连接到其他数据库

In your script files you can nevertheless connect to a different database using the meta-command

\connect DBNAME

这篇关于如何为postgres docker容器的初始化脚本指定当前的工作数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆