Docker postgreSQL entrypoint-initdb.d choose database

Viewed 1338

I have a docker-compose.yml file

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=root
      - POSTGRES_PASSWORD=password
      - APP_DB_USER=docker
      - APP_DB_PASS=docker
      - APP_DB_NAME=docker
    volumes:
      - ./db:/docker-entrypoint-initdb.d/
    ports:
      - 5432:5432

in the same directory there is a directory db with 1 file init.sql:

CREATE TABLE accounts (
    user_id serial PRIMARY KEY,
    username VARCHAR ( 50 ) UNIQUE NOT NULL,
    password VARCHAR ( 50 ) NOT NULL,
    email VARCHAR ( 255 ) UNIQUE NOT NULL,
    created_on TIMESTAMP NOT NULL,
        last_login TIMESTAMP 
);

insert into accounts(username,password,email,created_on) values ('a','aaa','assdfdas',now())

when I run docker-compose up (if the db is empty) the init.sql file is executed but the database in which it is executed is root and not postgres, How can I change it?

Imgur link to DataGrip screenshot

1 Answers

You can use the psql command \connect <db-name> inside your init.sql file in order to connect to the correct database (given that the database already exists).

In your case, the init.sql file would look something like:

\connect postgres   <-- connects to the 'postgres' database

CREATE TABLE accounts (
    user_id serial PRIMARY KEY,
    username VARCHAR ( 50 ) UNIQUE NOT NULL,
    password VARCHAR ( 50 ) NOT NULL,
    email VARCHAR ( 255 ) UNIQUE NOT NULL,
    created_on TIMESTAMP NOT NULL,
        last_login TIMESTAMP 
);
...
Related