스토리지

[06.14] AWS EC2를 이용해서 웹서버 배포하기 - 01 본문

개발일지

[06.14] AWS EC2를 이용해서 웹서버 배포하기 - 01

ljw4104 2021. 6. 14. 12:49

1. 웹서버 코드 작성

MongoDB에 접근해서 해당 Collection을 통째로 받아와서 반환해주는 간단한 웹서버입니다.

현재는 테스트이기에 3000번 포트에 접근하지만 실제 배포할 때는 80번 포트를 사용할 예정입니다.

 

app.js

const express = require("express");
const app = express();
const port = 3000;

const usersRouter = require("./routes/index");
app.use("/", usersRouter);

app.listen(port, () => {
  console.log("서버 실행중");
});

 

index.js (router)

const express = require("express");
const router = express.Router();
const MongoClient = require("mongodb").MongoClient;

const url =
  "mongodb+srv://<MongoDB에서 받아올 수 있습니다>";
const dbName = "<DB이름>";

router.get("/chapter", (req, res, next) => {
  res.send("Hello");
  //테스트
});

router.get("/:name", (req, res, next) => {
  const chapterNum = req.params.name;
  const client = new MongoClient(url);
  client.connect(function (err) {
    if (err) throw err;
    console.log("Connected successfully to server");
    const db = client.db(dbName);

    findDocuments(db, "Chapter" + chapterNum, (docs) => {
      client.close();
      console.log("Good bye");
      res.send(docs);
    });
  });
});

const findDocuments = function (db, chapterName, callback) {
  // Get the documents collection
  const collection = db.collection(chapterName);
  // Find some documents
  collection.find({}, { fields: { _id: 0 } }).toArray(function (err, docs) {
    callback(docs);
  });
};

module.exports = router;

 

이제 이 서버를 AWS 서버에 올려야된다.

현재 제 인스턴스는 중지시켰지만 갓 만든 인스턴스의 상태는 실행중이라고 표시가 됩니다.

 

2. Git을 통해 프로젝트를 Github에 올리기

먼저 Git 설치 및 Github 계정이 필요합니다. 계정이 만들어졌고 설치가 되었다고 가정하겠습니다.

 

1. 해당 폴더에서 마우스 오른쪽버튼을 누른 뒤 Git Bash Here을 누릅니다.

처음 Git을 설치했다면 유저 설정을 해줘야된다.

C:\Users\<UserName> 디렉토리에 .gitconfig파일이나 Bash를 통해서 유저 설정을 할 수 있다.

 

$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com

이와같이 유저설정을 해준다.

 

이제 GitHub에 코드를 올려야된다.

1. git add .

-모든 파일을 로드한다, 초기에만 모든 파일을 로딩하고 나중에는 변경된 파일만 로드한다.

 

2. git commit -m "<커밋할 메세지>"

커밋할 메세지를 적지않으면 에러가 난다.

 

3. git remote add origin https://아이디:비밀번호@github.com/아이디/프로젝트이름 

- Git에 GitHub주소를 등록하는 과정이다. 최초 1회만 하면 된다.

 

4. git push origin master

- Github에 업로드한다.

 

여기까지 진행후에 Github에 제대로 들어왔으면 성공이다.

Comments