Docker Swarm

00_8_3·2021년 3월 12일
1

Docker Swarm With Node JS

Swarm 이란

Swarm은 무리, 군중이라는 의미를 가지고 있습니다. Docker Swarm은 여러 컨테이너를 클러스터로 만들어 관리해줍니다.
Docker 개발자들이 Swarm을 개발하였기 때문에 이미 Docker 핵심 기능으로 포함되어있습니다. 따라서, Docker를 사용한 orchestration infra를 구축할 때 가장 호환성이 좋습니다.

선행지식

  • docker
  • docker-compose
  • nginx
  • node.js

개요

Node JS 서버를 도커라이징 하고 swarm cluster를 이용한 여러 개의 컨테이너로 배포 할 것 입니다. 그리고 nginx를 이용한 단일 IP로 로드 밸런싱을 볼 수 있습니다.

Node 서버

const express = require('express')
const app = express()
const os = require('os');


app.get('/', (req, res) => {
    res.send(`${os.hostname()}`);
})

const port = process.env.NODE_ENV || 3000
app.listen(port, () => {
    console.log(`서버 시작${port}`)
})

간단한 노드 서버를 작성합니다.

Node 서버 Dockerfile

FROM node
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
CMD node app.js
EXPOSE 3000

1

Dockerfile를 작성해주고
docker build -t username/appname . 를 실행합니다

username : 도커허브 아이디
appname : 지정할 서비스 이름

주의! .도 같이 찍어줘야 합니다.

2

docker image push username/appname
생성한 이미지를 도커허브에 올려줍니다.

ex

docker build -t 개죽이/swarmapp
docker image push 개죽이/swarmapp

Nginx Dockerfile & nginx.conf

FROM nginx
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf

위 와 같이 간단한 Dockerfile 작성 후
이미지 생성, 이미지 push를 해줍니다.

ex

docker build -t 개죽이/swarmapp_nginx
docker image push 개죽이/swarmapp_nginx

주의! 다른 폴더 루트에서 명령어 입력

upstream loadbalance {
    listen 80;
    least_conn;
  # aws 같은 서버 사용 시 서버 ip
  # server 13.233.229.122:3000;
  
    server server:3000;
    # 밑의 docker-compose의 service 이름
}

server {
    location / {
        proxy_pass http://loadbalance;
    }
}

간단하게 설명하면

80포트 접속 -> nginx -> server:3000으로 로드밸런싱

swarm 실행

docker swarm init 입력

docker-compose 작성

version: '3'

services:
  nodeapp:
   image: 개죽이/swarm
   ports:
     - 3000:3000
   deploy:
    // mode: replicated 
     replicas: 10
     restart_policy:
       max_attempts: 3
       condition: on-failure       
     update_config:
       parallelism: 3
       delay: 10s
   networks: 
    - balance 
  
  proxy:
    image: 개죽이/swarm
    ports:
      - 80:80
    depends_on:
      - nodeapp
    deploy:
      placement:
        constraints: [node.role == manager]
    networks: 
      - balance

networks:
  balance:
    driver: overlay

이전의 compose와 다른 점으로 deploy가 있습니다.
도커 버전 3부터 추가 되었습니다

  • mode : option으로 globalreplicated가 있습니다.(default : replicated)
    참조 : global and replicated services

  • replicas : mode가 replicated라면 실행 할 컨테이너 수를 명시합니다.

  • restart_policy : restart를 대신해 컨테이너 재실행을 명시합니다.

    • max_attempts :
    • condition : none, on-failure, any (default : any)
  • update_config : service가 어떻게 수정되는지 명시합니다.

    • parallelism : 한 번에 rollback하는 컨테너의 수를 명시 (0 일 때 모든 컨테이너가 같이 rollback)
    • delay : 각각의 컨테이너 그룹의 rollback간의 기다리는 시간을 명시 (default : 0s)
  • placement : constraintspreferences를 명시
    참조 : node service constraints

실행

docker stack deploy -c docker-compose.yml swarm 입력 하여 실행 후
docker service lsdocker service ps servicename로 배포 상태 확인

실행 중인 컨테이너 보기 : docker container ls

실행이 되었다면 해당 서버(또는 로컬)로 접근 후 새로고침 할 때마다
바뀌는 호스트네임을 볼 수 있다.

실행 도중 replicas 수정

실행 중인 서버의 컨테이너 수를 변경하고 싶다면
docker service scale servicename=replicas를 입력해보자

ex

docker service scale swarm=50

docker service ls로 확인해보자

삭제

docker stack rm swarm

docker stack rm

마침

Docker swarm 모드를 이용한 간단한 cluster를 구성해보았다.

2개의 댓글

comment-user-thumbnail
2022년 3월 31일

이거 하시는 분들은 nginx 설정에서
listen 80 지우고
server server:3000을 server :3000으로 바꾸어 주어야 됩니다.

1개의 답글