Docker 교육 2일차 정리

linux / / 2021. 3. 24. 17:45
반응형

Docker 교육 2일차 정리

Docker 교육을 들으며 혼자만의 방법으로 정리하는 중이니 docker 설치 및 사용법에 대해 궁금해서 들어온 분들은 아래 페이지에서 확인하시기 바랍니다.

https://kyumdoctor.co.kr/16 

 

Docker 설치 및 컨테이너 실행 옵션 사용방법

Docker 설치 및 컨테이너 실행 옵션 사용방법 Docker? nvidia-docker2? 이번 포스팅에서는 Docker에 대해 알아보려고 합니다. 사실 이미 오래전부터 사용되었던 Docker이지만 모르는 분들을 위한 글이기

kyumdoctor.co.kr

 

Docker 명령어

run

1) pull

2) image snapshot(create)

3) start

4) attach

 

--options

-h : docker hostname을 지정할 수 있다.

-d : detach 백그라운드 실행

-u : --user="사용자명" 사용자명을 입력

--restart=[no|on-failure|onfailure:횟수n|always] : 커맨드 실행 결과에 따라 재가동(unless-stopped)

--rm : 커맨드 실행 완료 container 자동 삭제

log -f : 실시간 로그 관측 가능

 

 

hostos1 복제 후 추가

 

/etc/hosts

192.168.56.101	hostos1
192.168.56.102	hostos2
192.168.56.103	hostos3

 

docker container test(nginx)

container test

  • nginx image를 --name options을 사용하여 webserver1로 지정 후
  • -d detached mode로 백그라운드 작업을 사용,
  • -p publish 를 사용하여 local 8001포트와 컨테이너 80포트를 포워딩한다.
  • docker ps로 컨테이너 작동 확인 후,
  • netstat -nlp |grep 8001로 docker-proxy port를 확인,
  • ps -ef |grep 4272로 process를 확인 하게 된다.

docker stats로 해당 container의 모니터링이 가능하며 foregroud로 확인되니, 새로운 창으로 띄워 실시간 확인이 가능하다.

 

Dockerfile

대문자 D로 시작하여 작성해야 한다.

코드로서 인프라 개발(IaC) 디렉토리 단위 개발

 

작업 환경 변경

jeff@hostos1:~$ mkdir LABs
jeff@hostos1:~$ cd LABs/
jeff@hostos1:~/LABs$ vim index.html
jeff@hostos1:~/LABs$ docker cp index.html webserver1:/usr/share/nginx/html
jeff@hostos1:~/LABs$ nginx webserver의 홈페이지가 수정한 index.html로 변경 됨 # docker cp(copy)

docker cp(copy) 명령어로 로컬서버의 index.html 파일로, webserver1 container안의 index.html 파일을 교체해준다.

 

 

jeff@hostos1:~/LABs$ vim Dockerfile
==== ADD ====
FROM php:7.2-apache

MAINTAINER datastory Hub <hylee@dshub.cloud>

ADD index.php /var/www/html/index.php

EXPOSE 80

CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
===============

jeff@hostos1:~/LABs$ git clone https://github.com/brayanlee/docker-phpserver.git
Cloning into 'docker-phpserver'...
remote: Enumerating objects: 18, done.
remote: Counting objects: 100% (18/18), done.
remote: Compressing objects: 100% (17/17), done.
remote: Total 18 (delta 4), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (18/18), done.

jeff@hostos1:~/LABs$ ls
Dockerfile  docker-phpserver  index.html
jeff@hostos1:~/LABs$ cd docker-phpserver/
jeff@hostos1:~/LABs/docker-phpserver$ ls
Dockerfile  index.php  index.php2  index.php3
  • Dockerfile생성 한다.
  • cmd를 통한 apache를 실행
  • git 을 하나 클론한다.
  • 다운로드한 깃에는 3가지 파일이 존재

 

jeff@hostos1:~/LABs/docker-phpserver$ cat index.php
<html>
<body>
<div style="font-size:25px">
<?php
$host=gethostname();
echo "Container Name : ";
echo $host;
?>
<p> Welcome to the Hell~! </p>
</div>
</body>
</html>
jeff@hostos1:~/LABs/docker-phpserver$ docker build -t phpserver:1.0 .
Sending build context to Docker daemon  83.46kB
Step 1/5 : FROM php:7.2-apache
7.2-apache: Pulling from library/php
c5516e56582: Pull complete
---> Running in 073edbdc69b0
Removing intermediate container 073edbdc69b0
 ---> f65a1f6dcd69
