简体   繁体   中英

flask service cannot communicate with postgres via docker-compose

getting an error which says it cannot make connections with my postgres database

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

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

why does it prefex with my folder name and the suffix it with a 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).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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