teang1995 / hello-nodejs

say hello to nodejs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

개발환경 구축

teang1995 opened this issue · comments

nodejs 개발 환경 구축을 하고자 함.
두 가지 방법으로 구축하고 싶은데

  1. 서버에서 개발하기
  2. 서버의 컨테이너에서 개발하기

두 가지 방법 모두에서 200, ok 를 받는 것까지 다뤄보겠음.

TODO's

  • 서버에서 nodejs 설치
  • nodejs 공식 홈페이지의 docker image 이용하여 컨테이너 띄우기
  • 두 방법 모두에서 사용할 간단한 REST 서버 만들기
  • 200, ok 받기 - 서버
  • 200, ok 받기 - 컨테이너

node.js official 에서 다운로드 파일을 받았음.
source file로 받으면 tar.gz 형식으로 다운 받을 수 있다.

npm 을 설치한다.
apt install npm

설치하려 했는데.. 서버에서는 권한이 막혀 있어서 설치가 안 되니 로컬에서 다운 받아 해보도록 하겠음

로컬에서는 공식 홈페이지의 exe파일로 설치하면 간단히 설치할 수 있다.

image
우선 윈도우에선 설치 완료

프로젝트 폴더에서 npm init
해서 값들을 채워주면 두번째 사진처럼 package.json 파일이 생김
image
image

npm install express --save 로 express 설치해주고나서
image

package.json을 다시 확인해보면 dependencies 라는 항목이 아래 사진과 같이 생김.

{
  "name": "hello-nodejs",
  "version": "1.0.0",
  "description": "nodejs test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": ";"
  },
  "keywords": [
    "node.js"
  ],
  "author": "yongtaek.lim",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.3"
  }
}

reference
https://waspro.tistory.com/615

express 서버 실행
express demo

cd demo

npm install

npm start

결과
image

reference
https://kitty-geno.tistory.com/62

두 개의 라우트를 추가함.

/* GET api demo*/
router.get('/api/demo', function(req, res) {
  res.status(200).json({
    'message': 'call get api demo'
  });
});

/* POST api demo */
router.post('/api/demo', function(req, res) {
  res.status(200).json({
    'message': 'call post api demo'
  });
});

postman 테스트 결과

1. /api/demo GET
image

2. /api/demo POST
image

reference
https://kitty-geno.tistory.com/63

Dockerfile 제작 및 docker image 빌드 완료.
image

docker container를 실행하고, exec을 이용하여 접속하는 것까지 구현 완료.
image

하지만 LF 때문에 dependencies 빌드에 필요한 파일들이 없다.
package.json 에 보니 dependencies가 잘 정리되어 있어 이를 이용해 설치하는 방법을 찾아보던 중
https://c17an.netlify.app/blog/node.js/npm-install-%EC%A0%95%EB%A6%AC/article/
를 보니 npm installpackage.json가 있는 폴더에서 실행해주면 dependencies가 알아서 설치된다고 함.

cd code

npm install

npm start

를 이용해 서버를 실행시키고 postman으로 확인.
반응이 잘 오는 것을 볼 수 있음.
image

이로서 서버에서 컨테이너를 이용해 nodejs 서버를 띄우는 것도 구현하였다.