[英]flask service cannot communicate with postgres via docker-compose
[英]flask app service can't connect to postgres service within docker-compose
我正在尝试使用以下 docker-compose 运行 flask、postgres 和 nginx 服务:
version: '3.6'
services:
postgres:
image: postgres:10.5
container_name: postgres
hostname: postgres
user: postgres
ports:
- "5432:5432"
networks:
- db-tier
environment:
CUSTOM_CONFIG: /etc/postgres/postgresql.conf
volumes:
- ./postgres/sql/create_tables.sql:/docker-entrypoint-initdb.d/create_tables.sql
- ./postgres/postgresql.conf:/etc/postgres/postgresql.conf
command: postgres -c config_file=/etc/postgres/postgresql.conf
restart: always
app:
image: python/app:0.0.1
container_name: app
hostname: app
build:
context: .
dockerfile: Dockerfile
depends_on:
- postgres
networks:
- app-tier
- db-tier
stdin_open: true
nginx:
image: nginx:1.22
container_name: nginx-reverse-proxy-flask
ports:
- "8080:80"
depends_on:
- app
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
networks:
- app-tier
networks:
app-tier:
driver: bridge
db-tier:
driver: bridge
这就是app.config["SQLALCHEMY_DATABASE_URI"]
等于postgresql://denis:1234Five@postgres:5432/app
docker-compose 起来后的错误是:
app | psycopg2.OperationalError: could not connect to server: Connection refused
app | Is the server running on host "postgres" (192.168.32.2) and accepting
app | TCP/IP connections on port 5432?
什么会导致这种类型的错误? 我仔细检查了 postgres 服务的容器名称,它以这个名称postgres
运行,为什么 flask 应用程序没有“看到”它?
您的 postgres 容器和 docker-compose.yml 中没有适当的启动探针可能会出现问题查看参考如何在Docker 设置它们 - 检查 postgres 是否准备就绪
因此,在 postgres 作为容器启动后,docker 启动您的应用程序,但容器内的 postgres 尚未准备好,您会收到错误消息
此问题已通过 postgres pg_isready
向postgres
服务添加以下行得到解决:
healthcheck:
test: ["CMD-SHELL", "sh -c 'pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}'"]
interval: 10s
timeout: 3s
retries: 3
从这里作为解决方案Safe ways to specify postgres parameters for healthchecks in docker compose
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.