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:
- 1. Create an init.sql
- 2. Copy init.sql to container
- 3. Start the Postgres container
- 4. Access the Postgres container
- 5. References
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.
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
.
-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.
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
.
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.
\q
P.S. If the PostgreSQL container fails to start, we can use docker logs container-name
to check the errors.