Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run SQL Scripts after DB Initialized from Docker-Compose?

I have the Docker Compose file below. I'm trying to run the following:

  • Set up Postgres
  • Run Entity Framework to set up my schemas/tables
  • Set up PG Admin
  • Run some SQL scripts on the database.

The I can get the first three items done no problem, but I'm not sure where to put the running of my SQL scripts. Right now it's on the last line of the YAML, but I'm sure this is wrong. Where would I put this? I'm not sure how to reference the database I'd set up earlier to run the SQL on.

version: '3.8'
services:
  #SET UP POSTGRES
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_USER: marmalade
      POSTGRES_PASSWORD: marmalade
      POSTGRES_DB: marmalade
    
    ports:
      - "15432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U marmalade"]
      interval: 5s
      timeout: 5s
      retries: 5
  #RUN ENTITY FRAMEWORK TO INITIALIZE DATABASE
  db-migrator:
    image: ${DOCKER_REGISTRY-}db-migrator
    build:
      context: ../../../
      dockerfile: src/marmalade/Dockerfile
    environment:
      - DOTNET_ENVIRONMENT=IntegrationTest
    depends_on:
      db:
        condition: service_healthy
        
  #SET UP PGADMIN
  pgadmin:
    container_name: pgadmin4_container
    image: dpage/pgadmin4
    restart: always
    environment:
      PGADMIN_DEFAULT_EMAIL: [email protected]
      PGADMIN_DEFAULT_PASSWORD: marmalade
   
    ports:
      - "5050:80"
    volumes:
       - ./servers.json:/pgadmin4/servers.json # preconfigured servers/connections
       - ./sql/admin_schema.sql:/docker-entrypoint-initdb.d/admin_schema.sql  #<-  WHERE DO I PUT THIS?
       
like image 493
kickinchicken Avatar asked Feb 03 '26 22:02

kickinchicken


1 Answers

Its correct but it needs to be in your Db service

Example:

services:
    my_db:
      image: postgres:latest    
      volumes:
          - ./init.sql:/docker-entrypoint-initdb.d/init.sql
  

UPDATE:

problem with running in any other service is that its not going to have the credentials to connect to the database. So you can just create a shell script and run it the old fashioned way like so:

services:
    some_service:
        image: your_image    
        volume: ./init.sh:/init.sh
        entrypoint: sh -c "/init.sh"

assuming of course that you have the shell already installed in your image

like image 65
Kaus2b Avatar answered Feb 06 '26 10:02

Kaus2b