Joseph Song
Joseph Song

Reputation: 204

How do I create a docker-compose version 2 to have a persistent postgres db using volumes?

I understand that using the older version of docker-compose, we can create another container with just a data volume and link it using volumes_from to make it a "data-only container." However, I wanted to test out using the new syntax.

version: '2'
services:
    app:
        build: .
        links:
            - psql
    psql:
        image: postgres
        volumes_from:
            - psqldata
        ports:
            - "5432:5432"
    psqldata:
        image: postgres
        volumes:
            - psqlvolumes:/var/lib/postgresql/data/

volumes:
    psqlvolumes:
        driver: local

This was based off of this post.

I have another script running to wait until this postgres container is up before the other containers run for example:

container:
    build: .
    volumes:
        - ./scripts/wait-for-postgres.sh:/code/wait-for-postgres.sh
    entrypoint: ./wait-for-postgres.sh "command"

with the script looking like:

#!/bin/bash

set -e
export PGPASSWORD=postgres
cmd="$@"

until psql -h "postgres" -U "postgres" -c '\l'; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done

>&2 echo "Postgres is up - executing command"
exec $cmd

This was taken from the docker website.

This only leads to the containers stalling and not coming up at all and I cannot even get the postgres container to initialize with the tables I need.

Upvotes: 7

Views: 6368

Answers (1)

waterscar
waterscar

Reputation: 876

With version 2 is not needed to run the check script, because postgres will start listening once it's started, and you can use depends_on to define the dependency. Here's how I setup a postgres, a volume and a server (glassfish) running on postgres:

version: '2'

services:
  my-app:
    image: my-glassfish-image
    depends_on:
      - my-db

  my-db:
    image: my-postgres-image
    volumes:
      - postgres-db-volume:/data/postgres

volumes:
  postgres-db-volume:

Upvotes: 7

Related Questions