0915(목) - 도커5

Yuri JI·2022년 9월 15일
0

Kakao Cloud School

목록 보기
10/27
  • docker swarm, overlay
    Swarm: inactive -> kubernetes와 같은 orchestration 기능

📔 docker swarm

💭 언제쓰는지 찾기 ?

  • docker network create

switch -> 로드밸런싱 한다.
server 3개 묶여있는 애들 = target group
switch는 server3대를 라운드로빈 대상으로 여긴다.

📔 network card? app card? 붙이기

  • endpoint는 컨테이너 안에 샌드박스 안에 위치한다.

connect / disconnect rm 에러메세지도 확인하기.

yji@hostos1:~$ docker run -it --name=add-net ubuntu:14.04 bash
root@8c490ff5427a:/# ifconfig
⭐eth0⭐      Link encap:Ethernet  HWaddr 02:42:ac:11:00:03
          ⭐inet addr:172.17.0.3⭐  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:9 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:929 (929.0 B)  TX bytes:0 (0.0 B)

# 다른 터미널에서
yji@hostos1:~$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED          STATUS          PORTS                                       NAMES
8c490ff5427a   ubuntu:14.04             "bash"                   38 seconds ago   Up 35 seconds                                               add-net

yji@hostos1:~$ docker network create --driver=bridge web-network
1f867ca19cb12df06a943b9e1165a07db57b6aa55535347e3494e1f0d13abe67

yji@hostos1:~$ docker network ls
NETWORK ID     NAME           DRIVER    SCOPE
1f867ca19cb1   web-network    bridge    local

ifconfig
# ifconfig = ip addr show = ip a = route
yji@hostos1:~$ ifconfig
br-b38113e7f7f2: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.19.0.1  netmask 255.255.0.0  broadcast 172.19.255.255
        ether 02:42:5f:b0:f4:a9  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        
📕 컨테이너에 네트워크 추가 = ep가 하나 더 생긴다.
yji@hostos1:~$ docker network connect web-network add-net
yji@hostos1:~$ docekr exec add-net route

Command 'docekr' not found, did you mean:

  command 'docker' from snap docker (20.10.14)
  command 'docker' from deb docker.io (20.10.12-0ubuntu2~20.04.1)

See 'snap info <snapname>' for additional versions.

# 📕 컨테이너에 네트워크 추가 후 조회 
# ⭐ 
yji@hostos1:~$ docker exec add-net route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.0.1      0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0
172.21.0.0      *               255.255.0.0     U     0      0        0 eth1
yji@hostos1:~$ ifconfig
br-b38113e7f7f2: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.19.0.1  netmask 255.255.0.0  broadcast 172.19.255.255
        ether 02:42:5f:b0:f4:a9  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0


