Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

411
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda