Home > Software design >  How to fix the docker setup issue
How to fix the docker setup issue

Time:11-16

I'm developing a site with MERN stack and I want to do all the things with Docker. But I have trouble with connecting to MongoDB with Docker.

Here's my docker-compose.yml file.

version: "3.7"

services:
  backend:
    build:
      context: ./node_backend
      dockerfile: Dockerfile.dev
    container_name: "${APP_NAME}-backend"
    restart: always
    env_file: .env
    volumes:
      - type: bind
        source: ./node_backend/src
        target: /usr/src/app/src
    expose: 
      - "${API_PORT}"
    ports: 
      - "${API_PORT}:${API_PORT}"
    command: npm run dev
    environment: 
      - PORT=${API_PORT}
      - DB_URL=mongodb://mongo:27017/${DB_NAME}

  db:
    image: mongo
    restart: always
    env_file: .env
    container_name: "${APP_NAME}-database"
    ports:
      - '27017:27017'
    environment: 
      - MONGO_INITDB_ROOT_USERNAME=${DB_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${DB_PASSWORD}
  
  frontend:
    build:
      context: ./react_frontend
      dockerfile: Dockerfile.dev
    container_name: "${APP_NAME}-frontend"
    env_file: .env
    expose:
      - "${CLIENT_PORT}"
    ports:
      - "${CLIENT_PORT}:${CLIENT_PORT}"
    volumes:
      - type: bind
        source: ./react_frontend/src
        target: /usr/src/app/src
      - type: bind
        source: ./react_frontend/public
        target: /usr/src/app/public
    command: npm start

I get this kind of warnings if I execute docker compose upcommand. enter image description here

Is there anyone helps me to fix it?

CodePudding user response:

you database service name is db so your DB_URL should be like

      - DB_URL=mongo://db:27017/${DB_NAME}

CodePudding user response:

You can add depends_on to set the order in which services must start and stop. And the host of DB_URL must be the same as the mongo service (in this case it is db)

  backend:
    build:
      context: ./node_backend
      dockerfile: Dockerfile.dev
    container_name: "${APP_NAME}-backend"
    restart: always
    env_file: .env
    volumes:
      - type: bind
        source: ./node_backend/src
        target: /usr/src/app/src
    expose: 
      - "${API_PORT}"
    ports: 
      - "${API_PORT}:${API_PORT}"
    command: npm run dev
    environment: 
      - PORT=${API_PORT}
                         //db is the name of the service
      - DB_URL=mongodb://db:27017/${DB_NAME}
    depends_on:
      - db
    

  db:
    image: mongo
    restart: always
    env_file: .env
    container_name: "${APP_NAME}-database"
    ports:
      - '27017:27017'
    environment: 
      - MONGO_INITDB_ROOT_USERNAME=${DB_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${DB_PASSWORD}
  • Related