如何创build一个docker-compose版本2来使用一个持久的postgres数据库?

我知道使用docker-compose的旧版本,我们可以创build另一个只有数据卷的容器,并使用volumes_from将其链接为“仅数据容器”。 不过,我想用新的语法来testing。

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 

这是基于这个职位 。

我有另一个脚本运行,等到这个postgres容器启动之前,其他容器运行,例如:

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

脚本看起来像:

 #!/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 

这是从docker网站。

这只会导致容器停滞不前,根本无法获得postgres容器来初始化我需要的表。

使用版本2不需要运行检查脚本,因为postgres一旦启动就会开始监听,并且可以使用depends_on来定义依赖关系。 下面是我如何设置postgres,一个卷和服务器(glassfish)运行在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: