目前正在构建一个包以使用AWS测试一些devOps配置。使用Swift Vapor3,PostgreSQL 11,Docker构建应用程序。给定我的github Repo项目构建/测试/运行与vapor build
vapor test
vapor run
很好,因为你有一个本地安装的postgresql安装与username: test, password: test
但是我的api没有连接到我的数据库,我担心我的配置是错误的。
version: "3.5"
services:
api:
container_name: vapor_it_container
build:
context: .
dockerfile: web.Dockerfile
image: api:dev
networks:
- vapor-it
environment:
POSTGRES_PASSWORD: 'test'
POSTGRES_DB: 'test'
POSTGRES_USER: 'test'
POSTGRES_HOST: db
POSTGRES_PORT: 5432
ports:
- 8080:8080
volumes:
- .:/app
working_dir: /app
stdin_open: true
tty: true
entrypoint: bash
restart: always
depends_on:
- db
db:
container_name: postgres_container
image: postgres:11.2-alpine
restart: unless-stopped
networks:
- vapor-it
ports:
- 5432:5432
environment:
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_HOST: db
POSTGRES_PORT: 5432
PGDATA: /var/lib/postgresql/data
volumes:
- database_data:/var/lib/postgresql/data
pgadmin:
container_name: pgadmin_container
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: [email protected]
PGADMIN_DEFAULT_PASSWORD: admin
volumes:
- pgadmin:/root/.pgadmin
ports:
- "${PGADMIN_PORT:-5050}:80"
networks:
- vapor-it
restart: unless-stopped
networks:
vapor-it:
driver: bridge
volumes:
database_data:
pgadmin:
# driver: local
另外,在阅读Docker postgres文档时,我在“警告”部分中看到了这一点。
如果postgres在容器中启动时没有数据库,那么postgres将为您创建默认数据库。虽然这是postgres的预期行为,但这意味着在此期间它不会接受传入连接。当使用自动化工具(例如docker-compose)同时启动多个容器时,这可能会导致问题.postgres dockerhub
我没有进行这些更改,因为我不确定如何制作该文件或配置的外观。有没有人做过这样的事情,有一些连接到Postgresql和使用蒸汽作为后端的经验?
理论上讲,一个行为良好的容器应该能够优雅地处理其依赖关系不能运行,因为尽管容器调度程序尽了最大的努力,容器可能会来来去去。因此,如果您的应用需要数据库,但在任何特定时刻数据库都不可用,它应该合理地响应。例如,为HTTP请求返回503,或者在计划任务延迟后再次尝试。
这是理论,但并不总是适用。在你的情况下,也许你真的只需要你的Vapor应用程序等待Postgres可用,在这种情况下你可以使用一个包装器脚本轮询你的数据库,只在数据库准备好后启动你的主应用程序。
See this suggested wrapper script from the Docker docs:
#!/bin/sh
# wait-for-postgres.sh
set -e
host="$1"
shift
cmd="$@"
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec $cmd
command: ["./wait-for-postgres.sh", "db", "vapor-app", "run"]