yji@hostos1:~$ docker network inspect web-network
[
    {
        "Name": "web-network",
        "Id": "1f867ca19cb12df06a943b9e1165a07db57b6aa55535347e3494e1f0d13abe67",
        "Created": "2022-09-15T09:19:20.869086986+09:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.21.0.0/16",
                    "Gateway": "172.21.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "8c490ff5427a81c3d778391efe0ddf4f146995e220ded45eda9d3eec1f2151c5": {
                "Name": "add-net",
                "EndpointID": "aece16dd352e29f0e389295c68c72dfdb83f77f6a74c9d3de36445f743d771d9",
                "MacAddress": "02:42:ac:15:00:02",
                "IPv4Address": "172.21.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]


yji@hostos1:~$ docker network rm web-network
Error response from daemon: error while removing network: network web-network id 1f867ca19cb12df06a943b9e1165a07db57b6aa55535347e3494e1f0d13abe67 ⭐has active endpoints⭐

# 세션이 있는 경우는 disconnect 안됨
# + docker stop add-net이랑 같은 명령어임 
yji@hostos1:~$ docker network disconnect web-network add-net
yji@hostos1:~$

# 도커 네트워크 삭제하기 
yji@hostos1:~$ docker network rm web-network
web-network
yji@hostos1:~$ docker network ls
NETWORK ID     NAME           DRIVER    SCOPE
d846ee1f1175   apache-net     bridge    local
b38113e7f7f2   app-service    bridge    local
b5193b9d3ac2   bridge         bridge    local
cd1e0d6188a3   host           host      local
fad17e6f022b   netlb          bridge    local
6e2bc71954be   none           null      local
d79507ea5285   vswithch-net   bridge    local
43bba2c1decb   web-net        bridge    local

ep 만들기 ...

1. 네트워크 추가 
yji@hostos1:~$ docker network create back-net
a5cc8db1f23d225af766e38e21702a362f61f0a0392c0e5cbf95e15c0f94339b

yji@hostos1:~$ docker network create front-net
48f13761d08b0672e2f9510e2a22894d20212a59ceab7f841a9d00e6c02940a8

yji@hostos1:~$ docker network ls
NETWORK ID     NAME        DRIVER    SCOPE
a5cc8db1f23d   back-net    bridge    local
b5193b9d3ac2   bridge      bridge    local
48f13761d08b   front-net   bridge    local
cd1e0d6188a3   host        host      local
6e2bc71954be   none        null      local


2. 컨테이너 2개 생성
yji@hostos1:~$ docker run -itd --name=conA ubuntu:14.04 bash
e2d9933d89ef457ccf097ebc1c80cf0f558c543e9013f9016c3aa55193e21957

yji@hostos1:~$ docker run -itd --name=conB ubuntu:14.04 bash
6fac35f2f38521d111e67479232eec5f3ff75551494c8e84c97b1752422a32ea

3. 컨테이너에 네트워크 추가 
yji@hostos1:~$ docker network connect back-net conA
yji@hostos1:~$ docker network connect back-net conB
yji@hostos1:~$ docker network connect front-net conB

4. 네트워크의 ip 확인 
yji@hostos1:~$ docker network inspect back-net | grep IPv4
                "IPv4Address": "172.22.0.3/16",
                "IPv4Address": "172.22.0.2/16",
yji@hostos1:~$ docker network inspect front-net | grep IPv4
                "IPv4Address": "172.23.0.2/16",


5. 컨테이너 확인  
# conA에는 back-net(172.22.0.0) 이 붙고 
# conB에는 back-net과 front-net(172.23.0.0)이 붙은 것을 확인할 수 있다. 
yji@hostos1:~$ docker exec conA route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.22.0.1      0.0.0.0         UG    0      0        0 eth1
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0
172.22.0.0      *               255.255.0.0     U     0      0        0 eth1

yji@hostos1:~$ docker exec conB route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.22.0.1      0.0.0.0         UG    0      0        0 eth1
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0
172.22.0.0      *               255.255.0.0     U     0      0        0 eth1
172.23.0.0      *               255.255.0.0     U     0      0        0 eth2

6. 네트워크 해제
yji@hostos1:~$ docker network disconnect back-net conA
yji@hostos1:~$ docker network disconnect back-net conB
yji@hostos1:~$ docker network disconnect front-net conB

7. 네트워크 해제 확인
yji@hostos1:~$ docker exec conA route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.0.1      0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0

yji@hostos1:~$ docker exec conB route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.0.1      0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0

8. 네트워크 삭제 
yji@hostos1:~$ docker network rm back-net
back-net
yji@hostos1:~$ docker network rm front-net
front-net

9. 네트워크 삭제 확인
yji@hostos1:~$ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
b5193b9d3ac2   bridge    bridge    local
cd1e0d6188a3   host      host      local
6e2bc71954be   none      null      local

자원소비제어

: 컨테이너에 자원 할당 -> cgroup -> (기본값) unlimit
: 제한 구성
// 요기 메모장 보고 적기
1) cpu -> cpu register에 작업 등록 -> time scheduling ->

  • count
    yji@hostos1:~$ grep -c processor /proc/cpuinfo
    1
    htop
  • time scheduling
    cpu를 사용할 수 있는 시간을 제한할 수 있음.
  yji@hostos1:~$ sudo apt -y install stress
  stress -c 1 -t 10s // 10초동안 cpu1개에 과부하 주기
  
* stress 테스트 중 

* stress 테스트 끝 

  • 비율(rate %)로 제한할 수도 있음

2) memory -> physical memory 와 swap 메모리가 있다. -> 4M (메모리 할당단위 page=4K) -> 메모리 사용량 제한 가능
3) disk -> 성능지표? ⭐IOPS / MBPS⭐ -> 특정 컨테이너의 disk 사용량 제한 가능 (I/O 너무 많이 일으키는거 제한 가능)

yji@hostos1:~$ sudo apt install sysstat # iostat 을 사용하기 위해 설치해주세요.
yji@hostos1:~$ iostat 2 2 # 2초마다 2번 찍어라
⭐ 뜻 찾기 
⭐kB_read/s    kB_wrtn/s    kB_dscd/s    kB_read    kB_wrtn  

초당 처리하는 IOPS를 높여줘야 트랜잭션 자체를 정상적으로 처리할 수 있다.

📔 cpu time scheduling 실습

yji@hostos1:~$ docker pull leecloudo/stress:1.0



yji@hostos1:~$ docker run -d --name=cpu_1024 --cpu-shares 1024 leecloudo/stress:1.0 stress -c 4
cce8bf72fcc8724d04a3353ec4b393b96160d53a5fbb01cf99fbace9591562d3

# 512는 1024보다 절반 이하의 시간만 먹는다. 
yji@hostos1:~$ docker run -d --name=cpu_512 --cpu-shares 512 leecloudo/stress:1.0 stress -c 4

