我使用docker-compose构建了一个带有postgresql的flask应用程序。 但是flask无法连接postgresql。 错误信息:
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "postgres-db" (192.168.16.2) and accepting
TCP/IP connections on port 5432?
当我进入Docker容器并ping
postgres-db
时,它可以正常工作。而且当我启动Flask app时,它也可以正常工作。仅当我使用docker-compose up时才无法连接。我的docker-compose文件:
version: '3.7'
services:
postgres-db:
restart: always
image: postgres:11.1-alpine
privileged: true
ports:
- 5432:5432
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: Aa123456
PGDATA: /var/lib/postgresql/data/pgdata
volumes:
- ./db/postgres/data:/var/lib/postgresql/data/pgdata
api:
build:
context: ./api
dockerfile: Dockerfile
volumes:
- './api:/usr/src/app'
ports:
- 5002:5000
environment:
- FLASK_CONFIG=development
- FLASK_ENV=development
- APP_SETTINGS=project.config.DevelopmentConfig
- DATABASE_URL=postgres://postgres:Aa123456@postgres-db:5432/cms
- DATABASE_TEST_URL=postgres://postgres:Aa123456@postgres-db:5432/cms_test
- SECRET_KEY=ZQbn05PDeA7v11
depends_on:
- postgres-db
container_name: api
links:
- postgres-db:postgres-db
nginx:
build:
context: ./nginx
dockerfile: Dockerfile
restart: unless-stopped
ports:
- 8080:8080
depends_on:
- api
- client
client:
build:
context: ./client
dockerfile: Dockerfile
volumes:
- './client:/usr/src/app'
- '/usr/src/app/node_modules'
ports:
- 3008:3000
environment:
- NODE_ENV=development
- REACT_APP_SERVICE_URL=http://localhost:8080
- CHOKIDAR_USEPOLLING=true
depends_on:
- api
docker-compose up -d
,它是否有效?(经常出现的问题是应用程序在数据库完全初始化之前启动。)links:
不是必需的,可能会导致复杂性,并建议将其删除。 - David Maze