Cannot connect to postgres container from rust container

95 Views Asked by At

I am using sqlx's query!() macro which needs a connection to the database to check if the queries are correct at compile time. As you can see in this answer I added network: host to the build of my rust service

However, I cannot connect to the database once the container is up and running. Then I get Io(Os { code: 111, kind: ConnectionRefused, message: "Connection refused" }). I don't understand why because the connection is working during compile time.

Here is my docker-compose.yml:

version: "3.9"
services:
  postgres:
    image: postgres:16.1
    restart: on-failure
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data
    env_file:
      - .pg.env

  backend:
    build:
      context: backend
      dockerfile: Dockerfile
      network: host
    env_file:
      - backend/.env
    ports:
      - "8080:8080"
    depends_on:
      - postgres

volumes:
  postgres-data:

In the .env file from the backend there is just the DATABASE_URL variable.

1

There are 1 best solutions below

4
Yilmaz On

The DATABASE_URL tells your application where the database is located and how to connect to it. The backend service uses this URL to connect to the postgres service.

Whereas, postgres service serves as the PostgreSQL DATABASE SERVER for your application. This is where your application's data will be stored and managed. It's a separate, standalone service that your application (backend service) will connect to for all its data needs, like storing, retrieving, updating, and deleting data.

so for postgres service you should have 3 environment variables:

environment:
  - POSTGRES_USER=postgres
  - POSTGRES_PASSWORD=postgres
  - POSTGRES_DB=name_of_db

for backend service you should have set DATABASE_URL

backend:
    environment:
      - DATABASE_URL=postgres://postgres:postgres@postgres/name_of_db