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.
The
DATABASE_URLtells your application where the database is located and how to connect to it. Thebackendservice uses this URL to connect to thepostgres service.Whereas,
postgresservice 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
postgresservice you should have 3 environment variables:for backend service you should have set
DATABASE_URL