Run script after container entrypoint in docker-compose

Viewed 12319

I have a postgres:9.5.6-alpine container, and another container, named web, which has to be linked to it. I want to run a script named create_db.sh in postgres container after it has been started and docker-entrypoint.sh has been executed, in order to create a db and a user and restore a backup. My docker-compose.yml (postgres part):

  postgres:
    build: ./postgres
    container_name: postgres
    volumes:
      - /shared_folder/postgresql:/var/lib/postgresql
    ports:
      - "5432:5432"    
    command:  sh /home/create_db.sh

The content of create_db.sh is:

#!/bin/sh

psql -d template1 -U postgres
psql --command "CREATE USER user WITH PASSWORD 'userpassword';" 
psql --command "CREATE DATABASE userdb;"
psql --command "GRANT ALL PRIVILEGES ON DATABASE userdb to user;"
psql --command "\q;"  
psql -U user -d userdb -f /var/lib/postgresql/backup.sql

exit

When i run docker-compose build and then docker-compose up i get this:

Attaching to postgres, web
postgres    | psql: could not connect to server: No such file or directory
postgres    |   Is the server running locally and accepting
postgres    |   connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I've understood this is because when I launch create_db.sh postgres server is not ready, but so how can i run it after the docker-entrypoint.sh of the container?

2 Answers

If you are getting an error /bin/sh: bad interpreter: Permission denied change execution permission to your script file first, since Docker copies over permissions:

chmod +x your/script.sh
Related