From 34d0b9bfb3082d2faf67812d11996bfdfd800e57 Mon Sep 17 00:00:00 2001 From: KingCSharp Date: Thu, 28 Mar 2019 18:39:33 +0800 Subject: [PATCH] Fix docker-compose start up order Add db.env --> store shared database environment variables Add wait-for-postgres.sh --> let crm container run django server after database being ready to connect --- Dockerfile | 10 ++++++---- db.env | 6 ++++++ docker-compose.yml | 11 ++++------- entrypoint.sh | 1 + wait-for-postgres.sh | 18 ++++++++++++++++++ 5 files changed, 35 insertions(+), 11 deletions(-) create mode 100644 db.env create mode 100644 wait-for-postgres.sh diff --git a/Dockerfile b/Dockerfile index dd9f59c..aa45555 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,11 +7,13 @@ COPY . /app/ RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - && \ apt update && \ - apt install -y git ruby-dev nodejs && \ + apt install -y git ruby-dev nodejs postgresql-client && \ + apt clean && \ gem install compass sass && \ npm -g install less && \ - pip install -r requirements.txt && \ - pip install redis coveralls + pip install --no-cache-dir -r requirements.txt && \ + pip install --no-cache-dir redis -RUN chmod +x /app/entrypoint.sh +RUN chmod +x /app/entrypoint.sh \ + /app/wait-for-postgres.sh ENTRYPOINT ["/app/entrypoint.sh"] \ No newline at end of file diff --git a/db.env b/db.env new file mode 100644 index 0000000..0d6e0c2 --- /dev/null +++ b/db.env @@ -0,0 +1,6 @@ +# Database environment variables +POSTGRES_USER=postgres +POSTGRES_PASSWORD=root +POSTGRES_DB=dj_crm +DB_HOST=db +DB_PORT=5432 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 4bfbfeb..cc51de7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,17 +5,14 @@ services: image: postgres # volumes: # - /home/db:/var/lib/postgresql/data - environment: - POSTGRES_PASSWORD: "root" - POSTGRES_USER: "postgres" - POSTGRES_DB: "dj_crm" + env_file: + - ./db.env web: build: . image: micropyramid/django-crm:1 - environment: - DB_HOST: db - DB_PORT: 5432 + env_file: + - ./db.env ports: - "8001:8000" depends_on: diff --git a/entrypoint.sh b/entrypoint.sh index 6170403..b4d7261 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,6 +1,7 @@ #!/bin/bash # Execute startup scripts +./wait-for-postgres.sh $DB_HOST python manage.py collectstatic --noinput python manage.py migrate python manage.py runserver 0.0.0.0:8000 \ No newline at end of file diff --git a/wait-for-postgres.sh b/wait-for-postgres.sh new file mode 100644 index 0000000..8d0dae9 --- /dev/null +++ b/wait-for-postgres.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# wait-for-postgres.sh + +set -e + +host="$1" +shift +cmd="$@" + +echo "Testing Postgres connection with psql ..." +until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do + #~ >&2 echo "Postgres is unavailable - sleeping" + >&2 echo -n . + sleep 1 +done + +>&2 echo "Postgres is up - executing command" +exec $cmd