Using Docker Compose makes it even easier to manage and deploy the PostgreSQL container with the seeded database. This compose.yml file defines a Postgres service named `db` using the latest Postgres image, which sets up a database with the name `sampledb`, along with a user `postgres` and a password `mysecretpassword`.
```yaml
services:
db:
build:
context: .
dockerfile: Dockerfile
container_name: my_postgres_db
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: mysecretpassword
POSTGRES_DB: sampledb
ports:
- "5432:5432"
volumes:
- data_sql:/var/lib/postgresql/data # Persistent data storage
volumes:
data_sql:
```
It maps port `5432` on the host to the container's `5432`, let you access to the Postgres database from outside the container. It also define `data_sql` for persisting the database data, ensuring that data is not lost when the container is stopped.
It is important to note that the port mapping to the host is only necessary if you want to connect to the database from non-containerized programs. If you containerize the service that connects to the DB, you should connect to the database over a custom bridge network.
4. Bring up the Compose service.
Assuming that you've placed the `seed.sql` file in the same directory as the Dockerfile, execute the following command:
```console
$ docker compose up -d --build
```
5. It’s time to verify if the table `users` get populated with the data.
```console
$ docker exec -it my_postgres_db psql -h localhost -U postgres sampledb
```
```sql
sampledb=# SELECT * FROM users;
id | name | email
----+-------+-------------------
1 | Alpha | alpha@example.com
2 | Beta | beta@example.com
3 | Gamma | gamma@example.com
(3 rows)
sampledb=#
```
## Pre-seed the database using JavaScript code
Now that you have learned how to seed the database using various methods like SQL script, mounting volumes etc., it's time to try to achieve it using JavaScript code.
1. Create a .env file with the following:
```plaintext
POSTGRES_USER=postgres
POSTGRES_DB_HOST=localhost
POSTGRES_DB=sampledb
POSTGRES_PASSWORD=mysecretpassword
POSTGRES_PORT=5432
```
2. Create a new JavaScript file called seed.js with the following content:
The following JavaScript code imports the `dotenv` package which is used to load environment variables from an `.env` file. The `.config()` method reads the `.env` file and sets the environment variables as properties of the `process.env` object. This let you to securely store sensitive information like database credentials outside of your code.