본문 바로가기

클라우드/Docker(도커)

[도커] 쉘스크립트에 도커 명령어 작성 & Docker compose & swarm

동일한 컨테이너 이름을 사용할 수 없음

동일한 이름의 컨테이너가 존재하는 경우, 기존 컨테이너를 삭제해야 컨테이너를 생성할 수 있음



vagrant@xenial64:~$ docker container run --name echo -itd -p 8888:8080 myanjini/echo:latest /bin/bash

 

vagrant@xenial64:~$ docker container run --name echo -itd -p 8889:8080 myanjini/echo:latest /bin/bash

docker: Error response from daemon: Conflict. The container name "/echo" is already in use by container "32b348b10a6244a6f8704bbb67a9450d2ebe7d6e8e40243623bade035edf0acb". You have to remove (or rename) that container to be able to reuse that name.

See 'docker run --help'.

 

vagrant@xenial64:~$ docker container rm -f echo

echo

 

vagrant@xenial64:~$ docker container run --name echo -itd -p 8889:8080 myanjini/echo:latest /bin/bash

3148d692d80fb153e48ba95eb3fd5c5b9a5559c3f8bf01242eac9abf69326997



기존에 생성된 컨테이너가 있으면 삭제하고, 새롭게 컨테이너를 생성

vagrant@xenial64:~$ docker container rm -f echo ; docker container run --name echo -itd -p 8889:8080 myanjini/echo:latest /bin/bash

echo

1f6d2aa0a93f07355b73131431d19cdfdff7ef4cb86818393fa5b9a4a9bd75b9



Quiz. 아래 요건을 만족하는 쉘 스크립트를 작성하시오. 

  1. run.sh 스크립트를 작성합니다. 

  2. run.sh 스크립트는 실행할 컨테이너의 이름을 파라미터로 입력받습니다.  (예) ⇒ $ run.sh echo

  3. 동일한 이름의 컨테이너가 존재하면 해당 컨테이너를 삭제하고 컨테이너를 실행(생성)합니다. 

  4. 컨테이너 생성 스크립트는 다음과 같은 형식입니다. 

docker container run --name 컨테이너이름 -itd -p 8888:8080 myanjini/echo:latest /bin/bash



작성한 스크립트 코드와 실행 결과를 아래 공유 문서에 OO조-OOO 탭에 등록해 주세요. (9월 20일까지)

https://docs.google.com/spreadsheets/d/1ZXAcSGC_1EhUrANhp6Cx91GSFR62fPX2eVyCJ5X4Mv0/edit#gid=0



도커 컴포즈 (P76)

설치 

https://docs.docker.com/compose/install/

 

vagrant@xenial64:~$ sudo curl -L "https://github.com/docker/compose/releases/download/1.27.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

                                 Dload  Upload   Total   Spent    Left  Speed

100   651  100   651    0     0   1517      0 --:--:-- --:--:-- --:--:--  1517

100 11.6M  100 11.6M    0     0   223k      0  0:00:53  0:00:53 --:--:--  249k

 

vagrant@xenial64:~$ sudo chmod +x /usr/local/bin/docker-compose

 

vagrant@xenial64:~$ docker-compose version

docker-compose version 1.27.2, build 18f557f9

docker-py version: 4.3.1

CPython version: 3.7.7

OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019

 

 

docker-compose 명령으로 컨테이너를 실행

 

https://docs.docker.com/compose/compose-file/



#1 작업 디렉터리 및 docker-compose.yml 파일을 생성

vagrant@xenial64:~$ mkdir ~/compose && cd ~/compose

vagrant@xenial64:~/compose$ vi docker-compose.yml

version: "3"                          # 문법 버전

services:            

  echo:                               # 컨테이너 이름

    image: myanjini/echo:latest       # 컨테이너 생성에 사용할 도커 이미지 

    ports:

      - 9000:8080                     # 포트 포워딩 ⇒ 호스트:컨테이너

 

#2 컨테이너 실행

vagrant@xenial64:~/compose$ docker-compose up

Creating network "compose_default" with the default driver

Creating compose_echo_1 ... done                                                                                  

Attaching to compose_echo_1

echo_1  | 2020/09/16 02:28:49 start server



#3 다른 터미널에서 컨테이너 생성 여부를 확인

vagrant@xenial64:~$ docker container ls

CONTAINER ID        IMAGE                  COMMAND                  CREATED              STATUS              PORTS                    NAMES

edda7a452f20        myanjini/echo:latest   "go run /echo/main.go"   About a minute ago   Up About a minute   0.0.0.0:9000->8080/tcp compose_echo_1

f6a029954b25        myanjini/echo:latest   "/bin/bash"              37 minutes ago       Up 37 minutes       0.0.0.0:8888->8080/tcp   echo

39786eb6abac        wordpress              "docker-entrypoint.s…"   3 hours ago          Up 3 hours          0.0.0.0:32778->80/tcp    wordpress_hostvolume

