반응형

WEB이란 네트워크 체계 위에서 동작하는 통신 규약(HTTP) 중의 하나이다.

 

인터넷 안에서 돌아가는 시스템들을 나열해 보면 아래와 같다.

이름 프로토콜 포트 기능
WWW HTTP 80 웹서비스
WWW HTTPS 443 보안인증서 추가된 웹서비스
FTP FTP 21 파일 전송 서비스
DNS DNS 23 네임서비스
NEWS NNTP 119 인터넷 뉴스 서비스

 

 

 

nginx는 요즘 떠오르는 차세대 웹서버 소프트웨어이다. 적은 자원으로 더 많은 일을 할 수 가 있다.

 

APCHE는 요청이 많을 경우 Process를 생성하여 처리하는 방식(preFork)이다. APACHE는 접속마다 프로세스 또는 Thread를 생성하는 구조이다. 동시 접속 요청이 10,000개라면 그 만큼 Thread 생성 비용이 들 것이고 대용량 요청을 처리할 수 있는 웹서버로서의 한계를 드러내게 된다.

 

반면 NGINX는 Event-driven 방식으로 동작한다.

한 개 또는 고정된 프로세스만 생성하고, 그 프로세스 내부에서 비동기방식으로 효율적으로 작업들을 처리한다. 따라서 동시 접속 요청이 많아도 프로세스 또는 쓰레드 생성 비용이 존재하지 않는다.

 

우분투 18.04에서 NGINX 설치 방법

nginx는 Ubuntu의 레파지토리에 default로 있기에 아래와 같이 명령어를 입력한다.

 

$ sudo apt update

$ sudo apt install nginx

 

그렇다면 아래와 같이 nginx가 설치된다.

