Test Container PostGres
The steps for creating a “seeded” test container for PostGres
This is based on: https://nickjanetakis.com/blog/docker-tip-79-saving-a-postgres-database-in-a-docker-image
For testing purposes, you may want one or more “staged” containers with your data in various configurations. For example, you might want an empty container with just your database and schema created, and another with some sample data.
Your tests can start with a clean-slate version of these things and dispose of them when you are done.
Step 1 - Create a “base” Dockerfile
FROM postgres:16.2-bullseye
COPY data.sql /docker-entrypoint-initdb.d/data.sql
ENV POSTGRES_PASSWORD=passwordENV POSTGRES_USER=userENV PGDATA=/dataIn the data.sql file put any SQL scripts you want Postgres to run on first run.
Step 2 - Build the Image
docker build -t app-data:raw .Step 3 - Start and Run the Container
docker run -d -p 5432:5432 app-data:rawStep 4 - Attach a shell and delete the init data.
In the container:
rm /docker-entrypoint-initdb.d/data.sqlStep 5 - Commit The Image
Exit the shell in the container, find the name given to your running instance, and do the following:
docker commit amazing_jones app-data:schema