on
[ CSAPI] nodejs, mongodb 컨테이너 추가
[ CSAPI] nodejs, mongodb 컨테이너 추가
추가되는 NodeJS, MongoDB 컨테이너
사용자와 직접 상호작용(?)하는 NodeJS 서비스 컨테이너를 추가한다. 이 서비스는 주로 사용자의 회원가입, 로그인, 로그아웃 등의 작업을 처리하는데 사용자 정보를 저장할 DB도 필요하다. 여기서는 MongoDB를 사용하도록 한다.
- 예상 구성
Node 컨테이너 추가
사용자가 실제 서비스를 이용할 때는 Nginx를 통해 node에 접속하게 된다. 이때 proxy를 이용해 접속하도록 한다. 이를 위해 node 컨테이너는 3000번 port를 expose 하게 된다.
우선, 간단히 hello world를 출력하는 node의 코드를 추가하여 nginx proxy로 node 서비스가 가능한지 확인해본다.
1. node 디렉토리 생성 및 필요한 파일 작성
node 디렉토리를 새롭게 만들고, 아래의 파일들을 node 디렉토리 아래에 작성한다.
- node 디렉토리가 추가된 디렉토리 구조
. ├── docker-compose.yml ├── nginx │ ├── certificate.crt │ ├── default.conf │ ├── Dockerfile │ └── private.key ├── node │ ├── Dockerfile │ ├── index.js │ └── package.json └── README.md
- index.js
const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
- package.json
{ "name": "csapi-node", "version": "1.0.0", "description": "csapi user auto service", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Penguin135", "license": "ISC", "dependencies": { "express": "^4.17.1" } }
- Dockerfile
FROM node:14.17.0 WORKDIR /node COPY . . RUN npm install
2. nginx proxy 설정
node 컨테이너로 proxy를 하도록 nginx 설정을 한다. 현재는 node 서버가 하나밖에 없어서 Load Balancing 방식이 필요할까 싶지만 우선은 ip_hash 방식으로 해두었다. Round Robin, Random, Weighted 등 많은 방식이 있다.
- default.conf
upstream node { ip_hash; server node:3000; } server { listen 80; server_name test.csapi.kro.kr; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl on; ssl_certificate /etc/ssl/certificate.crt; ssl_certificate_key /etc/ssl/private.key; server_name test.csapi.kro.kr; location / { proxy_pass http://node/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
3. docker-compose.yml 에 node 서비스 추가
- docker-compose.yml
version: "3" services: nginx: build: ./nginx image: csapi-nginx:test ports: - "80:80" - "443:443" node: build: ./node image: csapi-node:test expose: - "3000" commnad: "node index.js"
4. code push
gitlab-runner 가 파이프라인을 수행했고, passed 가 됐다.
5. 도메인 접속 테스트
접속 시, node 컨테이너 서비스 사용이 가능하다.
from http://not-to-be-reset.tistory.com/510 by ccl(A) rewrite - 2021-09-22 15:00:43