# 확인
yji@hostos1:~$ ps -auxf | grep stress
yji         2889  0.0  0.0  10344   712 pts/0    S+   11:23   0:00  |                                                                                                                         \_ grep --color=auto stress
root        2711  0.1  0.0   7488   824 ?        Ss   11:22   0:00  \_ stress -c                                                                                                               4
root        2745 75.7  0.0   7488    92 ?        R    11:22   0:40      \_ stres                                                                                                              s -c 4
root        2746 78.2  0.0   7488    92 ?        R    11:22   0:41      \_ stres                                                                                                              s -c 4
root        2747 76.4  0.0   7488    92 ?        R    11:22   0:40      \_ stres                                                                                                              s -c 4
root        2748 79.7  0.0   7488    92 ?        R    11:22   0:42      \_ stres                                                                                                              s -c 4
root        2832  0.1  0.0   7488   940 ?        Ss   11:23   0:00  \_ stress -c                                                                                                               4
root        2864 39.1  0.0   7488    96 ?        R    11:23   0:10      \_ stres                                                                                                              s -c 4
root        2865 25.6  0.0   7488    96 ?        R    11:23   0:06      \_ stres                                                                                                              s -c 4
root        2866 34.4  0.0   7488    96 ?        R    11:23   0:08      \_ stres                                                                                                              s -c 4
root        2867 43.0  0.0   7488    96 ?        R    11:23   0:11      \_ stres  


# 끄자
docker stop cpu_1024 cpu_512

📔 cpu 제한 실습 2

# 실습 1
# 너 cpu 2번 써 `--cpuset-cpus 2`
# 0,1,2,3 이니까 ->3번 cpu가 튄다.
yji@hostos1:~$ docker run -d --name=cpuset1 --cpuset-cpus 2 leecloudo/stress:1.0 stress --cpu 1

# 실습 2
# 0, 3 => 1번, 4번 cpu 써라. --cpu 2 => cpu 2개
yji@hostos1:~$ docker run -d --name=cpuset2 --cpuset-cpus 0,3 leecloudo/stress:1.0 stress --cpu 2

# 실습 3
# cpu 3번 써라.
yji@hostos1:~$ docker run -d --name=cpuset1 --cpuset-cpus 2 leecloudo/stress:1.0 stress --cpu 1
797367b4206a0d86145e847e7a94f52f34b36a56f113f397c11b527ac2426416
# 근데 이제 0.2 = 20퍼센트만 써라 .
yji@hostos1:~$ docker update --cpus=0.2 cpuset1
cpuset1

# 실습 4
yji@hostos1:~$ docker run -d --name=cpuset2 --cpuset-cpus 0,3 leecloudo/stress:1.0 stress --cpu 2
c59ba068a14ece766282418807ec22bd93e1d7e687a2ffabf89e5da68a530950

## 20퍼센트 걸어줄건데 각각 20퍼일까 합쳐서 20퍼일까 => 합쳐서 20퍼센트다 ~~~ 각각이 20아님 .
yji@hostos1:~$ docker update --cpus=0.2 cpuset2

📔 Memory 제한 실습


# 200m으로 제한 
yji@hostos1:~$ docker run -d --name nginx200m --memory=200m nginx:1.23.1-alpine
c4d29ecbab6b0c168958b67869ba5df28fa6fe01cd7073788d8d3d0d6a2a390c

# 1024로 한번 나누면 KB, 1024로 두번 나누면 MB
yji@hostos1:~$ docker inspect nginx200m | grep -i memory
            "Memory": ⭐209715200, == 200MB⭐
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "Memory✍Swap": ✍419430400,
            "MemorySwappiness": null,

# 계산기
yji@hostos1:~$ ✍ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
✍ 209715200/1024/1024
✍ 200
✍ quit


## 실습 2 swap 메모리도 제한 
yji@hostos1:~$ docker run -d --name nginx200ms --memory=200m --memory-swap=200m nginx:1.23.1-alpine
d2ec7d7594902695a87f36732b4622c50c86ac2500b78f3e47cced18f0122f1b
yji@hostos1:~$ docker inspect nginx200ms | grep -i memory
            "Memory": 209715200,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 209715200,
            "MemorySwappiness": null,


## 실습 3.
yji@hostos1:~$ docker run -itd -m=4m --name=mydb mysql:5.7-debian
docker: Error response from daemon: Minimum memory limit allowed is 6MB.⭐ 야 ~ 6MB는 부족해. 최소 6MB ㄱㄱ 

# 돌아는 가지만 부족하다 ! 앱 구동시 최소 200MB는 필요함.
yji@hostos1:~$ docker run -itd -m=6m --name=mydb mysql:5.7-debian
0b8934e1b383834c82232559c82099cf076509dd9209bf44a2214af33f49f560

📔 disk 제한 실습

dd : 임시 device 만들 때 쓴다.
loop = 임시 디바이스, 컨테이너가 사용하는 임시 디바이스..~

if= input file, of = output file
bs = blcok size
count = 10MB ??????

/dev/sda:1mb ...

원래속도 확인하고.
디스크 제한(1mb, 10mb) 한다음에 또 속도 확인

# 원래 속도
yji@hostos1:~$ docker run -it --rm ubuntu:14.04 bash
root@2e805b1cfafc:/# dd if=/dev/zero of=test.out bs=1M count=10 oflag=direct
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.0164318 s, 638 MB/s