35eb27e65ad4        mysql:5.7              "docker-entrypoint.s…"   3 hours ago          Up 3 hours          3306/tcp, 33060/tcp      wordpressdb_hostvolume

 

#4 컨테이너 중지 (중지와 함께 삭제도 수행)

vagrant@xenial64:~/compose$ docker-compose down

Stopping compose_echo_1 ... done                                                                                                            Removing compose_echo_1 ... done                                                                                                          Removing network compose_default

 

vagrant@xenial64:~/compose$ docker container ls -a

CONTAINER ID        IMAGE                  COMMAND              CREATED      STATUS                 PORTS                  NAMES

f6a029954b25        myanjini/echo:latest   "/bin/bash"              39 minutes ago      Up 39 minutes       0.0.0.0:8888->8080/tcp   echo

d6ec70aa8c04        ubuntu:14.04       "/bin/bash"              2 hours ago         Exited (0) 2 hours ago         volume_from_container

39786eb6abac        wordpress        "docker-entrypoint.s…"   3 hours ago         Up 3 hours               0.0.0.0:32778->80/tcp    wordpress_hostvolume

35eb27e65ad4    mysql:5.7     "docker-entrypoint.s…"   3 hours ago     Up 3 hours    3306/tcp, 33060/tcp     wordpressdb_hostvolume



이미지를 만들고 컨테이너를 실행

#1 기본에 만들어 놓은 Dockerfile, main.go 파일을 작업 디렉터리로 복사

vagrant@xenial64:~/compose$ cp ../chap02/Dockerfile ./

vagrant@xenial64:~/compose$ cp ../chap02/main.go ./

vagrant@xenial64:~/compose$ ls

docker-compose.yml  Dockerfile  main.go

 

#2 Dockerfile을 이용해서 이미지를 빌드 후 실행도록 docker-compose.yml 파일을 수정

vagrant@xenial64:~/compose$ vi docker-compose.yml

version: "3"

services:

  echo:

    #image: myanjini/echo:latest

    build: .

    ports:

      - 9000:8080



vagrant@xenial64:~/compose$ docker-compose up -d --build

Creating network "compose_default" with the default driver

Building echo ⇐ --build 옵션을 추가했기 때문에 이미지를 빌드(생성)

Step 1/4 : FROM   golang:1.9

1.9: Pulling from library/golang

55cbf04beb70: Already exists

1607093a898c: Already exists

9a8ea045c926: Already exists

d4eee24d4dac: Already exists

9c35c9787a2f: Already exists

8b376bbb244f: Already exists 

0d4eafcc732a: Already exists

186b06a99029: Already exists

Digest: sha256:8b5968585131604a92af02f5690713efadf029cc8dad53f79280b87a80eb1354

Status: Downloaded newer image for golang:1.9

 ---> ef89ef5c42a9

Step 2/4 : RUN    mkdir   /echo

 ---> Running in cf2401922dea

Removing intermediate container cf2401922dea

 ---> ce13106f0f84

Step 3/4 : COPY   main.go   /echo

 ---> af0fb2e70685

Step 4/4 : CMD   [ "go", "run", "/echo/main.go" ]

 ---> Running in cdcfe7cfad03

Removing intermediate container cdcfe7cfad03

 ---> 783ef639299e

 

Successfully built 783ef639299e

Successfully tagged compose_echo:latest

Creating compose_echo_1 ... done                                                                                                            vagrant@xenial64:~/compose$ ⇐ -d 옵션을 추가했기 때문에 명령어 입력이 가능 (백그라운드 실행)

 

vagrant@xenial64:~/compose$ docker image ls

REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE

compose_echo        latest              783ef639299e        About a minute ago   750MB

wordpress           latest              420b971d0f8b        4 days ago           546MB

mysql               5.7                 ef08065b0a30        5 days ago           448MB

myanjini/echo       latest              11c732eb2923        8 months ago         750MB

ubuntu              14.04               6e4f1fe62ff1        9 months ago         197MB

golang              1.9                 ef89ef5c42a9        2 years ago          750MB

 

vagrant@xenial64:~/compose$ docker container ls

CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                    NAMES

6cb17d61c6f1        compose_echo           "go run /echo/main.go"   4 minutes ago       Up 4 minutes        0.0.0.0:9000->8080/tcp   compose_echo_1

f6a029954b25        myanjini/echo:latest   "/bin/bash"              About an hour ago   Up About an hour    0.0.0.0:8888->8080/tcp   echo

39786eb6abac        wordpress              "docker-entrypoint.s…"   3 hours ago         Up 3 hours          0.0.0.0:32778->80/tcp    wordpress_hostvolume

35eb27e65ad4        mysql:5.7              "docker-entrypoint.s…"   3 hours ago         Up 3 hours          3306/tcp, 33060/tcp      wordpressdb_hostvolume




교재 80페이지부터 84페이지 참고해서 실습을 진행해 주세요. 

