Search code examples
docker

How to pass variable to init.sql file from docker-entrypoint-initdb.d


See below code:

I want to pass a variable from Dockerfile or wherever to my init.sql file. How can I do this?

Dockerfile

FROM postgres
ADD init.sql /docker-entrypoint-initdb.d/

init.sql

CREATE TABLE ${SOME_ARGUMENT_HERE}(
id SERIAL PRIMARY KEY,
name VARCHAR(500) NOT NULL,
completed BOOLEAN NOT NULL);

Solution

  • Ok so far I've created this

    docker-compose.yml

    build:
      context: .
      args:
       - PG_TABLE=${PG_TABLE}      # Comes from .env variable
    

    seed.sql

    CREATE TABLE ${PG_TABLE}(
    id SERIAL PRIMARY KEY,
    name VARCHAR(500) NOT NULL,
    completed BOOLEAN NOT NULL);
    

    script.sh

    #!/usr/bin/env bash
    sed  -i "s/\${$1}/$2/g" dump.sql
    

    Dockerfile

    FROM postgres
    ARG PG_TABLE
    
    ADD seed.sql /docker-entrypoint-initdb.d/seed.sql
    
    # pass variable PG_TABLE to script.sh to replace ${PG_TABLE} with .env variable in seed.sql
    WORKDIR /scripts
    COPY script.sh .
    RUN chmod +x script.sh
    RUN /scripts/script.sh PG_TABLE "${PG_TABLE}"
    

    Finally fixed. I realised the problem was because my script.sh was not targeting the destination of /docker-entrypoint-initdb.d/seed.sql