# /dev/sdb : 도커가 있는 위치 
yji@hostos1:~$ docker run -it --rm --device-write-bps /dev/sdb:1mb ubuntu:14.04 bash

root@a41712ece538:/# dd if=/dev/zero of=test.out bs=1M count=10 oflag=direct
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 10.2135 s, 1.0 MB/s


yji@hostos1:~$ docker run -it --rm --device-write-bps /dev/sdb:10mb ubuntu:14.04 bash

root@3d3410e57551:/# dd if=/dev/zero of=test.out bs=1M count=10 oflag=direct
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 1.01382 s, 10.3 MB/s

volumes 실습

  • 볼륨 = 공유

yji@hostos1:~$ cd LABs/
yji@hostos1:~/LABs$ mkdir hello1 hello2
yji@hostos1:~/LABs$ cd hello1
yji@hostos1:~/LABs/hello1$ cat > test1.txt
test1yji@hostos1:~/LABs/hello1$ cd ..
yji@hostos1:~/LABs$ cat > hello2/text2.txt
test2yji@hostos1:~/LABs$


yji@hostos1:~/LABs$ docker run -it --name ubuntu_volume1 -v /home/yji/LABs/hello1:/hello1 -v /home/yji/LABs/hello2:/hello2 ubuntu:14.04 bash
root@715bfbf098c7:/# ls
bin   dev  ⭐hello1  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  ⭐hello2  lib   media  opt  root  sbin  sys  usr
root@715bfbf098c7:/# ls hello1
test1.txt
root@715bfbf098c7:/# ls hello2
text2.txt


# 컨테이너 안
hello1 폴더에서 
mount
df -ha
한다음에 !! 
root@715bfbf098c7:/hello1# echo "HIHI" >> test.txt
root@715bfbf098c7:/hello1# cat test.txt
HIHI
root@715bfbf098c7:/h
yji@hostos1:~/LABs$
yji@hostos1:~/LABs$ cat test.txt
cat: test.txt: No such file or directory
yji@hostos1:~/LABs$ cd hello1
yji@hostos1:~/LABs/hello1$ cat test.txt
HIHI
yji@hostos1:~/LABs/hello1$ docker inspect --format="{{ .HostConfig.Binds }}" ubuntu_volume1
[/home/yji/LABs/hello1:/hello1 /home/yji/LABs/hello2:/hello2]



## 실습 2 Read-only, Read-Write 권한부여 

yji@hostos1:~/LABs$ docker run -it --name ubuntu_volume1 -v /home/yji/LABs/hello1:/hello1:ro -v /home/yji/LABs/hello2:/hello2:rw ubuntu:14.04 bash




root@71a9b9452aa1:/hello1# echo "lab02 readonly" >> test_ro.txt
bash: test_ro.txt: Read-only file system

# 터미널 나와서 
yji@hostos1:~/LABs$ ls hello1
test1.txt  test.txt
yji@hostos1:~/LABs$ ls hello2
test_rw.txt  text2.txt

docker run -it --name ubuntu_volume1 -v /home/yji/LABs/hello1:/hello1⭐:ro⭐ -v /home/yji/LABs/hello2:/hello2⭐:rw⭐ ubuntu:14.04 bash

📔 DB 관리

  • Master - Standby : 일반적

    • role 롤 종류
      • Active-Active : 동시 쓰기 가능, 더 빠르다🤔🤔🤔
      • Active-Standby :쓰기는 active에만, 장애발생시 standy를 active로 role을 바꿈. (Role 전환, Role-switching)
  • Backup

  • Migration(이전작업) : DB 쓰다보면 서버가 노후화되서 서버가 교체될 수 있음 or DB 업데이트 필요한 경우

    • *.idb를 옮겨야 한다. ! (*.idb는 데이터를 저장한 파일)
    • idb 파일은 용량이 매우 크다.. 대충 100GB 정도면 100분... 1TB(1000GB) = 16시간.
    • copy 중에 데이터 오류나면? rollabck 해야돼
    • 이런 작업을 volume을 통해 획기적으로 할 수 있음 !!!
    • docker volume으로 쉽게 구현 가능 !

    mysql의 가장 중요한 폴더 = /var/lib/mysql
    볼륨은 해당 컨테이너의 주요 소수, 구성 경로에 배치한다.
    application의 주요 소스 경로를 -v 붙인다 ~
    e.g. apache의 경우 -v 를 /var/www/html
    e.g. nginx의 경우 -v를 /etc/nginx or /usr/share/nginx/html
    /var/log/nginx -> (여기엔 access log, error log가 저장)
    그니까. nginx 컨테이너를 사용할거면 여기에 해당하는 볼륨 세개는 걸어주자.

    mysql 컨테이너 생성 및 접속 ! !

# mydb를 root 소유로 만든다. 
yji@hostos1:~$ docker run -itd --name mydb-vol1 -e MYSQL_ROOT_PASSWORD=pass123# -e MYSQL_DATABASE=kakaodb -v /home/yji/mydb:/var/lib/mysql mysql:5.7-debian 