docker-compose.yml 파일은 아래 수정된 내용을 참고해 주세요.

젠킨스 컨테이너 실행 ⇒ 테스트하지 마세요.

#1 docker-compose.yml 파일 작성

vagrant@xenial64:~/compose$ vi docker-compose.yml

version: "3"

services:

  master:

    container_name: master

    image: jenkinsci/jenkins

    ports:

      - 8080:8080

#    volumes:

#      - ./jenkins_home:/var/jenkins_home

 

#2 컨테이너 실행

vagrant@xenial64:~/compose$ docker-compose up

Recreating master ... done                                                                                                                      Attaching to master

master    | Running from: /usr/share/jenkins/jenkins.war

master    | webroot: EnvVars.masterEnvVars.get("JENKINS_HOME")

:

master    | Sep 16, 2020 3:07:04 AM jenkins.install.SetupWizard init

master    | INFO:

master    |

master    | *************************************************************

master    | *************************************************************

master    | *************************************************************

master    |

master    | Jenkins initial setup is required. An admin user has been created and a password generated.

master    | Please use the following password to proceed to installation:

master    |

master    | 0ff8e9cb2798460f888ca6ff23c94e73 ⇐ 초기 관리자 패스워드

master    |

master    | This may also be found at: /var/jenkins_home/secrets/initialAdminPassword

master    |

master    | *************************************************************

master    | *************************************************************

master    | *************************************************************

master    |

master    | --> setting agent port for jnlp

master    | --> setting agent port for jnlp... done

:

master    | INFO: Finished Download metadata. 21,138 ms ⇐ 컨테이너 실행 상태

 

#3 초기 설정 (교재 82~23페이지 참조)

본인 PC에서 브라우저를 실행 후 http://localhost:8080 으로 접속 (VirtualBox 관리자에서 포트 포워딩 필요)

:

 

#4 마스터 젠킨스 용 SSH 키 생성

vagrant@xenial64:~/compose$ docker container exec -it master ssh-keygen -t rsa

Generating public/private rsa key pair.

Enter file in which to save the key (/var/jenkins_home/.ssh/id_rsa):

Created directory '/var/jenkins_home/.ssh'.

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /var/jenkins_home/.ssh/id_rsa.

Your public key has been saved in /var/jenkins_home/.ssh/id_rsa.pub.

The key fingerprint is:

SHA256:/RVcQrgb6Kj0zrsCUrjmUgo6fAcBEayVOsQPzUyaDZA jenkins@a0aff5774123

The key's randomart image is:

+---[RSA 2048]----+

|==Bo         oo .|

|E*B+          .. o |

|o=+o        . .o  |

|+ .o.        .. o  . |

| . o.      So.  o.  |

|. =.. . .       ....    |

|+= ..o o    .      |

|=... .o..             |

| o. .  o=o         |

+----[SHA256]-----+

 

vagrant@xenial64:~/compose$ docker container exec master cat /var/jenkins_home/.ssh/id_rsa.pub

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCpRyrGcMe9WNT4rSy2Wnw3q3uU17AWT6M/ONOn7g5PHzxZfwhzUnlndJEgXZMgsL1Q0x1l5McQHKyirpBm+8krrwrtXBfBg1U7S69DYPce247l8jz2Vt11loM3GK0Gn3iFIhJVtzUNoerClaDWmIV3j2oWEqSAbDnFzizhQ7Bz9Eb3cPWJOLtPojHbE7kqdJIv1gfDmfZA9LwMCDobpYq8PswN7wuf8JQDI5naXkmDkNtPRswz+VVqhb/EVzSZSZIab0REN/rK+6RBGprJDXA7YVSkZHN1SVPEQks/FPhP10+rIsWdbYCfkIVQNAk9zXZyB/FnA9palW5RlBIuJvz7 jenkins@a0aff5774123



#5 슬레이브 젠킨스 컨테이너를 생성

vagrant@xenial64:~/compose$ vi docker-compose.yml

version: "3"

services:

  master:

    container_name: master

    image: jenkinsci/jenkins

    ports:

      - 8080:8080

    links:

      - slave01

#    volumes:

#      - ./jenkins_home:/var/jenkins_home

  slave01:

    container_name: slave01

    image: jenkinsci/ssh-slave

    environment:

      - JENKINS_SLAVE_SSH_PUBKEY=ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCpRyrGcMe9WNT4rSy2Wnw3q3uU17AWT6M/ONOn7g5PHzxZfwhzUnlndJEgXZMgsL1Q0x1l5McQHKyirpBm+8krrwrtXBfBg1U7S69DYPce247l8jz2Vt11loM3GK0Gn3iFIhJVtzUNoerClaDWmIV3j2oWEqSAbDnFzizhQ7Bz9Eb3cPWJOLtPojHbE7kqdJIv1gfDmfZA9LwMCDobpYq8PswN7wuf8JQDI5naXkmDkNtPRswz+VVqhb/EVzSZSZIab0REN/rK+6RBGprJDXA7YVSkZHN1SVPEQks/FPhP10+rIsWdbYCfkIVQNAk9zXZyB/FnA9palW5RlBIuJvz7 jenkins@a0aff5774123

 