Successfully built f65a1f6dcd69
Successfully tagged phpserver:1.0

jeff@hostos1:~/LABs/docker-phpserver$ docker images
REPOSITORY        TAG          IMAGE ID       CREATED          SIZE
phpserver         1.0          f65a1f6dcd69   3 seconds ago    410MB

jeff@hostos1:~/LABs/docker-phpserver$ docker run -t -d -p 8004:80 \
> -h phpserver --name=phpserver phpserver:1.0
3f38c559688454638968a3c6b91332b7b093d3a115983e34c41475f66fc5ad87


jeff@hostos1:~/LABs/docker-phpserver$ curl localhost:8004
<html>
<body>
<div style="font-size:25px">
Container Name : phpserver<p> Welcome to the Hell~! </p>
</div>
</body>
</html>

jeff@hostos1:~/LABs/docker-phpserver$ docker exec -it phpserver bash
root@phpserver:/var/www/html# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

root@phpserver:/var/www/html# service apache2 status
[ ok ] apache2 is running.


jeff@hostos1:~/LABs/docker-phpserver$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED              STATUS              PORTS                    NAMES
3f38c5596884   phpserver:1.0            "docker-php-entrypoi…"   About a minute ago   Up About a minute   0.0.0.0:8004->80/tcp     phpserver
  • index php 파일 확인 후
  • docker build -t(tag) phpserver:1.0 . 빌드 후,
  • -p 8084:80 포워딩 옵션과 -h hostname옵션을 사용하여 docker run
  • curl 을 통해 사이트 확인
  • exec로 컨테이너 진입 후 apache 서비스 상태 running확인

 

container layer 확인

jeff@hostos1:~/LABs$ docker pull httpd:2.4
2.4: Pulling from library/httpd
6f28985ad184: Already exists
3a141a09d1d0: Pull complete
1633384edb75: Pull complete
acb3e3b931b8: Pull complete
f6dc6b8b1d70: Pull complete
Digest: sha256:9625118824bc2514d4301b387c091fe802dd9e08da7dd9f44d93ee65497e7c1c
Status: Downloaded newer image for httpd:2.4

jeff@hostos1:~/LABs$ docker image history httpd:2.4
IMAGE          CREATED       CREATED BY                                      SIZE      COMMENT
ae15ff2bdcb4   11 days ago   /bin/sh -c #(nop)  CMD ["httpd-foreground"]     0B
<missing>      11 days ago   /bin/sh -c #(nop)  EXPOSE 80                    0B
<missing>      11 days ago   /bin/sh -c #(nop) COPY file:c432ff61c4993ecd…   138B
<missing>      11 days ago   /bin/sh -c #(nop)  STOPSIGNAL SIGWINCH          0B
<missing>      11 days ago   /bin/sh -c set -eux;   savedAptMark="$(apt-m…   60.9MB
<missing>      11 days ago   /bin/sh -c #(nop)  ENV HTTPD_PATCHES=           0B
<missing>      11 days ago   /bin/sh -c #(nop)  ENV HTTPD_SHA256=740eddf6…   0B
<missing>      11 days ago   /bin/sh -c #(nop)  ENV HTTPD_VERSION=2.4.46     0B
<missing>      11 days ago   /bin/sh -c set -eux;  apt-get update;  apt-g…   7.38MB
<missing>      11 days ago   /bin/sh -c #(nop) WORKDIR /usr/local/apache2    0B
<missing>      11 days ago   /bin/sh -c mkdir -p "$HTTPD_PREFIX"  && chow…   0B
<missing>      11 days ago   /bin/sh -c #(nop)  ENV PATH=/usr/local/apach…   0B
<missing>      11 days ago   /bin/sh -c #(nop)  ENV HTTPD_PREFIX=/usr/loc…   0B
<missing>      12 days ago   /bin/sh -c #(nop)  CMD ["bash"]                 0B
<missing>      12 days ago   /bin/sh -c #(nop) ADD file:3c32f1cd03198e141…   69.2MB
  • pull complete 갯수
  • image history 로 이미지 확인
  • size 표기 갯수 확인

 

중간 Tip

  • 리눅스 정상종료 SIGTERM(0)
  • 리눅스 비정상종료 SIGKILL(137)
  • Container 정상종료 EXITED(0)
  • Container 비정상종료 EXITED(137)등

 

Docker 정상종료 컨테이너 삭제

$ docker ps -a -q --filter 'status=exited'

-q = container id

 

$ docker rm $(docker ps -a -q --filter 'status=exited')

$ alias cexrm='docker rm $(docker ps -a -q --filter 'status=exited')'

$ .bashrc 에 추가 등록

 

alias를 등록하여 간편하게 종료된 컨테이너 삭제

 

 

Docker tag & push

docker tag & push

  • 기존의 이미지를 tag로 alias와 같이 내  아이디로 변경 후,
  • push로 본인의 docker hub에 올리면 끝.

 

Docker login password

docker login시 생성되는 패스워드는 항상 동일한 문자로 저장된다.

password는 암호화 되어 있지 않으므로 token 생성으로 해결할 수 있다.

 

  1. docker hub 사이트 본인 ID클릭
  2. account settings
  3. security
  4. new access tokens
  5. 발급토큰 복사
  6. vim .access_token 저장
  7. cat .access_token | docker login --username 1985ck --password-stdin
jeff@hostos1:~$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED             STATUS             PORTS                                             NAMES
16cbcd9c7334   redis                    "docker-entrypoint.s…"   23 seconds ago      Up 22 seconds                                                        redis-server
a7e9ef7c2820   httpd                    "httpd-foreground"       58 seconds ago      Up 57 seconds      80/tcp                                            httpd-server

active inactive

 

Docker 네트워크

jeff@hostos1:~$ docker run -it -d --name=ubuntu_test1 ubuntu:14.04
0d13a0ee8a7c5f81c670e0ee397e62dec38af59665f9144e7c280e688375ae47
jeff@hostos1:~$ docker exec -it ubuntu_test1 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
jeff@hostos1:~$ docker exec -it ubuntu_test1 ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
39: eth0@if40: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:06 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.6/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
jeff@hostos1:~$ brctl show
bridge name     bridge id               STP enabled     interfaces
docker0         8000.02425f9b5950       no              veth69f24d1
                                                        veth87a54f7
                                                        veth8a367bb
                                                        veth8dd08d0
                                                        vethabe5fcb
                                                        vethb3b7e28
jeff@hostos1:~$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED          STATUS          PORTS                    NAMES
0d13a0ee8a7c   ubuntu:14.04             "/bin/bash"              26 seconds ago   Up 25 seconds                            ubuntu_test1

jeff@hostos1:~$ docker inspect ubuntu_test1 |grep -i "ipa\|mac"
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.6",
            "MacAddress": "02:42:ac:11:00:06",
                    "IPAMConfig": null,
                    "IPAddress": "172.17.0.6",
                    "MacAddress": "02:42:ac:11:00:06",



jeff@hostos1:~$ docker run -itd --add-host=hostos1:192.168.56.101 \
> --dns=8.8.8.8 centos bash
jeff@hostos1:~$ docker exec -it jovial_buck cat /etc/hosts
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
192.168.56.101  hostos1
172.17.0.8      e5784471f931
jeff@hostos1:~$ docker exec -it jovial_buck cat /etc/resolv.conf
nameserver 8.8.8.8


jeff@hostos1:~$ docker run -d --expose=10000 -P nginx

jeff@hostos1:~$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED          STATUS          PORTS                                             NAMES
2bb1074db31d   nginx                    "/docker-entrypoint.…"   4 seconds ago    Up 3 seconds    0.0.0.0:49154->80/tcp, 0.0.0.0:49153->10000/tcp   kind_benz

