0

I can't figure out what address to use when running my API service in the same container as my Postgres image. I keep getting the following error.

thread 'main' panicked at 'Error connecting to db: Io(Os { code: 99, kind: AddrNotAvailable, message: "Cannot assign requested address" })'

My current sqlx connection is the following.

    let postgress_pool: Pool<sqlx::Postgres> = PgPoolOptions::new()
        .max_connections(2)
        .connect("postgresql://postgres:123@database:5432/users").await
        .expect("Error connecting to db");

docker-compose.yml


  database:
    container_name: postgres-database
    image: postgres
    expose:
      - 5432
    ports:
      - 5432:5432
    restart: always
    environment:
      POSTGRES_PASSWORD: 123
      POSTGRES_DB: users
    volumes:
      - ./init_users.sql:/docker-entrypoint-initdb.d/init.sql

  auth:

    container_name: auth-service
    build: ./Authentication/
    ports:
      - 8080:8080

I've tried changing the address to the following addresses

  • 0.0.0.0
  • localhost
  • 172.17.0.1
  • 172.18.0.1
  • 172.18.0.3
  • postgres-database
  • database

Sidenote: I am relatively new and saw some sources say things like establishing a network in the docker-compose file but others say this isn't necessary.

cafce25
  • 15,907
  • 4
  • 25
  • 31
Dumb Nerd
  • 15
  • 6
  • Is it possible your application container is starting before the database container exists? That could cause this error; setting it to `depends_on: [database]` might help get around this specific error (you would still need to wait for the database to be up and running though). – David Maze Aug 31 '23 at 10:52

1 Answers1

0

Turns out you need to establish a network in the docker compose file. My docker file ended up looking like this.

services:

  database:
    container_name: postgres-database
    image: postgres
    expose:
      - 5432
    ports:
      - 5432:5432
    restart: always
    environment:
      POSTGRES_PASSWORD: 123
      POSTGRES_DB: users
    volumes:
      - ./init_users.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - rust-local-network

  auth:

    container_name: auth-service
    build: ./Authentication/
    ports:
      - 8080:8080
    networks:
      - rust-local-network

networks:
  rust-local-network:
    driver: bridge

and my connection string looks like...

    let postgress_pool: Pool<sqlx::Postgres> = PgPoolOptions::new()
        .max_connections(2)
        .connect("postgresql://postgres:123@database:5432/users").await
        .expect("Error connecting to db");
Dumb Nerd
  • 15
  • 6
  • Compose provides a network named `default` for you, and so long as you have no `networks:` at all in the file this shouldn't be necessary. Also see [Networking in Compose](https://docs.docker.com/compose/networking/) in the Docker documentation. – David Maze Aug 31 '23 at 10:51