# PostgreSQL via Docker Compose

* Create Docker Compose file in location that you want to start it in

```yaml
version: '3'

services:
  postgres:
    image: postgres:13.1
    healthcheck:
      test: [ "CMD", "pg_isready", "-q", "-d", "postgres", "-U", "root" ]
      timeout: 45s
      interval: 10s
      retries: 10
    restart: always
    environment:
      - POSTGRES_USER=<postgres_user>
      - POSTGRES_PASSWORD=<postgres_user_pass>
      - APP_DB_USER=<app_user>
      - APP_DB_PASS=<app_user_pass>
      - APP_DB_NAME=<app_database_name>
    volumes:
      - ./db:/docker-entrypoint-initdb.d/
    ports:
      - 5432:5432
```

* Create Database <mark style="color:orange;">`INIT`</mark> Script

```bash
# Create the folder in docker compose file location
mkdir <location_of_docker_compose_file>/db

# Create the script
touch <location_of_docker_compose_file>/db/01-init.sh
```

Should look like this:

```bash
drwxr-xr-x 2 user user 4096 Jul 16 14:22 db
-rw-r--r-- 1 user user  479 Jul 16 14:24 docker-compose.yml
drwxr-xr-x 5 user user 4096 Jul 16 14:33 ..
drwxr-xr-x 3 user user 4096 Jul 16 14:33 .
```

* Add the following script to is:

```bash
#!/bin/bash
set -e
export PGPASSWORD=$POSTGRES_PASSWORD;
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
  CREATE USER $APP_DB_USER WITH PASSWORD '$APP_DB_PASS';
  CREATE DATABASE $APP_DB_NAME;
  GRANT ALL PRIVILEGES ON DATABASE $APP_DB_NAME TO $APP_DB_USER;
  \connect $APP_DB_NAME $APP_DB_USER
  BEGIN;
    CREATE TABLE IF NOT EXISTS event (
	  id CHAR(26) NOT NULL CHECK (CHAR_LENGTH(id) = 26) PRIMARY KEY,
	  aggregate_id CHAR(26) NOT NULL CHECK (CHAR_LENGTH(aggregate_id) = 26),
	  event_data JSON NOT NULL,
	  version INT,
	  UNIQUE(aggregate_id, version)
	);
	CREATE INDEX idx_event_aggregate_id ON event (aggregate_id);
  COMMIT;
EOSQL
```

The script will:

* create a new user and password assigned in the variables in the composed file
* create the App database
* grant the priviilages for the user on the database
* connect to the database cand create a table called <mark style="color:orange;">`event`</mark>

Only thing left is to run the docker composed script:

```bash
docker-compose up -d
```

{% hint style="info" %}
Note:&#x20;

This should run the script automatically but if it doesn't run it with <mark style="color:orange;">`bash 01-init.sh`</mark>
{% endhint %}

* This should now be reachable via DBeaver or pgAdmin

![](https://3885248957-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoE4wMO1dMVDOGDjh0En7%2Fuploads%2FjRSa3AtrBZPHHCjl4bQm%2Fimage.png?alt=media\&token=39240ada-dacb-47dc-a847-75b61cd317d0)