jeff@hostos1:~$ sudo netstat -nlp |grep 49154
[sudo] password for jeff:
tcp        0      0 0.0.0.0:49154           0.0.0.0:*               LISTEN      10474/docker-proxy
jeff@hostos1:~$ ps -ef |grep 49154
root     10474  1080  0 16:17 ?        00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 49154 -container-ip 172.17.0.9 -container-port 80
jeff     10733  3393  0 16:20 pts/0    00:00:00 grep --color=auto 49154
iptraf-ng (네트워크 트래픽 모니터링 툴)

네트워크 생성
jeff@hostos1:~$ docker network create -d bridge webap-net
2821d85085ac4d2aebc42b9f09f4ff40e2af58beee68b6a4d89b18781efcbddf
jeff@hostos1:~$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         _gateway        0.0.0.0         UG    100    0        0 enp0s3
10.0.2.0        0.0.0.0         255.255.255.0   U     100    0        0 enp0s3
link-local      0.0.0.0         255.255.0.0     U     1000   0        0 enp0s3
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
172.18.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-2821d85085ac
192.168.56.0    0.0.0.0         255.255.255.0   U     101    0        0 enp0s8
jeff@hostos1:~$ docker network ls
NETWORK ID     NAME        DRIVER    SCOPE
1b47cc87ec0d   bridge      bridge    local
f176a0d8f57e   host        host      local
494c1c6f158a   none        null      local
2821d85085ac   webap-net   bridge    local
jeff@hostos1:~$ ifconfig |grep br
br-2821d85085ac: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.18.0.1  netmask 255.255.0.0  broadcast 172.18.255.255
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet 192.168.56.101  netmask 255.255.255.0  broadcast 192.168.56.255
jeff@hostos1:~$ docker run --net=webap-net -it --name=net-check ubuntu:14.04 bash
root@3bad8a3bff22:/# ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:ac:12:00:02
          inet addr:172.18.0.2  Bcast:172.18.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:32 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:4269 (4.2 KB)  TX bytes:0 (0.0 B)

새로운 터미널
# brctl show
bridge name     bridge id               STP enabled     interfaces
br-2821d85085ac         8000.0242f5b255a0       no              vethd8776d7
docker0         8000.02425f9b5950       no              veth3a1404d
                                                        veth69f24d1
                                                        veth87a54f7
                                                        veth8a367bb
                                                        veth8dd08d0
                                                        vethabe5fcb
                                                        vethb3b7e28
                                                        vethc89b807
# docker network inspect webap-net
# docker exec net-check route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         hostos1         0.0.0.0         UG    0      0        0 eth0
172.18.0.0      *               255.255.0.0     U     0      0        0 eth0

