devops

(간단)docker를 사용한 dev용 mongoDB 서버 실행하기

하리하링웹 2024. 11. 4. 18:36

docker-compose 파일 생성

# docker-compose.yaml
version: '3.8'
services:
  mongodb:
    image: mongo:latest
    container_name: mongodb
    restart: always
    ports:
      - '27017:27017'
    volumes:
      - ./data/db:/data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

package.json에 실행 명령어 등록, 테스트

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "db": "docker-compose up -d",
    "db:down": "docker-compose down"
  },

 

정상 동작 테스트

**PS D:\\programming\\delivery-mate> yarn db**     
yarn run v1.22.22
$ docker-compose up -d
time="2024-11-04T11:14:08+09:00" level=warning msg="D:\\\\programming\\\\delivery-mate\\\\docker-compose.yaml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
[+] Running 3/3
 ✔ Network delivery-mate_default            Created                                                             0.1s 
 ✔ Container delivery-mate-mongodb-1        Started                                                             0.7s 
 ✔ Container delivery-mate-myapplication-1  Started                                                             0.9s 
Done in 1.54s.
**PS D:\\programming\\delivery-mate> yarn db:down**
yarn run v1.22.22
$ docker-compose down
time="2024-11-04T11:14:11+09:00" level=warning msg="D:\\\\programming\\\\delivery-mate\\\\docker-compose.yaml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
[+] Running 3/3
 ✔ Container delivery-mate-myapplication-1  Removed                                                             3.3s 
 ✔ Container delivery-mate-mongodb-1        Removed                                                            10.4s 
 ✔ Network delivery-mate_default            Removed                                                             0.2s 
Done in 14.29s.
PS D:\\programming\\delivery-mate> 

DB Util 생성

global types

// global.d.ts
/* eslint-disable no-var */

import { MongoClient } from 'mongodb';

declare global {
  var _mongoClientPromise: Promise<MongoClient> | undefined;
}

 

connect.ts

// connect.ts
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI || 'mongodb://root:example@localhost:27017';
const options = {};

let client;
let clientPromise: Promise<MongoClient>;

if (process.env.NODE_ENV === 'development') {
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  if (!process.env.MONGODB_URI) {
    throw new Error('Please add your Mongo URI to .env.local');
  }

  client = new MongoClient(uri, options);
  clientPromise = client.connect();
}

export default clientPromise;

 

collection.ts

// collection.ts
import { clientPromise, ITest } from '@/lib/mongo';

async function getMongo() {
  return clientPromise;
}

export const collection = {
  test: async () => (await getMongo()).db().collection<ITest>('test'),
};

 

schema-type.ts

// schema-type.ts
export interface ITest {
  name: string;
  age: number;
}

테스트 API 생성

// localhost:3000/api/db-status

import { collection } from '@/lib/mongo';
import { NextResponse } from 'next/server';

export async function GET(req: Request) {
  const testCollection = await collection.test();

  const result = await testCollection.find().toArray();

  return NextResponse.json(result);
}

export async function POST(req: Request) {
  const testCollection = await collection.test();
  const requestBody = await req.json();

  const result = await testCollection.insertOne(requestBody);

  return NextResponse.json(result);
}

테스트

POST Command

curl -X POST -H "Content-Type: application/json" -d "{\\"name\\":\\"홍길동\\",\\"age\\":25}" <http://localhost:3000/api/db-status>

 

POST

**>curl -X POST -H "Content-Type: application/json" -d "{\\"name\\":\\"홍길동\\",\\"age\\":25}" <http://localhost:3000/api/db-status**>
{"acknowledged":true,"insertedId":"67284e28ae49bd7480209c03"}

 

GET