Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

410
Views
create postgres database if it does not exist on docker-compose start up

I have the following docker-compose file:

version: '3.5'

services:
  postgres:
    container_name: postgres_container
    image: postgres
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-postgres}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
      PGDATA: /data/postgres
    volumes:
       - postgres:/data/postgres
    onrun:
      psql -h=localhost -P=${POSTGRES_PASSWORD} -U=${POSTGRES_USER} -tc "SELECT 1 FROM pg_database WHERE datname = 'premiership'" | grep -q 1 || psql -h=localhost -P=${POSTGRES_PASSWORD}-U=${POSTGRES_USER}c "CREATE DATABASE premiership"
    ports:
      - "5432:5432"
    networks:
      - postgres
    restart: unless-stopped

The above does not work because there is no onrun in docker-compose services.

All I want to do is create a database if it does not exist but this is insanely difficult because I don't know when the service is up.

Also it is not easy to do this in postgres. I tried mapping a volume so that an initdb.sql is ran:

volumes:
   - postgres:/data/postgres
   - ./initdb/1_schema.sql:/docker-entrypoint-initdb.d/1_schema.sql

1_schema.sql looks like this:

SELECT datname
FROM pg_database
WHERE datname='premiership'';
    IF datname='
premiership' 
        THEN CREATE DATABASE premiership PASSWORD 'test';
    END IF;

THe database is not created and when I run docker-compose logs I don't see anything about running the script.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Have you tried setting POSTGRES_DB variable in your docker-compose.yml environment ?

 image: postgres
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-postgres}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
      POSTGRES_DB: premiership
      PGDATA: /data/postgres
    volumes:

see https://hub.docker.com/_/postgres :

POSTGRES_DB

This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!