Connect to a postrges batabase running on a docker with python

I have a postgreysql running on a docker.
I can conncet to it with the command :

sudo docker exec -it immich_postgres psql --dbname=immich --username=“username”

and it works fine.
But I would like to connect with python.

In python there is a lib pg8000 to do that.
I have configure the 5432 port in docker to be exposed as 5431 outside docker
I try the folowing command :

import pg8000
connection = pg8000.connect(host=“localhost”,database=“immich”,user=“username”,password=“XXXXXX”,port=5431)

but I get a “pg8000.exceptions.InterfaceError: network error”
I am “new” with docker…
Is it a postgres erro? a docker error or python error?

Thanks

Please share how you created the database container, as in the exact ´docker run` command, or if docker compose was used the content of the compose file.

To be clear: “outside docker” means the python app is running as a native process on the docker host itself, right?

When I say “outside docker” I mean to run the python script directly on the ubuntu that run the docker

To creat the docker (Immich app) I run the folowing command :

sudo docker compose up -d

with the docker-compose.yml file (and I think I made an error in the yml file…) :

name: immich

services:
  immich-server:
    container_name: immich_server
    image: xxxxxx
    volumes:
      - ${UPLOAD_LOCATION}:/usr/src/app/upload
      - /var/www/nextcloud/data/xxx/
    env_file:
      - .env
    ports:
      - '2283:2283'
      - '5431:5432'
    depends_on:
      - redis
      - database
    restart: always
    healthcheck:
      disable: false
  immich-machine-learning:
    container_name: immich_machine_learning
    image: xxxxx
    volumes:
      - model-cache:/cache
    env_file:
      - .env
    restart: always
    healthcheck:
      disable: false

  redis:
    container_name: immich_redis
    image: xxxxxxxx
    healthcheck:
      test: redis-cli ping || exit 1
    restart: always

  database:
    container_name: immich_postgres
    image: xxxxxx
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_DB: ${DB_DATABASE_NAME}
      POSTGRES_INITDB_ARGS: '--data-checksums'
    volumes:
      - ${DB_DATA_LOCATION}:/var/lib/postgresql/data
    restart: always

volumes:
  model-cache:

I put the port forward in the immich app part in stead of putting it in the database part…
With it in the database part i can connect to tthe database

Thanks your question made me found the error