[Docker] nginx + nodejs + mongodb 배포하기

이상협·2022년 9월 29일
0

Docker

목록 보기
4/6

Docker를 사용한 서버 배포

도커를 이용해서 nginx와 nodejs 그리고 mongodb를 한번에 배포해보려고 한다.

먼저 파일구조는

.
├── docker-compose.yml      // 여러 이미지를 한번에 배포시켜주는 파일
├── nginx
│   ├── Dockerfile          // conf 폴더 안의 파일을 복붙해주기 위한 도커파일
│   └── conf
│       └── default.conf    // 배포할 서버를 연결하기 위한 파일
└── server                
    ├── Dockerfile          // 필요한 모듈 설치 및 프로젝트 빌드용 파일
    ├── node_modules
    ├── package-lock.json
    ├── package.json
    ├── .dockerignore       // 도커 이미지에 넣지 않을 파일 목록
    └── src

다음과 같다.

먼저 server(nodejs) 폴더부터 도커파일을 만들어준다.

🎈 nodejs 빌드

  • mongodb와 연동하기 위해 mongoose로 connect 시 mongo url을 mongodb://[유저 ID]:[유저 PW]@mongo:27017/[사용할 DB이름] 로 해준다.

    • mongodb와 nodejs 연동하는 법
    • 아이디와 비밀번호를 넣는 이유는 mongodb를 도커 컨테이너로 열게 되면 nodejs에서 접속 시 필수로 로그인을 해야되는 것으로 알고 있다.
      (안넣으니까 에러만 뜬다...)
  • 자신이 만든 nodejs 프로젝트에 들어가서 Dockerfile을 하나 만들어준다.

// server/Dockerfile
FROM node:[사용할 버전]

WORKDIR /usr/src/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE [사용할 포트]
CMD ["npm", "start"] // 이미지 배포시 구동할 command
  • 그리고 .dockerignore 파일을 만들어서 작성해준다.
// server/.dockerignore
node_modules
  • docker-compose.yml 에 서버 관련 내용들을 작성해준다.
// docker-compose.yml
services:
  [서버 프로젝트 이름]:
    build: ./server
    container_name: [서버 프로젝트 이름]
    restart: always
    depends_on:
      - mongodb       // mongodb가 완료되면 실행
    ports:
      - 8080:4500     // 8080포트로 들어오면 4500으로 읽는다
    networks:
      - backend

🎈 mongodb 빌드

  • docker-compose.yml 에 작성
// docker-compose.yml
...
  mongodb:
    image: mongo:latest
    container_name: mongo
    restart: always
    ports:
      - "27017:27017"
    volumes:
      # - ./mongo/init.js:/docker-entrypoint-initdb.d/init.js:ro
      - type: bind                     // db의 경로를 local로 바꿔주는 내용
        source: /var/lib/mongodb       // local 경로
        target: /data/db               // docker image 내 경로
    networks:
      - backend

🎈 nginx 빌드

  • 처음에 보여줬던 파일 구조처럼 nginx 폴더를 하나 만들어준다.
  • conf.d 폴더를 하나 더 만들어서 경로 안에 default.conf 파일 작성해준다.
// nginx/conf.d/default.conf
upstream [서버 이름] {
    server host.docker.internal:8080; // 도커 컨테이너로 되어있어 ip를 직접 끌어와야 함
}

server {
    listen 80;
    location / {
        proxy_pass http://[서버 이름];
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
        proxy_set_header X-Forwarded-Host $server_name; 
        # root /usr/share/nginx/html;
        # index index.html index.html; 
    }
}
  • nginx 폴더에 Dockerfile 하나 만들어준다.
// nginx/Dockerfile
FROM nginx

RUN rm /etc/nginx/conf.d/default.conf

COPY ./conf.d/default.conf /etc/nginx/conf.d/default.conf
// 만들어둔 default.conf를 넣어주는 작업
  • docker-compose.yml 에 작성해준다.
// docker-compose.yml
...
nginx:
    build: ./[nginx 폴더]
    container_name: nginx
    restart: always
    depends_on:
      - [서버 프로젝트 이름]
    ports:
      - 8000:80
    extra_hosts:
      - "host.docker.internal:host-gateway" // ip 정보를 컨테이너 안으로 보내주기 위함
    networks:
      - backend

🎈 배포하기

  • docker-compose.yml 의 최종 모습은 다음과 같다.
// docker-compose.yml
version: "3"
services:
  nginx:
    build: ./[서버 프로젝트 이름]
    container_name: nginx
    restart: always
    depends_on:
      - [서버 프로젝트 이름]
    ports:
      - 8000:80
    extra_hosts:
      - "host.docker.internal:host-gateway"
    networks:
      - backend

  [서버 프로젝트 이름]:
    build: ./[서버 폴더 이름]
    container_name: [서버 프로젝트 이름]
    restart: always
    depends_on:
      - mongodb
    ports:
      - 8080:4500
    networks:
      - backend

  mongodb:
    image: mongo:latest
    container_name: mongo
    restart: always
    ports:
      - "27017:27017"
    volumes:
      # - ./mongo/init.js:/docker-entrypoint-initdb.d/init.js:ro
      - type: bind
        source: /var/lib/mongodb # local 경로
        target: /data/db
    networks:
      - backend

networks:
  backend:
    driver: bridge
  • docker-compose.yml 파일이 있는 경로로 들어간 후 다음 명령을 쳐준다.
$ docker-compose up -d
  • 빌드가 하나씩 되고 난 후 다음과 같이 뜬다.
Creating mongo ... done
Creating server-todolist ... done
Creating nginx           ... done

🎈 서버에서 만든 api 주소 들어가보기

  • 미리 만들어둔 api를 통해 한번 접속을 해보자.

    mongodb에 넣어둔 데이터들이 정상적으로 잘 나오는 것을 알 수 있다.

참고

0개의 댓글