2

I'm using Postgres and looking to create a database and then table after the container is created. Right now I using a dockerfile and init.sql file. The database gets created but the table gets created in the default postgres database. How do I get my new database to be the default one or at least get my table created in the correct database? Thank you

Dockerfile
FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

init.sql
CREATE DATABASE myApp;
CREATE TABLE session(sessionguid UUID NOT NULL, created text NOT NULL, sessionlife integer NOT NULL);
0

2 Answers 2

3

There's a set of variables that control things like the name of the user an the name of the database that is automatically created. Here is the relevant piece of documentation (see Environment Variables section):

POSTGRES_DB

This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used

Just specify it as environment variable in run command or in Dockerfile:

ENV POSTGRES_DB myApp
Sign up to request clarification or add additional context in comments.

Comments

0

As mentioned by @Roman Konoval you can use POSTGRES_DB env variable to create the database.

Here is the relevant piece of documentation (see Environment Variables section):

POSTGRES_DB

This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used

Then to create a table or do any sql imports (extend postgres image: https://docs.docker.com/samples/library/postgres/#how-to-extend-this-image).

Your dockerfile should look like this:

FROM library/postgres
COPY start.sh /docker-entrypoint-initdb.d/start.sh

start.sh:

#!/bin/sh
psql -h localhost -U user -W -d database_name -f /path/to/init.sql

when you run your container, you need to mount your sql script to /path/to/init.sql as follows:

$ docker run my_postgress_image -e "POSTGRES_DB=database_name" -v ./init.sql:/path/to/init.sql

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.