jeff@hostos1:~$ docker network create \
> --driver bridge \
> --subnet 172.100.1.0/24 \
> --ip-range 172.100.1.0/24 \
> --gateway 172.100.1.1 \
> vswitch-ap
09b98e6f524d68c6e95388ce044b1b0717b7a1602a8775ef777a99421273ac60
jeff@hostos1:~$ docker network ls
NETWORK ID     NAME         DRIVER    SCOPE
1b47cc87ec0d   bridge       bridge    local
f176a0d8f57e   host         host      local
494c1c6f158a   none         null      local
09b98e6f524d   vswitch-ap   bridge    local
2821d85085ac   webap-net    bridge    local
jeff@hostos1:~$ docker network inspect vswitch-ap
[
    {
        "Name": "vswitch-ap",
        "Id": "09b98e6f524d68c6e95388ce044b1b0717b7a1602a8775ef777a99421273ac60",
        "Created": "2021-03-24T16:49:03.469227602+09:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.100.1.0/24",
                    "IPRange": "172.100.1.0/24",
                    "Gateway": "172.100.1.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]

jeff@hostos1:~$ docker run --net=vswitch-ap -itd --name=net1 ubuntu:14.04
8c96f2a4998182b326e12303f056f47af686f546ff1e772cd7e3681c4251f145
jeff@hostos1:~$ docker run --net=vswitch-ap -itd --name=net2 --ip 172.100.1.100 ubuntu:14.04
7b648dc3cc00ac21730f8b69d2ea97a8010cdc6ec3f106fbebba669a9ead4349
jeff@hostos1:~$ docker inspect net1 |grep -i ipad
            "SecondaryIPAddresses": null,
            "IPAddress": "",
                    "IPAddress": "172.100.1.2",
jeff@hostos1:~$ docker inspect net2 |grep -i ipad
            "SecondaryIPAddresses": null,
            "IPAddress": "",
                    "IPAddress": "172.100.1.100",
jeff@hostos1:~$ brctl show
bridge name     bridge id               STP enabled     interfaces
br-09b98e6f524d         8000.02429f233f0c       no              veth965864c
                                                        vethf6e7717
br-2821d85085ac         8000.0242f5b255a0       no
docker0         8000.02425f9b5950       no              veth3a1404d
                                                        veth69f24d1
                                                        veth87a54f7
                                                        veth8a367bb
                                                        veth8dd08d0
                                                        vethabe5fcb
                                                        vethb3b7e28
                                                        vethc89b807
jeff@hostos1:~$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         _gateway        0.0.0.0         UG    100    0        0 enp0s3
10.0.2.0        0.0.0.0         255.255.255.0   U     100    0        0 enp0s3
link-local      0.0.0.0         255.255.0.0     U     1000   0        0 enp0s3
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
172.18.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-2821d85085ac
172.100.1.0     0.0.0.0         255.255.255.0   U     0      0        0 br-09b98e6f524d
192.168.56.0    0.0.0.0         255.255.255.0   U     101    0        0 enp0s8
jeff@hostos1:~$ docker exec net1 route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         cpe-172-100-1-1 0.0.0.0         UG    0      0        0 eth0
172.100.1.0     *               255.255.255.0   U     0      0        0 eth0

jeff@hostos1:~/LABs$ docker exec -it 8c96f2a49981 bash
root@8c96f2a49981:/# ping net2
PING net2 (172.100.1.100) 56(84) bytes of data.
64 bytes from net2.vswitch-ap (172.100.1.100): icmp_seq=1 ttl=64 time=0.052 ms
64 bytes from net2.vswitch-ap (172.100.1.100): icmp_seq=2 ttl=64 time=0.037 ms
64 bytes from net2.vswitch-ap (172.100.1.100): icmp_seq=3 ttl=64 time=0.053 ms
root@7b648dc3cc00:/# ping net1
PING net1 (172.100.1.2) 56(84) bytes of data.
64 bytes from net1.vswitch-ap (172.100.1.2): icmp_seq=1 ttl=64 time=0.032 ms
64 bytes from net1.vswitch-ap (172.100.1.2): icmp_seq=2 ttl=64 time=0.203 ms
64 bytes from net1.vswitch-ap (172.100.1.2): icmp_seq=3 ttl=64 time=0.118 ms
같은 네트워크 대역의 컨테이너들은 컨테이너 id가 아닌 컨테이너 name으로 ping 이 가능하다.





jeff@hostos1:~$ docker run -d --name=httpd-server httpd
Unable to find image 'httpd:latest' locally
latest: Pulling from library/httpd
Digest: sha256:9625118824bc2514d4301b387c091fe802dd9e08da7dd9f44d93ee65497e7c1c
Status: Downloaded newer image for httpd:latest
a7e9ef7c2820f93d8fc274220d774dc46126bc93925d2986bf889241d8b0c2e1
jeff@hostos1:~$ docker run -d --name=redis-server --net=container:httpd-server redis
Unable to find image 'redis:latest' locally
latest: Pulling from library/redis
6f28985ad184: Already exists
60e8b46025d8: Pull complete
122fe26e50b0: Pull complete
de3ca1eb2e20: Pull complete
4813a7e5bd57: Pull complete
99dd8d3a66f2: Pull complete
Digest: sha256:e97d506be34a39fa69f45eea846080d6985c2c9ee338c0d408c7ea4347f014a5
Status: Downloaded newer image for redis:latest
16cbcd9c73342b7ed7490446297b61495b269de7fa4bbb9e36edad0425240d44

jeff@hostos1:~$ docker ps
CONTAINER ID   IMAGE                    COMMAND                  CREATED             STATUS             PORTS                                             NAMES
16cbcd9c7334   redis                    "docker-entrypoint.s…"   23 seconds ago      Up 22 seconds                                                        redis-server
a7e9ef7c2820   httpd                    "httpd-foreground"       58 seconds ago      Up 57 seconds      80/tcp                                            httpd-server

추후수정

 

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기