root2@DESKTOP-024G8AA:~$ sudo apt update
Get:4 https://download.docker.com/linux/ubuntu bionic InRelease [64.4 kB]
Hit:1 http://mirror.kakao.com/ubuntu bionic InRelease
Get:2 http://mirror.kakao.com/ubuntu bionic-updates InRelease [88.7 kB]
Get:3 http://mirror.kakao.com/ubuntu bionic-backports InRelease [74.6 kB]
Get:5 https://download.docker.com/linux/ubuntu bionic/stable amd64 Packages [9594 B]
Get:6 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Get:7 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 Packages [768 kB]
Get:8 http://mirror.kakao.com/ubuntu bionic-updates/main Translation-en [275 kB]
Get:9 http://mirror.kakao.com/ubuntu bionic-updates/restricted amd64 Packages [18.7 kB]
Get:10 http://mirror.kakao.com/ubuntu bionic-updates/restricted Translation-en [5328 B]
Get:11 http://mirror.kakao.com/ubuntu bionic-updates/universe amd64 Packages [1022 kB]
Get:12 http://mirror.kakao.com/ubuntu bionic-updates/universe Translation-en [315 kB]
Get:13 http://mirror.kakao.com/ubuntu bionic-updates/multiverse amd64 Packages [8096 B]
Get:14 http://mirror.kakao.com/ubuntu bionic-updates/multiverse Translation-en [3972 B]
Get:15 http://mirror.kakao.com/ubuntu bionic-backports/main amd64 Packages [2512 B]
Get:16 http://mirror.kakao.com/ubuntu bionic-backports/main Translation-en [1644 B]
Get:17 http://mirror.kakao.com/ubuntu bionic-backports/universe amd64 Packages [4024 B]
Get:18 http://mirror.kakao.com/ubuntu bionic-backports/universe Translation-en [1856 B]
Get:19 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [545 kB]
Get:20 http://security.ubuntu.com/ubuntu bionic-security/main Translation-en [182 kB]
Get:21 http://security.ubuntu.com/ubuntu bionic-security/restricted amd64 Packages [9856 B]
Get:22 http://security.ubuntu.com/ubuntu bionic-security/restricted Translation-en [3480 B]
Get:23 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [617 kB]
Get:24 http://security.ubuntu.com/ubuntu bionic-security/universe Translation-en [206 kB]
Get:25 http://security.ubuntu.com/ubuntu bionic-security/multiverse amd64 Packages [5476 B]
Get:26 http://security.ubuntu.com/ubuntu bionic-security/multiverse Translation-en [2500 B]
Fetched 4324 kB in 13s (328 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
291 packages can be upgraded. Run 'apt list --upgradable' to see them.


root2@DESKTOP-024G8AA:~$ sudo apt install nginx
[sudo] password for root2:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libnginx-mod-http-geoip libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter libnginx-mod-mail
  libnginx-mod-stream nginx-common nginx-core
Suggested packages:
  fcgiwrap nginx-doc ssl-cert
The following NEW packages will be installed:
  libnginx-mod-http-geoip libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter libnginx-mod-mail
  libnginx-mod-stream nginx nginx-common nginx-core
0 upgraded, 8 newly installed, 0 to remove and 291 not upgraded.
1 not fully installed or removed.
Need to get 598 kB of archives.
After this operation, 2120 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 nginx-common all 1.14.0-0ubuntu1.6 [37.3 kB]
Get:2 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 libnginx-mod-http-geoip amd64 1.14.0-0ubuntu1.6 [11.2 kB]
Get:3 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 libnginx-mod-http-image-filter amd64 1.14.0-0ubuntu1.6 [1
4.5 kB]
Get:4 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 libnginx-mod-http-xslt-filter amd64 1.14.0-0ubuntu1.6 [12
.9 kB]
Get:5 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 libnginx-mod-mail amd64 1.14.0-0ubuntu1.6 [41.7 kB]
Get:6 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 libnginx-mod-stream amd64 1.14.0-0ubuntu1.6 [63.6 kB]
Get:7 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 nginx-core amd64 1.14.0-0ubuntu1.6 [413 kB]
Get:8 http://mirror.kakao.com/ubuntu bionic-updates/main amd64 nginx all 1.14.0-0ubuntu1.6 [3596 B]
Fetched 598 kB in 1s (1183 kB/s)
Preconfiguring packages ...
Selecting previously unselected package nginx-common.
(Reading database ... 46509 files and directories currently installed.)
Preparing to unpack .../0-nginx-common_1.14.0-0ubuntu1.6_all.deb ...
Unpacking nginx-common (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package libnginx-mod-http-geoip.
Preparing to unpack .../1-libnginx-mod-http-geoip_1.14.0-0ubuntu1.6_amd64.deb ...
Unpacking libnginx-mod-http-geoip (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package libnginx-mod-http-image-filter.
Preparing to unpack .../2-libnginx-mod-http-image-filter_1.14.0-0ubuntu1.6_amd64.deb ...
Unpacking libnginx-mod-http-image-filter (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package libnginx-mod-http-xslt-filter.
Preparing to unpack .../3-libnginx-mod-http-xslt-filter_1.14.0-0ubuntu1.6_amd64.deb ...
Unpacking libnginx-mod-http-xslt-filter (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package libnginx-mod-mail.
Preparing to unpack .../4-libnginx-mod-mail_1.14.0-0ubuntu1.6_amd64.deb ...
Unpacking libnginx-mod-mail (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package libnginx-mod-stream.
Preparing to unpack .../5-libnginx-mod-stream_1.14.0-0ubuntu1.6_amd64.deb ...
Unpacking libnginx-mod-stream (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package nginx-core.
Preparing to unpack .../6-nginx-core_1.14.0-0ubuntu1.6_amd64.deb ...
Unpacking nginx-core (1.14.0-0ubuntu1.6) ...
Selecting previously unselected package nginx.
Preparing to unpack .../7-nginx_1.14.0-0ubuntu1.6_all.deb ...
Unpacking nginx (1.14.0-0ubuntu1.6) ...
Processing triggers for ufw (0.35-5) ...
Setting up docker.io (18.09.2-0ubuntu1~18.04.1) ...
invoke-rc.d: could not determine current runlevel
Processing triggers for ureadahead (0.100.0-20) ...
Setting up nginx-common (1.14.0-0ubuntu1.6) ...
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /lib/systemd/system/nginx.service.
Setting up libnginx-mod-http-image-filter (1.14.0-0ubuntu1.6) ...
Processing triggers for systemd (237-3ubuntu10.3) ...
Setting up libnginx-mod-mail (1.14.0-0ubuntu1.6) ...
Processing triggers for man-db (2.8.3-2) ...
Setting up libnginx-mod-http-xslt-filter (1.14.0-0ubuntu1.6) ...
Setting up libnginx-mod-http-geoip (1.14.0-0ubuntu1.6) ...
Setting up libnginx-mod-stream (1.14.0-0ubuntu1.6) ...
Setting up nginx-core (1.14.0-0ubuntu1.6) ...
Cannot open netlink socket: Protocol not supported
invoke-rc.d: could not determine current runlevel
Setting up nginx (1.14.0-0ubuntu1.6) ...
Processing triggers for ureadahead (0.100.0-20) ...
Processing triggers for ufw (0.35-5) ...
W: APT had planned for dpkg to do more than it reported back (40 vs 44).
   Affected packages: docker.io:amd64

 

방화벽설치

 

NGINX를 테스트하기전에 ufw라는 방화벽을 설치한다.

root2@DESKTOP-024G8AA:~$ sudo ufw app list
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

 

아직 서버에 SSL을 구성하지 않았으므로 포트 80의 트래픽만 허용하면 된다.

 

다음을 입력하여 활성화 할 수 있다.

 

$ sudo ufw allow 'nginx HTTP'

 

----------

윈도우 우분투는 iptables를 사용할 수 없다고 나온다.

 

nginx의 상세 설정은 conf파일을 통해 이루어지며 자세한 것은 아래 링크에 있다.

 

https://sarc.io/index.php/nginx/61-nginx-nginx-conf

 

Nginx 주요 설정 (nginx.conf)

Technical Note 정보 appsroot 님이 작성하신 글입니다. 카테고리: [ Nginx ] 게시됨: 23 February 2014 작성됨: 19 February 2014 최종 변경: 09 February 2018 조회수: 68502 1. 개요 지난 번 포스팅을 통해 OS X에서 Nginx 1.4.4를 설치하여 보았습니다. 강철지그님께서는 계속 작업을 해주고 계십니다. 한편 왜 Nginx를 써야 하는지도 언급된 적이 있지요. 이번에는 설정 파일인

sarc.io

systemctl start nginx

systemctl stop nginx

systemctl restart nginx

 

리눅스에서는 위 명령어로 nginx를 쉽게 조작할 수 있다.

 

 

반응형
반응형

시퀄라이즈는 ORM(Object-relational Mapping)으로 분류가 된다.

ORM은 자바스크립트 객체와 데이터베이스의 릴레이션을 매핑해주는 도구이다.

 

1. express를 이용해서 새 프로젝트 생성

$ express sequlize_ex --view=pug

 

위에 나온대로 디렉토리를 바꿔준뒤 npm i를 해준다.

$ cd sequelize_ex
$ npm i

 

방금 만든 프로젝트에 sequelize와 mysql2 패키지를 설치한다. 그 후 sequelize 커맨드를 사용하기 위해 sequelize-cli를 전역 설치

$ npm i sequelize mysql2
$ npm i -g sequelize-cli
$ sequelize init

 

그 뒤 파일들을 아래대로 세팅

models/index.js

const path = require('path');
const Sequelize = require('sequelize'); //sequelize 연결

const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);


db.sequelize = sequelize;
db.Sequelize = Sequelize;

//user와 comment 테이블을 연결시킨다.
db.User = require('./user')(sequelize, Sequelize);
db.Comment = require('./comment')(sequelize, Sequelize); 

//테이블 간의 관계를 정의해줌
db.User.hasMany(db.Comment, {foreignKey: 'commenter', sourceKey: 'id'});
db.Comment.belongsTo(db.User, {foreignKey: 'commenter', targetKey: 'id'});

module.exports = db; //db라는 객체에 user와 comment 모델을 담는다.

 

시퀄라이즈를 통해 익스프레스 앱과 MYSQL을 연결한다. app.js에서 추가해준다.

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commentsRouter = require('./routes/comments');

//추가
var sequelize = require('./models').sequelize;

var app = express();

//추가
sequelize.sync();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/comments', commentsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

 

번거롭지만 MYSQL에서 정의한 테이블을 시퀄라이즈에서도 정의해야 한다.

기본적으로 모델 이름은 단수형으로 테이블 이름은 복수형으로 사용한다.

 

models/user.js

module.exports = (sequelize, DataTypes) => {
    return sequelize.define('user', {
        name: {
            type: DataTypes.STRING(20),
            allowNull: false,
            unique: true,
        },
        age: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
        },
        married: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
        },
        comment: {
            type: DataTypes.TEXT,
            allowNull: true,
        },
        created_at: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW,
        },
    }, {
        timestamps: false,
    });
};

 알아서 id를 기본 키로 연결하므로 id 컬럼은 적어줄 필요가 없다.

그리고 알아둘 것이 timestamps가 true면 시퀄라이즈는 createdAt과 updatedAt 컬럼을 추가하며 행이 생성 될때와 수정될 때의 시간을 자동으로 입력한다.

 

하지만 여기서는 created_at 컬럼을 직접만들었으므로 timestamps는 false로 하였다.

참고로 paranoid: true 도 많이 사용하는데 이러면 deletedAt이라는 컬럼이 추가되어 행이 삭제 되었을 때 제거하는 대신 deletedAt에 제거된 날짜를 입력한다.

 

실무에서는 데이터베이스 복원을 위하여 데이터 삭제는 왠만해선 하지 않는다. 사이트에서 회원탈퇴해도 같은 아이디로는 재가입할 수 없는 것도 이러한 이치.

 

이 외에도 underscored 옵션을 사용하여 캐멀형식이 아닌 _를 중간에 써주어 created_at 처럼 표기시킬 수도 있다.

 

comment 모델도 만들어 보자.

models/comment.js

module.exports = (sequelize, DataTypes) => {
    return sequelize.define('comment', {
        comment: {
            type: DataTypes.STRING(100),
            allowNull: false,
        },
        created_at: {
            type: DataTypes.DATE,
            allowNull: true,
            defaultValue: DataTypes.NOW,
        },
    }, {
        timestamps: false,
    });
};

 

아까 위에서 index.js에서 보듯이 db라는 객체에 user와 comment 모델을 담아두었다.

models/index.js

const path = require('path');
const Sequelize = require('sequelize'); //sequelize 연결

const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);


db.sequelize = sequelize;
db.Sequelize = Sequelize;

//user와 comment 테이블을 연결시킨다.
db.User = require('./user')(sequelize, Sequelize);
db.Comment = require('./comment')(sequelize, Sequelize); 

//테이블 간의 관계를 정의해줌
db.User.hasMany(db.Comment, {foreignKey: 'commenter', sourceKey: 'id'});
db.Comment.belongsTo(db.User, {foreignKey: 'commenter', targetKey: 'id'});

module.exports = db; //db라는 객체에 user와 comment 모델을 담는다.

db객체를 require하여 User와 Comment 모델에 접근할 수 있다.

 

마지막으로 config.json을 수정하여 mysql 비밀번호를 입력하여 연결시켜준다.

본인은 비밀번호는 12351235로 하였다. 

config/config.json

{
  "development": {
    "username": "root",
    "password": "12351235",
    "database": "nodejs",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  }
}

 

그리고 나머지 html 코딩파일은 아래의 파일을 다운로드 받아서 덮어쓰기 한다.

 

 

learn-sequelize.zip
6.28MB

 

 

그 뒤 npm start를 실행시킨다.

 

localhost:3000으로 들어가면 아래와 같은 페이지가 나타난다.

위에 이름나이를 등록하고 중간에 리스트를 클릭하면 아래에 클릭한 리스트가 나타난다.

 

 

 

 

 

 

 

 

 

 

 

반응형
반응형

1. Insert 문

SQL문법

INSERT INTO nodejs.users (name, age, married, comment) VALUES ('zero', 24, 0, '자기소개1');

sequelize 문법

const { User } = require('../models')
User.create({
name: 'zero',
age: 24,
married: false,
comment: '자기소개1',
});

 

이하 아래부터는 위는 SQL문 아래는 seq문법이다.

 

 

 

- SELECT * FROM nodejs.users;

- User.findALL({});

 

- SELECT * FROM nodejs.users LIMIT 1;

- User.findOne({});

 

- SELECT name, married FROM nodejs.users;

- User.findALL({

  attributes: ['name', 'married'],

});

 

- SELECT name, age FROM nodejs.users WHERE married =1 AND age > 30;

 

- const { User, Sequelize : {Op}} = require('../models');

User.findAll({

  attributes: ['name', 'age'],

where: {

  married: 1,

age: { [Op.gt]: 30 },

},

});

 

- SELECT id, name FROM users ORDER BY age DESC;

- User.findAll({

  attributes: ['id', 'name'],

order: [[ 'age', 'DESC']],

});

 

- UPDATE nodejs.users SET comment = '바꿀 내용' WHERE id = 2;

- User.update({

  comment: '바꿀 내용',

}, {

  where : { id : 2 },

});

 

- DELETE FROM nodejs.users WHERE id = 2;

- User.destroy({

 where: { id : 2},

});

 

반응형

+ Recent posts