vagrant@xenial64:~/compose$ docker-compose up -d

 

vagrant@xenial64:~/compose$ docker-compose ps

 Name                Command               State                 Ports

------------------------------------------------------------------------------------

master    /sbin/tini -- /usr/local/b ...   Up      50000/tcp, 0.0.0.0:8080->8080/tcp

slave01   setup-sshd                       Up      22/tcp








docker-compose를 이용해서 MySQL과 Wordpress를 연동

 

기존 컨테이너, 이미지, 볼륨, … 등을 모두 삭제

vagrant@xenial64:~/compose$ docker container rm -f $(docker container ls -aq)

vagrant@xenial64:~/compose$ docker image rm -f $(docker image ls -aq)

vagrant@xenial64:~/compose$ docker volume rm -f $(docker volume ls -q)

 

docker-compose.yml 파일을 생성

version: "3.3"


services:

  db:

    image: library/mysql:5.7

    volumes:

      - /home/vagrant/db_data:/var/lib/mysql

    restart: always

    environment:

      MYSQL_ROOT_PASSWORD: password

      MYSQL_DATABASE: wordpress

      MYSQL_USER: wordpress

      MYSQL_PASSWORD: wordpress


  wordpress:

    depends_on:

      - db

    image: library/wordpress:latest

    ports:

      - "80:80"

    restart: always

    environment:

      WORDPRESS_DB_HOST: db:3306

      WORDPRESS_DB_USER: wordpress

      WORDPRESS_DB_PASSWORD: wordpress

      WORDPRESS_DB_NAME: wordpress

volumes:

  db_data: {}



vagrant@xenial64:~/compose$ docker-compose up -d

Creating network "compose_default" with the default driver

Creating volume "compose_db_data" with default driver

Pulling db (library/mysql:5.7)...

5.7: Pulling from library/mysql

d121f8d1c412: Pull complete                                                                                                                   f3cebc0b4691: Pull complete                                                                                                                   1862755a0b37: Pull complete                                                                                                                 489b44f3dbb4: Pull complete                                                                                                                   690874f836db: Pull complete                                                                                                                   baa8be383ffb: Pull complete                                                                                                                   55356608b4ac: Pull complete                                                                                                                   277d8f888368: Pull complete                                                                                                                   21f2da6feb67: Pull complete                                                                                                                   2c98f818bcb9: Pull complete                                                                                                                   031b0a770162: Pull complete                                                                                                                 Digest: sha256:14fd47ec8724954b63d1a236d2299b8da25c9bbb8eacc739bb88038d82da4919

Status: Downloaded newer image for mysql:5.7

Pulling wordpress (library/wordpress:latest)...

latest: Pulling from library/wordpress

d121f8d1c412: Already exists                                                                                                                    58b3577b786a: Pull complete                                                                                                                  60538287851f: Pull complete                                                                                                                  c53ff72fe225: Pull complete                                                                                                                     79b018c8773f: Pull complete                                                                                                                    fbe3e00ac4b0: Pull complete                                                                                                                   ff35226e1df8: Pull complete                                                                                                                   ab3b1d46dd82: Pull complete                                                                                                                 b29cdd230d9a: Pull complete                                                                                                                 d466b05cf627: Pull complete                                                                                                                   771f930f6d23: Pull complete                                                                                                                   b89a2786f2a3: Pull complete                                                                                                                   c35594c34f69: Pull complete                                                                                                                   8e3c480bd8bf: Pull complete                                                                                                                   2d3e26ca1157: Pull complete                                                                                                                   cc0d53b93bc3: Pull complete                                                                                                                   dbcd12305020: Pull complete                                                                                                                 90356c70a472: Pull complete                                                                                                                   ceb2ac363e49: Pull complete                                                                                         

202d7e2f6c6c: Pull complete                                                                                                                     Digest: sha256:7b67b32c076e9463a804182e0356966829d5533184c5064e22a7b97686e2154b

Status: Downloaded newer image for wordpress:latest

Creating compose_db_1 ... done                                                                                                                Creating compose_wordpress_1 ... done                                                                                                    vagrant@xenial64:~/compose$

 

vagrant@xenial64:~/compose$ docker-compose ps

       Name                      Command               State          Ports

----------------------------------------------------------------------------------

compose_db_1          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_wordpress_1   docker-entrypoint.sh apach ...   Up      0.0.0.0:80->80/tcp



VirtualBox 관리자에서 포트 포워딩 설정

 

내 PC에서 http://localhost:8888 로 접속

 

docker-compose scale

호스트 포트가 고정되면 동일한 컨테이너 생성이 불가

 

docker-compose.yml 파일을 생성

version: "3.3"


services:

  db:

    image: library/mysql:5.7

    volumes:

      - /home/vagrant/db_data:/var/lib/mysql

    restart: always

    environment:

      MYSQL_ROOT_PASSWORD: password

      MYSQL_DATABASE: wordpress

      MYSQL_USER: wordpress

      MYSQL_PASSWORD: wordpress


  wordpress:

    depends_on:

      - db

    image: library/wordpress:latest

    ports:

      - "80"

    restart: always

    environment:

      WORDPRESS_DB_HOST: db:3306

      WORDPRESS_DB_USER: wordpress

      WORDPRESS_DB_PASSWORD: wordpress

      WORDPRESS_DB_NAME: wordpress

volumes:

  db_data: {}

 

vagrant@xenial64:~/compose$ docker-compose up -d

Creating network "compose_default" with the default driver

Creating compose_db_1 ... done                                                                                                        Creating compose_wordpress_1 ... done    

                                                                                                       

vagrant@xenial64:~/compose$ docker-compose scale db=2 wordpress=2

WARNING: The scale command is deprecated. Use the up command with the --scale flag instead.

Starting compose_db_1 ... done                                                                                                                Creating compose_db_2 ... done                                                                                                                Starting compose_wordpress_1 ... done                                                                                                      Creating compose_wordpress_2 ... done       

                                                                                                    

vagrant@xenial64:~/compose$ docker-compose ps

       Name                      Command               State           Ports

------------------------------------------------------------------------------------

compose_db_1          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_db_2          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_wordpress_1   docker-entrypoint.sh apach ...   Up      0.0.0.0:32779->80/tcp

compose_wordpress_2   docker-entrypoint.sh apach ...   Up      0.0.0.0:32780->80/tcp

 

vagrant@xenial64:~/compose$ docker-compose scale db=4 wordpress=5

WARNING: The scale command is deprecated. Use the up command with the --scale flag instead.

Starting compose_db_1 ... done                                                                                                                Starting compose_db_2 ... done                                                                                                                Creating compose_db_3 ... done                                                                                                                Creating compose_db_4 ... done                                                                                                                Starting compose_wordpress_1 ... done                                                                                                       Starting compose_wordpress_2 ... done                                                                                                     Creating compose_wordpress_3 ... done                                                                                                     Creating compose_wordpress_4 ... done                                                                                                     Creating compose_wordpress_5 ... done        

                                                                                                   

vagrant@xenial64:~/compose$ docker-compose ps

       Name                      Command               State           Ports

------------------------------------------------------------------------------------

compose_db_1          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_db_2          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_db_3          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_db_4          docker-entrypoint.sh mysqld      Up      3306/tcp, 33060/tcp

compose_wordpress_1   docker-entrypoint.sh apach ...   Up      0.0.0.0:32779->80/tcp

compose_wordpress_2   docker-entrypoint.sh apach ...   Up      0.0.0.0:32780->80/tcp

compose_wordpress_3   docker-entrypoint.sh apach ...   Up      0.0.0.0:32781->80/tcp

compose_wordpress_4   docker-entrypoint.sh apach ...   Up      0.0.0.0:32783->80/tcp

compose_wordpress_5   docker-entrypoint.sh apach ...   Up      0.0.0.0:32782->80/tcp

 

vagrant@xenial64:~/compose$ docker-compose scale db=1 wordpress=1

WARNING: The scale command is deprecated. Use the up command with the --scale flag instead.

Stopping and removing compose_db_2 ... done                                                                                           Stopping and removing compose_db_3 ... done                                                                                           Stopping and removing compose_db_4 ... done                                                                                           Stopping and removing compose_wordpress_2 ... done                                                                                Stopping and removing compose_wordpress_3 ... done                                                                                  Stopping and removing compose_wordpress_4 ... done                                                                                  Stopping and removing compose_wordpress_5 ... done                                                                                  vagrant@xenial64:~/compose$



vagrant@xenial64:~/compose$ docker-compose up -d --scale db=2 ⇐ 컨테이너 실행 시 스케일 조정

Creating network "compose_default" with the default driver

Creating compose_db_1 ... done                                                                                                                Creating compose_db_2 ... done                                                                                                                Creating compose_wordpress_1 ... done    




도커 스웜 클러스터를 구성

테스트 환경 구성 방법1 

#1 기존 리소스 정리

모든 가상머진을 중지합니다. 필요하다면 가상 머신 이미지를 삭제해서 디스크 공간도 확보해 두세요.



#2 아래 3개 폴더 아래에 Vagrantfile을 생성

C:\HashiCorp\swarm-manager

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

# config.vm.box = "centos/7"

  config.vm.box = "generic/centos7"

  config.vm.hostname = "swarm-manager"

  config.vm.network "private_network", ip: "192.168.111.100"

  config.vm.synced_folder ".", "/home/vagrant/sync", disabled: true

end



C:\HashiCorp\swarm-worker1

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

# config.vm.box = "centos/7"

  config.vm.box = "generic/centos7"

  config.vm.hostname = "swarm-worker1"

  config.vm.network "private_network", ip: "192.168.111.101"

  config.vm.synced_folder ".", "/home/vagrant/sync", disabled: true

end



C:\HashiCorp\swarm-worker2 

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

# config.vm.box = "centos/7"

  config.vm.box = "generic/centos7"

  config.vm.hostname = "swarm-worker2"

  config.vm.network "private_network", ip: "192.168.111.102"

  config.vm.synced_folder ".", "/home/vagrant/sync", disabled: true

end



#3 각 폴더에서 vagrant up 명령으로 가상머신을 생성

C:\HashiCorp\swarm-manager> vagrant up

C:\HashiCorp\swarm-worker1> vagrant up

C:\HashiCorp\swarm-worker2> vagrant up

 

------------------------------------------------

Host Name     IP

============= ===============

swarm-manager 192.168.111.100

swarm-worker1 192.168.111.101

swarm-worker2 192.168.111.102

--------------------------------------------------



#4 도커 스웜 모드의 구조

  • 매니저(manager) 노드와 워커(worker) 노드로 구성

  • 워커 노드 ⇒ 실제 컨테이너가 생성되고 관리되는 도커 서버

  • 매니저 노드 ⇒ 워커 노드를 관리하기 위한 도커 서버

  • 매니저 노드는 워커 노드의 역할을 포함

  • 클러스터를 구성하기 위해서는 최소 1개 이상의 매니저 노드가 존재해야 함



#5 #3에서 생성한 가상머신에 SSH로 접속 후 도커 설치

C:\HashiCorp\swarm-manager> vagrant ssh

[vagrant@swarm-manager ~]$ sudo su

[root@swarm-manager vagrant]# cd

[root@swarm-manager ~]# yum install -y docker

[root@swarm-manager ~]# systemctl start docker.service

[root@swarm-manager ~]# docker version

[root@swarm-manager ~]# systemctl stop firewalld

 

C:\HashiCorp\swarm-worker1> vagrant ssh

[vagrant@swarm-worker1 ~]$ sudo su

[root@swarm-worker1 vagrant]# cd

[root@swarm-worker1 ~]# yum install -y docker

[root@swarm-worker1 ~]# systemctl start docker.service

[root@swarm-worker1 ~]# docker version

[root@swarm-worker1 ~]# systemctl stop firewalld

 

C:\HashiCorp\swarm-worker2> vagrant ssh

[vagrant@swarm-worker2 ~]$ sudo su

[root@swarm-worker2 vagrant]# cd

[root@swarm-worker2 ~]# yum install -y docker 

[root@swarm-worker2 ~]# systemctl start docker.service

[root@swarm-worker2 ~]# docker version

[root@swarm-worker2 ~]# systemctl stop firewalld



#6 매니저 역할의 서버에서 스웜 클러스터를 시작

[root@swarm-manager ~]# docker swarm init --advertise-addr 192.168.111.100

                                                              ~~~~~~~~~~~~~~~~~~~~~ ⇒ 매니저 노드의 주소 

Swarm initialized: current node (ym6n02vuulxa9izewh25vdv57) is now a manager.

 

To add a worker to this swarm, run the following command:

 

    docker swarm join \

    --token SWMTKN-1-51gsqhe3wqo7nj7tffuexh2jphwfjffy0a5anzgbx6ljn0m4as-24zl1npz454ep1olarxsddu0o \

    192.168.111.100:2377

    ⇒ 새로운 워커 노드를 클러스터에 추가할 때 사용하는 비밀키(토큰)

 

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.



#7 워커 노드를 추가

[root@swarm-worker1 ~]# docker swarm join \

>     --token SWMTKN-1-51gsqhe3wqo7nj7tffuexh2jphwfjffy0a5anzgbx6ljn0m4as-24zl1npz454ep1olarxsddu0o \

>     192.168.111.100:2377

This node joined a swarm as a worker.

 

[root@swarm-worker2 ~]# docker swarm join \

>     --token SWMTKN-1-51gsqhe3wqo7nj7tffuexh2jphwfjffy0a5anzgbx6ljn0m4as-24zl1npz454ep1olarxsddu0o \

>     192.168.111.100:2377

This node joined a swarm as a worker.



#8 스웜 클러스터에 정상적으로 추가되었는지 확인

[root@swarm-manager ~]# docker node ls

ID                                     HOSTNAME       STATUS  AVAILABILITY  MANAGER STATUS

u0aezhea44cx9z5faipmntbpl    swarm-worker2    Ready   Active

wdnqgalwfd9828npcr516uw2s    swarm-worker1  Ready   Active

ym6n02vuulxa9izewh25vdv57 *  swarm-manager  Ready   Active        Leader



#9 토큰 확인 및 변경 방법

[root@swarm-manager ~]# docker swarm join-token manager

To add a manager to this swarm, run the following command:

 

    docker swarm join \

    --token SWMTKN-1-51gsqhe3wqo7nj7tffuexh2jphwfjffy0a5anzgbx6ljn0m4as-3m4lmy22pfapenpxonqvcpobj \

    192.168.111.100:2377

 

[root@swarm-manager ~]# docker swarm join-token worker

To add a worker to this swarm, run the following command:

 

    docker swarm join \

    --token SWMTKN-1-51gsqhe3wqo7nj7tffuexh2jphwfjffy0a5anzgbx6ljn0m4as-24zl1npz454ep1olarxsddu0o \

    192.168.111.100:2377

 

[root@swarm-manager ~]# docker swarm join-token --rotate manager

Successfully rotated manager join token.

 

To add a manager to this swarm, run the following command:

 

    docker swarm join \

    --token SWMTKN-1-51gsqhe3wqo7nj7tffuexh2jphwfjffy0a5anzgbx6ljn0m4as-2x9uqu2xqgrobck2ho7z10rgh \

    192.168.111.100:2377

 





테스트 환경 구성 방법2 ⇐ 권장

#1 우분투 18.04 를 베이스로 하는 가상머신을 생성하고 도커를 설치

c:\swarm\Vagrantfile 

# -*- mode: ruby -*-

# vi: set ft=ruby :


Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/bionic64"

  config.vm.hostname = "swarm-manager"

  config.vm.network "private_network", ip: "192.168.111.100"

  config.vm.synced_folder ".", "/vagrant_data", disabled: true

end

 

C:\swarm> vagrant up

C:\swarm> vagrant ssh

 

vagrant@swarm-manager:~$ sudo apt update

vagrant@swarm-manager:~$ sudo apt upgrade

 

vagrant@swarm-manager:~$ sudo apt install -y docker.io

vagrant@swarm-manager:~$ sudo usermod -a -G docker $USER

vagrant@swarm-manager:~$ sudo service docker restart

vagrant@swarm-manager:~$ sudo chmod 666 /var/run/docker.sock

vagrant@swarm-manager:~$ docker version

Client:

 Version:           19.03.6

 API version:       1.40

 Go version:        go1.12.17

 Git commit:        369ce74a3c

 Built:             Fri Feb 28 23:45:43 2020

 OS/Arch:           linux/amd64

 Experimental:      false

 

Server:

 Engine:

  Version:          19.03.6

  API version:      1.40 (minimum version 1.12)

  Go version:       go1.12.17

  Git commit:       369ce74a3c

  Built:            Wed Feb 19 01:06:16 2020

  OS/Arch:          linux/amd64

  Experimental:     false

 containerd:

  Version:          1.3.3-0ubuntu1~18.04.2

  GitCommit:

 runc:

  Version:          spec: 1.0.1-dev

  GitCommit:

 docker-init:

  Version:          0.18.0

  GitCommit:

vagrant@swarm-manager:~$ exit

logout

Connection to 127.0.0.1 closed.

 

C:\swarm> vagrant halt

==> default: Attempting graceful shutdown of VM...

 

#2 #1에서 생성한 가상머신으로 스웜 테스트에서 사용할 가상머신을 복제해서 제작

VirtualBox 관리자 > #1번에서 생성한 가상머신을 선택 > 머신 메뉴 > 복제 메뉴 클릭 (3번 반복)

 

이름: swarm-manager, swarm-worker1, swarm-worker2 (각각)

경로: c:\swarm

 

 

#3 가상머신(도커 스웜의 노드로 동작)을 실행 

#3-1 swarm_manager 시작

 

#3-2 swarm_worker1 시작

$ sudo vi /etc/netplan/50-vagrant.yml

IP를 192.168.111.101 으로 변경 후 저장

$ sudo netplan apply 

$ sudo hostnamectl set-hostname swarm-worker1

$ reboot

 

#3-3 swarm_worker2 시작

$ sudo vi /etc/netplan/50-vagrant.yml

IP를 192.168.111.102 으로 변경 후 저장

$ sudo netplan apply 

$ sudo hostnamectl set-hostname swarm-worker2

$ reboot

 

#4 Bitvise SSH Client로 접속할 수 있도록 키를 등록

 

#5 Bitvise 실행 > 주소 변경(swarm-manager, swarm-worker1, swarm-worker2 각각) > SSH 접속 (3번 반복)



#7 매니저 역할의 서버에서 스웜 클러스터를 시작

[root@swarm-manager ~]# docker swarm init --advertise-addr 192.168.111.100

                                                              ~~~~~~~~~~~~~~~~~~~~~ ⇒ 매니저 노드의 주소 

Swarm initialized: current node (ym6n02vuulxa9izewh25vdv57) is now a manager.

 

To add a worker to this swarm, run the following command:

docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-f105esf8p1dvu5cfvkwsb9ukj 192.168.111.100:2377

    ⇒ 새로운 워커 노드를 클러스터에 추가할 때 사용하는 비밀키(토큰)

 

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.



