简体   繁体   English

flask 服务无法通过 docker-compose 与 postgres 通信

[英]flask service cannot communicate with postgres via docker-compose

getting an error which says it cannot make connections with my postgres database收到一个错误,提示它无法与我的 postgres 数据库建立连接

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 "clean_life_database_1" (172.19.0.2) and accepting
    TCP/IP connections on port 4444?

here is my docker-compose.yml这是我的 docker-compose.yml

version: "3.8"

services:
    web:
        build: .
        environment:
            - POSTGRES_URI=postgresql://postgresuser123:mysecret@clean_life_database_1:4444
        ports:
            - 5000:5000
        networks:
            - db_new

    database:
        image: postgres
        environment:
            - POSTGRES_USER=postgresuser123
            - POSTGRES_PASSWORD=mysecret
        ports:
            - 4444:5432
        volumes:
            - ./postgres-data:/var/lib/postgresql/data
        networks:
            - db_new

networks:
    db_new:
        driver: bridge

also, the folder in which the project resides is clean_life, so when i checked the container names, it gives me clean_life_database_1另外,项目所在的文件夹是 clean_life,所以当我检查容器名称时,它给了我 clean_life_database_1

why does it prefex with my folder name and the suffix it with a 1?为什么它以我的文件夹名称为前缀,后缀为 1?

Taking a look at the docs on.networking in compose, it looks like you should instead set your database host to database (as it's the name of your database container).查看 compose 中的 on.networking文档,您似乎应该将数据库主机设置为database (因为它是数据库容器的名称)。

You're also setting up a.network db_new which could also be used for the web and database services to talk to each other but I'll leave that up to you.您还设置了 a.network db_new ,它也可用于webdatabase服务以相互通信,但我会把它留给您。

So as an updated compose file you should have:因此,作为更新的撰写文件,您应该拥有:

version: "3.8"

services:
    web:
        build: .
        environment:
            - POSTGRES_URI=postgresql://postgresuser123:mysecret@database:4444
        ports:
            - 5000:5000
        networks:
            - db_new

    database:
        image: postgres
        environment:
            - POSTGRES_USER=postgresuser123
            - POSTGRES_PASSWORD=mysecret
        ports:
            - 4444:5432
        volumes:
            - ./postgres-data:/var/lib/postgresql/data
        networks:
            - db_new

networks:
    db_new:
        driver: bridge

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM