Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

417
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda