I have been trying to create a docker-compose file to get my web application up and running using only 'docker-compose up'. I can't make the containers reach each other, currently, I'm trying that the backend container connects to the postgres DB.
- I have added a health check for the postgres container
- I have been trying to add 'network_mode: host' to the postgres container but with no success.
- I am using Prisma as an ORM to connect to the DB.
This is my docker-compose.yml file:
version: "2.1"
services:
##############################
# Database Container
##############################
postgres:
restart: always
container_name: db
hostname: postgres
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- "5432:5432"
build:
dockerfile: ./database/Dockerfile
context: .
networks:
- mynet
healthcheck:
test: ["CMD-SHELL", "pg_isready -d postgres -U postgres"]
interval: 10s
timeout: 5s
retries: 5
# ##############################
# # Backend Container
# ##############################
backend:
restart: always
container_name: backend
hostname: backend
environment:
- DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres?schema=public
build:
dockerfile: ./Dockerfile
context: ./backend
depends_on:
postgres:
condition: service_healthy
networks:
- mynet
ports:
- "3001:3000"
# ##############################
# # Frontend Container
# ##############################
# frontend:
# restart: always
# container_name: frontend
# hostname: frontend
# build:
# dockerfile: ./Dockerfile
# context: ./frontend
# ports:
# - "3000:3000"
# depends_on:
# - "backend"
networks:
mynet:
driver: bridge
That's what I am getting ( Currently trying to communicate between the backend and Postgres containers. ):
I really appreciate any help you can provide.
CodePudding user response:
Just use the name of the database-service as hostname.
- DATABASE_URL=postgresql://postgres:postgres@postgres:5432/postgres?schema=public
edit
Docker containers are a little bit like a virtual machine. They have their own isolated network. When you write down the container ports (it is the ports
-part of your docker-compose), then is docker able to establish a routing between your containers.
Docker container "A" can talk to container "B" with only knowing the port and the name of the container.
When you want to talk from your host to container, then you have to publish the ports. You already did it with 3001:3001
.
That means for docker: All traffic on port 3001
on the host will be redirected to container on port 3001
. <portOnHost>:<portOnContainer>
I recommend to learn something about the networking. Here is documentation of docker.