# 컨테이너 접속 
docker exec -it mydb-vol1 bash
mysql -u root -p

# kakaodb (sample data) 생성하기
root@e81e9b50c384:/# cd /var/lib/mysql/kakaodb
root@e81e9b50c384:/var/lib/mysql/kakaodb# ls
db.opt  kakao_prod.frm  kakao_prod.ibd

mysql> use kakaodb;
Database changed

mysql> create table kakao_prod (prod_name varchar(20), prod_item varchar(50));
Query OK, 0 rows affected (0.04 sec)

mysql> insert into kakao_prod values('emoticon', 'muji');
Query OK, 1 row affected (0.03 sec)

mysql> select * from kakao_prod;
+-----------+-----------+
| prod_name | prod_item |
+-----------+-----------+
| emoticon  | muji      |
+-----------+-----------+
1 row in set (0.01 sec)

mysql> exit;
Bye

# 다른 터미널
yji@hostos1:~$ cd mydb/
yji@hostos1:~/mydb$ sudo ls -l kakaodb/
-rw-r----- 1 systemd-coredump systemd-coredump 114688  915 14:08 kakao_prod.ibd

yji@hostos1:~/mydb$ docker stop mydb-vol1
cexmydb-vol1

yji@hostos1:~/mydb$ cexrm
e81e9b50c384

Q. mysql:5.7-debian -> stop/rm -> mysql:8.0 = ? databse 살아있는지 확인하기 : 살아있다.

yji@hostos1:~/mydb$ docker run -itd --name mydb-vol1 -e MYSQL_ROOT_PASSWORD=pass123# -e MYSQL_DATABASE=kakaodb -v /home/yji/mydb:/var/lib/mysql mysql:8.0

yji@hostos1:~/mydb$ docker exec -it mydb-vol1 bash
bash-4.4# mysql -u root -p

mysql> use kakaodb;
Database changed

mysql> select * from kakao_prod;
+-----------+-----------+
| prod_name | prod_item |
+-----------+-----------+
| emoticon  | muji      |
+-----------+-----------+
1 row in set (0.00 sec)

Q. mysql:5.7-debian -> stop/rm -> mariadb:10.2 = ? databse 살아있는지 확인하기 > 🤔 kakaodb없음 !

아키텍쳐가 다르기 때문에 같은 계열일지라도 데이터가 없다~

⭐ 이런 형태의 작업을 데이터 영속성, 데이터 지속성 유지를 위한 볼륨 구성 이라고 한다.

# mariaDB 컨테이너 생성 
yji@hostos1:~$ docker run -d -e MARIADB_ROOT_PASSWORD=1234 -e MARIADB_DATABASE=item --name=itemdb -p 13306:3306 mariadb:10.2

# mariaDB 컨테이너 접속 
yji@hostos1:~$ docker exec -it itemdb bash

root@2de81beaea7f:/# mysql -u root -p

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| item               |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)

📔 로그

💭 서버에 장애가 발생했다. 제일 먼저 해야할 일은 ?
1. 로그를 봐라 > 로그를 모니터링 할 수 있는 서버를 둬라.

Web Application은 Auto Scaling 그룹의 Amazon Ec2 인스턴스에서 실행됩니다.
장애로 인해 인스턴스가 종료되면 ,종료된 인스턴스에 있는 로그는 손실되므로 Systems Operations 팀은 문제의 원인을 확인할 수 없습니다. 근본 원인을 어떻게 확인할 수 있을까요?

sol)
Amazon CloudWatch 에이전트를 Web Application에 적용하여 로그를 Amazon CloudWatch Logs로 push한다. or SQS ( Amazon Simple Queue Service 서비스 활용)

nginx에는 /var/log/nginx/access.log | error.log 파일이 있다 ~ ! ==> 볼륨 걸자.

# 웹 서비스 Nginx 로그 경로를 볼륨으로 호스트와 bind mount 수행
yji@hostos1:~$ mkdir -p /home/yji/nginx-log

# directory를 생성하지 않고 볼륨에 의해 자동으로 생성되면 소유권이 root로 됨
yji@hostos1:~$ docker run -d -v /home/yji/nginx-log:/var/log/nginx -p 8011:80 nginx:1.21
e0dd0f88ca314a62ff157e531436f436387f52ae81de8d70a4c556892a01bb4f

# 호스트에서 웹 서비스 로그 확인
yji@hostos1:~$ cd nginx-log/
yji@hostos1:~/nginx-log$ ls
access.log  error.log

# 192.168.56.101:8011에 접속한 뒤 새로고침하면 계속 로그가 남는 걸 볼 수 있음
yji@hostos1:~/nginx-log$ tail -f access.log

# 웹 서비스 로그 분석: 지정 범위 내의 로그시간($4) 동안 [IP 중복건수, IP내림차순 출력]
yji@hostos1:~/nginx-log$ awk '$4>"[$(date)]" && $4<"[$(date)]"' access.log | awk '{ print $1 }' | sort | uniq -c | sort -r | more


