ARYA
ARYA

Reputation: 243

Not able to execute the sql file script from docker compose

I am trying to execute the sql files from docker compose.

My compose file is:

    - ../folder:/docker-entrypoint-initdb.d/folder1/
    - ../folder2:/docker-entrypoint-initdb.d/folder2/

The sql files are in folder named folder.

Docker file is:

COPY init.sh /docker-entrypoint-initdb.d/init.sh

init.sh file:

"${psql[@]}" -f folder1/*.sql
"${psql[@]}" -f folder2/*.sql

I am getting :

postgres_1 | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1 postgres_1 | postgres_1 | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh postgres_1 | /docker-entrypoint-initdb.d/init.sh: line : -f: command not found

Upvotes: 1

Views: 1559

Answers (2)

David Maze
David Maze

Reputation: 159613

The code you have in the init.sh isn't standard Bourne shell syntax. I believe that expansion will look for an environment variable named psql[@], and when no environment variable with that name exists (including the punctuation as part of the variable name), you will get an empty string (hence the -f option being interpreted as the command).

If you put your SQL initialization files directly in the container's /docker-entrypoint-initdb.d directory, the container startup will run them for you. It's reasonable to inject these using a bind mount; you do not need a derived image.

version: '3'
services:
  db:
    # Stock PostgreSQL image, not something locally built
    image: postgres:12
    volumes:
      - pgdata:/var/lib/postgresql/data
      # Bind-mount init scripts directly into init directory
      - ./folder:/docker-entrypoint-initdb.d
volumes:
  pgdata:

If you do want to store these files in the image, COPY the SQL scripts (and not the Bourne shell wrapper) into the init directory

COPY folder/*.sql /docker-entrypoint-initdb.d

You need to do one or the other, but not both.

Upvotes: 0

paltaa
paltaa

Reputation: 3254

According to mysql image documentation on docker hub:

When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

Also, the logs show your .sh file is getting executed and got errors. Looking into the code it seems you are trying to execute an init script which execute other *.sql files which is redundant.

If an order of execution is desirable, stick to naming them to comply with an alphabetical order execution.

Upvotes: 0

Related Questions