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);
CodePudding user response:
You can use for example script or execute shell command using sed/awk to replace your variable ${SOME_ARGUMENT_HERE}
with some other variable that has been passed to the Dockerfile
Example of command
sed -i 's/${SOME_ARGUMENT_HERE}/TEST-REPLACE/g' init.sql
Example of shell script (replace.sh)
#!/usr/bin/env bash
sed -i 's/${SOME_ARGUMENT_HERE}/TEST-REPLACE/g' init.sql
CodePudding user response:
Ok so far I've created this
docker-compose.yml
build:
context: .
args:
- PG_TABLE=${PG_TABLE} # Comes from .env variable
dumps.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/\${PG_TABLE}/$PG_TABLE/g" dump.sql
Dockerfile
FROM postgres
# Run script to replace variable - ${PG_TABLE} with the arg supplied via docker-compose
COPY script.sh script.sh
RUN chmod x script.sh
RUN ./script.sh $PG_TABLE
ADD dump.sql /docker-entrypoint-initdb.d/
The only problem here is that the script to replace the variable runs before the actual dump.sql has been copied. How do I resolve the above?