awk '$4>"[15/Sep/2022:05:30:23]" && $4<"[15/Sep/2022:15:36:30]"' access.log | awk '{ print $1 }' | sort |uniq -c | sort -r | more

yji@hostos1:~/nginx-log$ awk '$4>"[15/Sep/2022:05:30:23]" && $4<"[15/Sep/2022:15:36:30]"' access.log | awk '{ print $1 }' | sort |uniq -c | sort -r | more
      6 192.168.56.1
     28 192.168.56.102

📔 mount

directory to directory 뿐만 아니라,
file to file도 가능하다.

yji@hostos1:~$ docker run -it -v /home/yji/.bash_history:/root/.bash_history --rm centos:7 bash
[root@e16af84b638b /]# cd
[root@e16af84b638b ~]# ls -al
total 40
dr-xr-x--- 1 root root    27 Sep 15 05:37 .
drwxr-xr-x 1 root root    18 Sep 15 05:37 ..
-rw------- 1 1000 1000 13074 Sep 15 05:37 .bash_history
-rw-r--r-- 1 root root    18 Dec 29  2013 .bash_logout
-rw-r--r-- 1 root root   176 Dec 29  2013 .bash_profile
-rw-r--r-- 1 root root   176 Dec 29  2013 .bashrc
-rw-r--r-- 1 root root   100 Dec 29  2013 .cshrc
-rw-r--r-- 1 root root   129 Dec 29  2013 .tcshrc
-rw------- 1 root root  3416 Nov 13  2020 anaconda-ks.cfg
[root@e16af84b638b ~]# echo 'docker file volume test' > file_volume.txt
[root@e16af84b638b ~]# ls
anaconda-ks.cfg  file_volume.txt
[root@e16af84b638b ~]# cat file_volume.txt
docker file volume test
[root@e16af84b638b ~]# exit
exit


# cat .bash_history 하면 컨테이너 안에서 작성했던 명령어들이 기록된다. 근데 컨테이너 exit 하고나서야 기록됨 ! 바로바로 기록되는건 아님.
== 즉, mount는 file도 자동으로 mount 되는구나 ~ ~

cd
ls -al
echo 'docker file volume test' > file_volume.txt
ls
cat file_volume.txt
exit

📔 로컬과 컨테이너 시간 동기화

-v /etc/localtime:/etc/localtime 사용해서 시간도 동기화 할 수 있다.

yji@hostos1:~$ date
2022. 09. 15. () 14:41:50 KST
yji@hostos1:~$ docker run -it --rm -v /etc/localtime:/etc/localtime centos:7 bash
[root@ecc3e2f563ca /]# date
Thu Sep 15 14:42:29 KST 2022

📔 container root FS quota(할당량) 제한

# host os 
df -h
/dev/sdb1       1⭐00G  8.7G   92G   9% /var/lib/docker

# ubuntu container
yji@hostos1:~$ docker run -it -v /home/yji/webapp --name=webapp ubuntu:14.04 bash
root@3c97faddadc2:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay         ⭐100G  8.7G   92G   9% /
/dev/sdb1       ⭐100G  8.7G   92G   9% /etc/hosts

🤔 컨테이너 하나가 host OS의 100GB를 다 먹을 수도 있겠구나 !
-> 🐳 제한하자 


# 실습 1. /var/lib/docker 가 컨테이너의 / 영역 
컨테이너에 1GB만 주고 싶다.

yji@hostos1:~$ docker run -it -v /home/yji/webapp --rm --name=webapp --storage-opt size=1G ubuntu:14.04 bash
docker: Error response from daemon: --storage-opt is supported only for overlay over xfs with 'pquota' mount option.
: pquota 옵션이 같이 있어야한다. 

cat /etc/fstab.. 여기에 pquota 추가?

# /etc/default/grub    uquota, pquota 추가  오타 주의 ~~~~ 제발~~~~~




bind mount 기법

yji@hostos2:~$ docker run -v /home/yji/myvolume:/webapp -it --name webapp ubuntu:14.04 bash

root@2ff783988f04:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay         100G  1.6G   99G   2% /
/dev/sda1        73G  7.9G   62G  12% /webapp
/dev/sdb1       100G  1.6G   99G   2% /etc/hosts



# OS level에서 용량을 제한한 image 생성 후 연결할 directory에 mount -> volume으로 지정 
# 512MB로 image 생성 
root@hostos2:~# dd if=/dev/zero of=temphdd.img count=512 bs=1M
512+0 records in
512+0 records out
536870912 bytes (537 MB, 512 MiB) copied, 1.31411 s, 409 MB/s
root@hostos2:~# mkfs.ext4 temphdd.img
mke2fs 1.45.5 (07-Jan-2020)
Discarding device blocks: done
Creating filesystem with 131072 4k blocks and 32768 inodes
Filesystem UUID: 8a00cfbd-77db-4c6d-994e-23db343fccef
Superblock backups stored on blocks:
        32768, 98304

Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done

