How to run an init script for Docker Postgres

The official Docker postgres image will run all *.sh and *.sql scripts in its /docker-entrypoint-initdb.d directory automatically when it starts.

Table of contents:

Technologies used:

  • Docker 24.0.5
  • Official Docker postgres image (latest)

1. Create an init.sql

5.1 Creates an init.sql (can be any filename ending with the extension .sql) to create a table and insert three rows.

init.sql

CREATE TABLE students (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  age INTEGER
);

INSERT INTO students (name, age) VALUES
  ('Mkyong', 40),
  ('Ali', 28),
  ('Teoh', 18);

2. Copy init.sql to container

The below command maps the local /path/to/init.sql file to the container’s /docker-entrypoint-initdb.d/init.sql.

Terminal

  -v /path/to/init.sql:/docker-entrypoint-initdb.d/init.sql

3. Start the Postgres container

The below command starts a Postgres container and runs the init.sql initialization script.

Terminal

docker run --name pg-container-name -p 5432:5432 -e POSTGRES_USER=mkyong -e POSTGRES_PASSWORD=password -e POSTGRES_DB=mydb -v /path/to/init.sql:/docker-entrypoint-initdb.d/init.sql -d postgres

Note
More about the about command – Running PostgreSQL as a container

4. Access the Postgres container

Access the running container and display the data inserted by init.sql.

Terminal

docker exec -it pg-container-name psql -U mkyong -d mydb

psql (15.4 (Debian 15.4-1.pgdg120+1))
Type "help" for help.

mydb=# select * from students;
 id |  name  | age
----+--------+-----
  1 | Mkyong |  40
  2 | Ali    |  28
  3 | Teoh   |  18
(3 rows)

mydb=#

Exit the terminal.

Terminal

  \q

P.S. If the PostgreSQL container fails to start, we can use docker logs container-name to check the errors.

5. References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments