docker-compose.yml, postgress, how to setup db, tables and prepop in an init.sql file?

人盡茶涼 提交于 2021-02-11 14:25:39

问题


I would like to add a DB, table and prepopulate with some kind of init.sql file. not sure what the init.sql file looks like. Also not sure where I would be putting the ADD command.

This docker-compose.yml file works

version: '3.6'
services:
  postgre:
    image: postgres:11.1-alpine
    ports:
      - "5432"
    environment:
      POSTGRES_USER: 'user'
      POSTGRES_PASSWORD: 'password'
      POSTGRESS_DB: 'db_amex01'
    volumes:
      - ./init:/docker-entrypoint-initdb.d/

回答1:


You can add *.sh script(s) and/or *.sql instructions to the /docker-entrypoint-initdb.d/ directory (basically how you have in your docker-compose.yml file already).

An example of a shell script to create a user:

#!/bin/bash
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

You can generate your .sql file from an existing database by "dumping" the data with psql -U <username> -d <dbname> -1 -f <filename>.sql. You can then add the .sql file to your ./init/ directory.

This is documented at https://github.com/docker-library/docs/tree/master/postgres#how-to-extend-this-image.



来源:https://stackoverflow.com/questions/53729813/docker-compose-yml-postgress-how-to-setup-db-tables-and-prepop-in-an-init-sql

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