Create table in PostgreSQL docker image

前端 未结 1 2005
暗喜
暗喜 2020-12-30 01:53

I am new to docker. I have extended PostgreSQL image and able to create new DB instance while running the image.I need to create tables in that DB from shell script that wil

相关标签:
1条回答
  • 2020-12-30 02:47

    In the docker-entrypoint.sh script of the official docker image of postgres is written:

    psql+=( --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" )
    
            echo
            for f in /docker-entrypoint-initdb.d/*; do
                case "$f" in
                    *.sh)     echo "$0: running $f"; . "$f" ;;
                    *.sql)    echo "$0: running $f"; "${psql[@]}" < "$f"; echo ;;
                    *.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${psql[@]}"; echo ;;
                    *)        echo "$0: ignoring $f" ;;
                esac
                echo
    done
    

    So every .sql file you want to execute inside your docker image can just be placed inside that folder. So my dockerfile looks like

    FROM postgres:9.3
    ENV POSTGRES_USER docker
    ENV POSTGRES_PASSWORD docker
    ENV POSTGRES_DB docker
    ADD CreateDB.sql /docker-entrypoint-initdb.d/
    

    And the content of my CreateDB.sql:

    CREATE TABLE web_origins (
        client_id character varying(36) NOT NULL,
        value character varying(255)
    );
    

    So I just start my container with:

    docker run -d my-postgres
    

    To check:

    docker exec -it 6250aee43d12 bash
    root@6250aee43d12:/# psql -h localhost -p 5432 -U docker -d docker
    psql (9.3.13)
    Type "help" for help.
    
    docker=# \c
    You are now connected to database "docker" as user "docker".
    docker=# \dt
               List of relations
     Schema |    Name     | Type  | Owner
    --------+-------------+-------+--------
     public | web_origins | table | docker
    (1 row)
    

    You can find the details for mysql here in this blog.

    0 讨论(0)
提交回复
热议问题