title: How to execute docker-entrypoint-initdb.d/init.sql files AFTER database is created?
body: <p>I have a Django app with Docker</p>
  <p>I want to initialize my database based on init.sql file when running docker-compose up</p>
  <p>2 containers are correctly built and init.sql file is available in db_container</p>
  <p>but <code>docker logs db_container</code> show an error indicating that database has not been migrated yet:</p>
  <blockquote>
  <p>ERROR: relation table1 does not exist</p>
  </blockquote>
  <p>Database is created when entrypoint.sh files is executed (command python manage.py migrate)</p>
  <p>I do not understand when init.db is executed?</p>
  <p><strong>Dockerfile</strong></p>
  <pre><code>FROM python:3.8.3-alpine
  
  WORKDIR /usr/src/app
  
  ENV PYTHONDONTWRITEBYTECODE 1
  ENV PYTHONUNBUFFERED 1
  
  RUN apk update &amp;&amp; apk add postgresql-dev gcc python3-dev musl-dev
  RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl
  RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev
  RUN pip3 install psycopg2 psycopg2-binary
  
  COPY requirements/ requirements/
  RUN pip install --upgrade pip &amp;&amp; pip install -r requirements/dev.txt
  
  COPY ./entrypoint.sh .
  COPY . .
  
  # Run entrypoint.sh
  ENTRYPOINT [ &quot;/usr/src/app/entrypoint.sh&quot; ]
  
  </code></pre>
  <p><strong>entrypoint.sh</strong></p>
  <pre><code>#!/bin/sh
  
  if [ &quot;$DATABASE&quot; = &quot;postgres&quot; ]
  then
      echo &quot;Waiting for postgres...&quot;
      # nc = netcap -z = scanning
      while ! nc -z $SQL_HOST $SQL_PORT; do
        sleep 0.1
      done
  
      echo &quot;PostgreSQL started&quot;
  fi
  
  python manage.py flush --no-input
  python manage.py migrate
  
  exec &quot;$@&quot;
  </code></pre>
  <p><strong>docker-compose.yml</strong></p>
  <pre><code>version: '3.7'
  
  services:
      web:
          ...
          depends_on: 
              - db
      db:
          image: postgres:12.0-alpine
          restart: always
          volumes:
              - postgres_data:/var/lib/postgres/data/
              - ./imports/init.sql:/docker-entrypoint-initdb.d/init.sql
          environment:
              - POSTGRES_USER=user
              - POSTGRES_PASSWORD=user
              - POSTGRES_DB=db_dev
  volumes:
      postgres_data:
  </code></pre>
  <p>init.sql</p>
  <pre><code>\c db_dev
  
  INSERT INTO table1 (field1,field2,field3) VALUES ('value1','value2','value3');
  ...
  </code></pre>