root@hostos2:~# fdisk -l temphdd.img
Disk temphdd.img: 512 MiB, 536870912 bytes, 1048576 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
root@hostos2:~# mkdir -p /home/yji/myvolume
root@hostos2:~# mount -o loop temphdd.img /home/yji/myvolume/
root@hostos2:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           393M  1.8M  391M   1% /run
/dev/sda1        73G  8.0G   62G  12% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
/dev/loop0       62M   62M     0 100% /snap/core20/1611
/dev/loop2      249M  249M     0 100% /snap/gnome-3-38-2004/99
/dev/loop3       47M   47M     0 100% /snap/snapd/16292
/dev/loop1      347M  347M     0 100% /snap/gnome-3-38-2004/115
/dev/loop7      128K  128K     0 100% /snap/bare/5
/dev/loop4       92M   92M     0 100% /snap/gtk-common-themes/1535
/dev/loop6       46M   46M     0 100% /snap/snap-store/592
/dev/loop8       55M   55M     0 100% /snap/snap-store/558
/dev/loop5       66M   66M     0 100% /snap/gtk-common-themes/1519
/dev/loop9       48M   48M     0 100% /snap/snapd/16778
/dev/loop10      64M   64M     0 100% /snap/core20/1623
/dev/sda5       9.1G   24K  8.6G   1% /BACKUP
/dev/sdb1       100G  1.6G   99G   2% /var/lib/docker
tmpfs           393M   20K  393M   1% /run/user/125
tmpfs           393M   32K  393M   1% /run/user/1000
overlay         100G  1.6G   99G   2% /var/lib/docker/overlay2/c5119246d933066306ebf450f4c8ecaff38ca1e7f535be74cc224827d4180b17/merged
/dev/loop11     488M   24K  452M   1% /home/yji/myvolume
root@hostos2:~# chown -R yji.yji /home/yji/myvolume
root@hostos2:~# exit
exit

# 설정 이후 다시 mount
~$ docker run -v /home/yji/myvolume:/webapp -it --name=vquota ubuntu:14.04 bash

yji@hostos2:~$ docker run -v /home/yji/myvolume:/webapp -it --name=vquota ubuntu:14.04 bash
root@d3d2acbcd6f0:/#
root@d3d2acbcd6f0:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay         100G  1.6G   99G   2% /
tmpfs            64M     0   64M   0% /dev
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
shm              64M     0   64M   0% /dev/shm
/dev/loop11     488M   24K  452M   1% /webapp
/dev/sdb1       100G  1.6G   99G   2% /etc/hosts

volume 생성


yji@hostos2:~$ docker volume create my-db-volume
my-db-volume
yji@hostos2:~$ docker volume ls
DRIVER    VOLUME NAME
local     my-db-volume
yji@hostos2:~$ docker run -d --name mydb -e MYSQL_ROOT_PASSWORD=1234 -e MYSQL_DATABASE=wp -v my-db-volume:/var/lib/mysql mysql:5.7

yji@hostos2:~$ sudo ls /var/lib/docker/volumes/my-db-volume/_data
auto.cnf         ib_buffer_pool  mysql               server-cert.pem
ca-key.pem       ibdata1         mysql.sock          server-key.pem
ca.pem           ib_logfile0     performance_schema  sys
client-cert.pem  ib_logfile1     private_key.pem     wp
client-key.pem   ibtmp1          public_key.pem

# 볼륨 조회
yji@hostos2:~$ docker inspect --type volume my-db-volume
[
    {
        "CreatedAt": "2022-09-15T15:40:00+09:00",
        "Driver": "local",
        "Labels": {},
        "Mountpoint":"/var/lib/docker/volumes/my-db-volume/_data"⭐,
        "Name": "my-db-volume",
        "Options": {},
        "Scope": "local"
    }
]

yji@hostos2:~$ docker volume inspect my-db-volume
[
    {
        "CreatedAt": "2022-09-15T15:40:00+09:00",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/my-db-volume/_data",
        "Name": "my-db-volume",
        "Options": {},
        "Scope": "local"
    }
]

# 볼륨 삭제 
yji@hostos2:~$ docker stop mydb
mydb
yji@hostos2:~$ cexrm
93dcd8b73fbd
yji@hostos2:~$ docker volume rm my-db-volume
my-db-volume


yji@hostos2:~$ docker volume --help

Usage:  docker volume COMMAND

Manage volumes

Commands:
  create      Create a volume
  inspect     Display detailed information on one or more volumes
  ls          List volumes
  prune       Remove all unused local volumes
  rm          Remove one or more volumes

application과 database가 결합된 Container 결합 환경 구성

-> 🐳 docker의 철학 : 1 Container = 1 Application

  • --link 옵션 또는 docker network를 이용하여 container 연결.

docker command 배우는 이유 = docker compose.

📔 컨테이너를 활용한 2 Tier 모델

  • wordpress에 글 남기면 mysql 서버에 바로 저장된다 !
