node.js/nodemon systemd 서비스 등록하기

mosad2334·2022년 1월 3일
0

사내에서는 node.js/nodemon을 항상 도커환경에서 쓰고 있던 상황이었다. 그러던 어느날 도커를 세팅하지 않고 로컬 서버 환경에서 고대로 세팅해야 될 일이 생기게 되었는데..

아래 파일 내용 중 '...'은 생략을 의미한다.

도커 환경에서 사용했던 node.js의 docker-compose 구성

...

  node_service_name:
    image: node:12
    container_name: node_container_name
    depends_on:
      - node_depends_service_names1
      - node_depends_service_names2
    working_dir: /home/node/app
    volumes:
      - /my/local/paths:/home/node/app
    environment:
      - NODE_ENV=production
    expose:
      - "80"
    command: ["npm", "start"]
    restart: on-failure
    
...

package.json 파일

{
  "name": "node_project_name",
  ...
  "scripts": {
    "start": "nodemon -L ./your/path",
  },
  ...
  "dependencies": {
    "nodemon": "^2.0.7",
    ...
  },
  ...
}

-L 옵션은 도커로 구성된 환경에서 노드몬이 원하는 대로 재시작을 하지 않아서 붙였던 옵션으로 기억한다. 아래 참고.

nodemon --help option 커맨드 내용


Configuration
  --config <file> .......... alternate nodemon.json config file to use
  --exitcrash .............. exit on crash, allows nodemon to work with other watchers
  -i, --ignore ............. ignore specific files or directories
  --no-colors .............. disable color output
  --signal <signal> ........ use specified kill signal instead of default (ex. SIGTERM)
  -w, --watch path ......... watch directory "dir" or files. use once for each
                             directory or file to watch
  --no-update-notifier ..... opt-out of update version check

Execution
  -C, --on-change-only ..... execute script on change only, not startup
  --cwd <dir> .............. change into <dir> before running the script
  -e, --ext ................ extensions to look for, ie. "js,pug,hbs"
  -I, --no-stdin ........... nodemon passes stdin directly to child process
  --spawn .................. force nodemon to use spawn (over fork) [node only]
  -x, --exec app ........... execute script with "app", ie. -x "python -v"
  -- <your args> ........... to tell nodemon stop slurping arguments

Watching
  -d, --delay n ............ debounce restart for "n" seconds
  -L, --legacy-watch ....... use polling to watch for changes (typically needed
                             when watching over a network/Docker)
  -P, --polling-interval ... combined with -L, milliseconds to poll for (default 100)

Information
  --dump ................... print full debug configuration
  -h, --help ............... default help
  --help <topic> ........... help on a specific feature. Try "--help topics"
  -q, --quiet .............. minimise nodemon messages to start/stop only
  -v, --version ............ current nodemon version
  -V, --verbose ............ show detail on what is causing restarts


> Note that any unrecognised arguments are passed to the executing command.

대강 이런식으로 package.json 파일에 nodemon을 잘 실행하도록 세팅하고 docker-compose 파일에 컨테이너 구동 시 npm start를 실행하면 도커 컨테이너는 잘 돌아가줬던 상황이었다.

도커가 없는 환경에서도 그냥 package.json 세팅만 잘 된 상태로 그냥 npm start를 실행시키면 잘 되겠거니 판단해서 커맨드를 갈겼는데, 아 맞아. 이거 백그라운드로 실행되는게 당연한게 아니었지...
터미널이 종료되면 당연히 같이 서버가 꺼져 버리는 상황이었다.

당시 검색을 해서 node.js를 백그라운드로 실행시키는 데에 도움을 줄 수 있는 여러 도구들이 있기는 했는데(대표적으로 pm2), 당시 스택오버플로우에서 systemd를 활용하면 더이상 필요하지 않다는 내용이 있었다.
👉stack overflow:How do I run a node.js app as a background service?

이 내용이 필요하게 된 서론은 여기까지. 아래는 본론.
centOS7 기준으로 작성했다.

1. service 파일 작성

(root 권한 필요) # vi /etc/systemd/mynode.service

/etc/systemd/mynode.service

[Unit]
Description=Please Do Not exIt My NOdeMon!!!!!!!!!!!

[Service]
Type=simple
ExecStart=/usr/bin/npm start

Restart=on-failure
User=nobody
Group=nobody
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/my/local/paths
TimeoutStartSec=0
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

참고로 위의 스택오버플로우 링크의 예시파일과는 많이 다르다.
(아마도) npm 실행파일의 위치같은 것이 기본적인 환경구성이 다른지 잘 먹히지 않아서 로그에 찍힌 단서같은 것으로 열심히 검색해서 찾아냈던 기억이 있다. 그때 그때 왜 이런 설정을 넣었는지 메모해 둘걸..

2. 데몬 리로드 및 서비스 활성화/시작

# systemctl daemon-reload
# systemctl enable mynode.service
# systemctl start mynode.service

3. 서비스 확인

# journalctl -u mynode.service

잘 돌아가는지 확인이 됐으면, 세팅 완료 이후 3번의 커맨드에서 follow(-f) 옵션 넣고 실행한뒤

# journalctl -f -u mynode.service

코드에 콘솔 마구마구 찍으면 확인이 바로바로 나타나서 행복사하면서 코드 짜기 시작했던 기억이 난다.

보통 journalctl 커맨드를 치기 시작할 때는 어디서부터 되지않는 경우인지 몰라 헤메는 보통은 매우 불행한 상태일 때가 많은데, 처음으로 journalctl이 나에게 행복감을 줬을 때라 더 인상깊었던 것 같기도 하다....

여튼 node.js 말고도 다른 상황의 서버 프로그램일 경우 매우 유용해보였다. 킵해두기.

profile
Web Developer / Read "KEEP CALM CARRY ON" Poster

0개의 댓글