#8 워커 노드를 추가

[root@swarm-worker1 ~]# docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-f105esf8p1dvu5cfvkwsb9ukj 192.168.111.100:2377

This node joined a swarm as a worker.

 

[root@swarm-worker2 ~]# docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-f105esf8p1dvu5cfvkwsb9ukj 192.168.111.100:2377

This node joined a swarm as a worker.



#9 스웜 클러스터에 정상적으로 추가되었는지 확인

[root@swarm-manager ~]# docker node ls

ID                                         HOSTNAME            STATUS     AVAILABILITY    MANAGER STATUS      ENGINE VERSION

wn5j8nymx704prelscdq8fw54 *    swarm-manager       Ready      Active                      Leader                    19.03.6

i2boml3wjv87wjv35mpi0okgt       swarm-worker1       Ready       Active                                                  19.03.6

m110afvl76ppbomnlmh6zzwke     swarm-worker2       Ready       Active                                                  19.03.6



#10 토큰 확인 및 변경 방법

[root@swarm-manager ~]# docker swarm join-token manager

To add a manager to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-5rn4mxiq7va86d04tjqidanjd 192.168.111.100:2377

 

[root@swarm-manager ~]# docker swarm join-token worker

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-f105esf8p1dvu5cfvkwsb9ukj 192.168.111.100:2377

 

[root@swarm-manager ~]# docker swarm join-token --rotate manager

Successfully rotated manager join token.

To add a manager to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-bdgqy50v9bt3reswv7upf87ok 192.168.111.100:2377



#11 워커 노드 삭제

vagrant@swarm-worker2:~$ docker swarm leave

Node left the swarm.

 

vagrant@swarm-manager:~$ docker node ls

ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION

wn5j8nymx704prelscdq8fw54 *   swarm-manager       Ready               Active              Leader              19.03.6

i2boml3wjv87wjv35mpi0okgt     swarm-worker1       Ready               Active                                  19.03.6

m110afvl76ppbomnlmh6zzwke     swarm-worker2       Down                Active                                  19.03.6

 

vagrant@swarm-manager:~$ docker node rm swarm-worker2

swarm-worker2

 

vagrant@swarm-manager:~$ docker node ls

ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION

wn5j8nymx704prelscdq8fw54 *   swarm-manager       Ready               Active              Leader              19.03.6

i2boml3wjv87wjv35mpi0okgt     swarm-worker1       Ready               Active                                  19.03.6



#12 워커 노드를 매니저 노드로 변경

## swarm-manager 노드에서 조인 토큰을 확인

vagrant@swarm-manager:~$ docker swarm join-token worker

To add a worker to this swarm, run the following command:

 

    docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-f105esf8p1dvu5cfvkwsb9ukj 192.168.111.100:2377

 

## swarm-worker2 노드를 클러스터에 워크 노드로 추가

vagrant@swarm-worker2:~$ docker swarm join --token SWMTKN-1-5w9hi0j9ahwgnq78w29pbqvm8sdte7osgl261lf6hte4fatgxp-f105esf8p1dvu5cfvkwsb9ukj 192.168.111.100:2377

This node joined a swarm as a worker.

 

### swarm-manager 노드에서 워크 노드 추가를 확인

vagrant@swarm-manager:~$ docker node ls

ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION

wn5j8nymx704prelscdq8fw54 *   swarm-manager       Ready               Active              Leader              19.03.6

i2boml3wjv87wjv35mpi0okgt     swarm-worker1       Ready               Active                                  19.03.6

8cjqbgqzlf26kszvcyxoy3wgu     swarm-worker2       Ready               Active                                  19.03.6

 

## promote 명령으로 swarm-worker1 노드를 매니저 노드로 승격

vagrant@swarm-manager:~$ docker node promote swarm-worker1

Node swarm-worker1 promoted to a manager in the swarm.

vagrant@swarm-manager:~$ docker node ls

ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION

wn5j8nymx704prelscdq8fw54 *   swarm-manager       Ready               Active              Leader              19.03.6

i2boml3wjv87wjv35mpi0okgt     swarm-worker1       Ready               Active              Reachable           19.03.6

8cjqbgqzlf26kszvcyxoy3wgu     swarm-worker2       Ready               Active                                  19.03.6

 

#13 demote 명령으로 매너저 노드를 워커 노드로 변경

vagrant@swarm-manager:~$ docker node demote swarm-worker1

Manager swarm-worker1 demoted in the swarm.

 

vagrant@swarm-manager:~$ docker node ls

ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION

wn5j8nymx704prelscdq8fw54 *   swarm-manager       Ready               Active              Leader              19.03.6

i2boml3wjv87wjv35mpi0okgt     swarm-worker1       Ready               Active                                  19.03.6

8cjqbgqzlf26kszvcyxoy3wgu     swarm-worker2       Ready               Active                                  19.03.6