# mysql container
yji@hostos1:~$ docker network create myapp-net
1a639f77530ddd501ba4c131437cf02274de05df2129d83d50807e9a2365b542

yji@hostos1:~$ docker volume create mydb_data
mydb_data

yji@hostos1:~$ docker run -itd \
--name=mysql_app \
-v mydb_data:/var/lib/mysql \
--restart=always -p 3306:3306 \
--net=myapp-net \
-e MYSQL_ROOT_PASSWORD=password# \
-e MYSQL_DATABASE=wpdb \
-e MYSQL_USER=wpuser \
-e MYSQL_PASSWORD=wppassword \
mysql:8.0

docker run -itd --name=mysql_app -v mydb_data:/var/lib/mysql --restart=always -p 3306:3306 --net=myapp-net -e MYSQL_ROOT_PASSWORD=password# -e MYSQL_DATABASE=wpdb -e MYSQL_USER=wpuser -e MYSQL_PASSWORD=wppassword mysql:8.0


7f30c76b680f55d206a621ec056e03f7c2805cb0f2b92fd08f63c54300b6ef71

# wordpress container
yji@hostos1:~$ docker volume create myweb_data
myweb_data
yji@hostos1:~$ docker run -itd \
> --name=wordpress_app \
> -v myweb_data:/var/www/html \
> -v ${PWD}/myweb-log:/var/log \
> --restart=always \
> -p 8888:80 \
> --net=myapp-net \
> -e WORDPRESS_DB_HOST=mysql_app:3306 \
> -e WORDPRESS_DB_NAME=wpdb \
> -e WORDPRESS_DB_USER=wpuser \
> -e WORDPRESS_DB_PASSWORD=wppassword \
> --link mysql_app:mysql \
> wordpress


yji@hostos1:~$ docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED              STATUS              PORTS                                                  NAMES
223fc13b8a39   wordpress   "docker-entrypoint.s…"   About a minute ago   Up About a minute   0.0.0.0:8888->80/tcp, :::8888->80/tcp                  wordpress_app
7f30c76b680f   mysql:8.0   "docker-entrypoint.s…"   6 minutes ago        Up 5 minutes        0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql_app



docker exec -it mysql_app bash
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| wpdb               |
+--------------------+



# wordpress에 글 남기면 
# mysql 서버에 바로 저장된다 ! 
 jiji           | lee989898@naver.com  | http://34:21 | KUKU KAKA    

3 Tier 모델

mongo db
user guestbook
show tables
db.messages.find() // find = select

--restart 왜 자꾸 쓰는지 : 우리 이거 서비스 제공하는거라 죽으면 재시작 해줘야함

1. 네트워크 만들기 
yji@hostos1:~$ docker network create devapp-net

2. mongodb container 생성 
yji@hostos1:~$ docker run -d \
> --name=mongodb \
> -p 17017:27017 \
> --restart=always \
> --network=devapp-net \
> mongo:4

3. backend container 생성 
yji@hostos1:~$ docker run -d \
> --name backend \
> --network=devapp-net \
> --restart=always \
> -e PORT=8000 \
> -e GUESTBOOK_DB_ADDR=mongodb:27017 \
> leecloudo/guestbook:backend_1.0


4. frontend container 생성 
yji@hostos1:~$ docker run -d \
> --name frontend \
> -p 3000:8000 \
> --network devapp-net \
> --restart always \
> -e PORT=8000 \
> -e GUESTBOOK_API_ADDR=backend:8000 \
> leecloudo/guestbook:frontend_1.0

5. 컨테이너 확인 
yji@hostos1:~$ docker ps
CONTAINER ID   IMAGE                              COMMAND                  CREATED              STATUS              PORTS                                                  NAMES
f1aa90102f84   leecloudo/guestbook:frontend_1.0   "node --inspect=9229…"   About a minute ago   Up 59 seconds       0.0.0.0:3000->8000/tcp, :::3000->8000/tcp              frontend
748724ed766d   leecloudo/guestbook:backend_1.0    "node --inspect=9229…"   About a minute ago   Up About a minute                                                          backend
b1f64895ca07   mongo:4                            "docker-entrypoint.s…"   4 minutes ago        Up 4 minutes        0.0.0.0:17017->27017/tcp, :::17017->27017/tcp          mongodb

http://192.168.56.101:3000/
여기 접속해서 글 쓰면 ROBO 3T를 통해 볼 수 있다 !
ROBO 3T 접속 : 192.168.56.101, port: 17017

--

메모장

SandBox =- 격리된 network stack : namespace가 제공. 이더넷, 포트, DNS, 라우팅테이블, 방화벽을 제공한다.

  • swap은 물리적메모리의 2배를 잡는다.
  • 앱 구동시 최소 200MB는 필요하다.
    mysql의 가장 중요한 폴더 = /var/lib/mysql
    🐳 📕 ⭐ 📔 💭 🤔 ✍
profile
안녕하세요 😄

0개의 댓글