brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Jun 08. 2021

쿠버1탄-1. 우분투에 도커 설치,컨테이너-2021

자료 1/32

다음은 쿠버네티스 스터디 자료를 참고해  정리한 내용입니다.


<1> 도커를 알아보고, AWS에서  ubuntu 서버 생성

<2> ubuntu  login과 업데이트

<3> 서버 정보 확인

<4> 도커 설치

<5> 도커 설치 후 확인

<6> AWS에 도커 서버 구성과 cowsay 컨테이너 실행

<7> docker.io 는  기본 경로에 포함되어 있어 생략해도 된다.

<8> 도커 허브 (이미지 저장소) 계정 만들기

<9> 도커 파일 만들기

<10> 이미지를 컨테이너에서 실행

<11> 도커 이미지  업로드를 위해 태그 달기

<12> 도커 허브 계정 생성과 로그인

<13>  push

<14> 도커 허브에  이미지 올라간 것  확인

<15> 로컬에 있는 이미지  삭제하고 도커 이미지 실행해보자.

<16> 도커 이미지 실행시키기, 로컬에 이미지가 없으면  레파지토리에서 가져옴

<17> 확인

<18> 모든 컨테이너 삭제

<19> 개인 정리

<20> AWS 사이트에도 도커 이미지 만드는 예제가 있다. 참고 바란다.





<1> 도커를 알아보고, AWS에서  ubuntu 서버 생성




1

도커를 알아보자.


도커 이미지를 만들어 쉽게 서로 다른 시스템으로 편하게 이동 시킬수 있다.



참고 유튜브

https://www.youtube.com/watch?v=tPjpcsgxgWc




2

https://www.youtube.com/watch?v=NLUugLQ8unM&list=PLApuRlvrZKogb78kKq1wRvrjg1VMwYrvi





3

내용

우분트 서버에 도커를 설치해보자.

도커 파일로 이미지를 만들어 보자 = build

태그를 달고 도커 허브에 이미지를 올리자.  Registry = 도커 허브에 push

도커 저장소에서 이미지 가져와 서비스해보자. pull & run







4

개발 서버 1대를 구하라~


AWS 나 Google GCP에   ubuntu  생성


public subnet

공인 ip

ubuntu  서버 하나 생성한다.




5

개발 서버 구하는법


https://brunch.co.kr/@topasvga/705






<2> ubuntu  login과 업데이트



1

login as:

ubuntu

sudo su -




2

apt update





<3>  서버 정보 확인

 


1

버전 확인

lsb_release -a

No LSB modules are available.

Distributor ID: Ubuntu

Description:    Ubuntu xxxxx LTS

Release:       xxxxx

Codename:       focal



2

프로세스 확인

ps auf

USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

ubuntu      1326  0.0  0.5  10028  5148 pts/0    Ss   05:06   0:00 -bash

root        1343  0.0  0.4  11172  4748 pts/0    S    05:06   0:00  \_ sudo su -

root        1344  0.0  0.4  10132  4312 pts/0    S    05:06   0:00      \_ su -

root        1345  0.0  0.5  10028  5032 pts/0    S    05:06   0:00          \_ -

root        1689  0.0  0.3  10616  3380 pts/0    R+   05:07   0:00             p

root         540  0.0  0.1   5828  1844 tty1     Ss+  05:04   0:00 /sbin/agetty

root         517  0.0  0.2   7352  2104 ttyS0    Ss+  05:04   0:00 /sbin/agetty



pstree

systemd─┬─accounts-daemon───2*[{accounts-daemon}]

        ├─acpid

        ├─2*[agetty]

        ├─amazon-ssm-agen─┬─ssm-agent-worke───7*[{ssm-agent-worke}]

        │                 └─7*[{amazon-ssm-agen}]

        ├─atd

        ├─cron

        ├─dbus-daemon

        ├─multipathd───6*[{multipathd}]

        ├─networkd-dispat

        ├─packagekitd───2*[{packagekitd}]

        ├─polkitd───2*[{polkitd}]

        ├─rsyslogd───3*[{rsyslogd}]

        ├─snapd───11*[{snapd}]

        ├─sshd───sshd───sshd───bash───sudo───su───bash───pstree

        ├─systemd───(sd-pam)

        ├─systemd-journal

        ├─systemd-logind

        ├─systemd-network

        ├─systemd-resolve

        ├─systemd-timesyn───{systemd-timesyn}

        ├─systemd-udevd

        └─unattended-upgr───{unattended-upgr}



3

IP 확인 ?

 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

    inet6 ::1/128 scope host

       valid_lft forever preferred_lft forever

2: ens5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000

    link/ether 02:61:e3:02:0f:c6 brd ff:ff:ff:ff:ff:ff

    inet 10.0.0.116/24 brd 10.0.0.255 scope global dynamic ens5

       valid_lft 3329sec preferred_lft 3329sec

    inet6 fe80::61:e3ff:fe02:fc6/64 scope link

       valid_lft forever preferred_lft forever



4

ip route show

default via 10.0.0.1 dev ens5 proto dhcp src 10.0.0.116 metric 100

10.0.0.0/24 dev ens5 proto kernel scope link src 10.0.0.116

10.0.0.1 dev ens5 proto dhcp scope link src 10.0.0.116 metric 100



5

서버에 설정된 iptable 보안 정책 확인

IPTABLE 확인해보면 기본으로 모두 열려있다.


 iptables -t filter -S

-P INPUT ACCEPT

-P FORWARD ACCEPT

-P OUTPUT ACCEPT


iptables -t nat -S

-P PREROUTING ACCEPT

-P INPUT ACCEPT

-P OUTPUT ACCEPT

-P POSTROUTING ACCEPT



6

df -hT

Filesystem     Type      Size  Used Avail Use% Mounted on

/dev/root      ext4      7.7G  1.3G  6.5G  17% /

devtmpfs       devtmpfs  484M     0  484M   0% /dev

tmpfs          tmpfs     490M     0  490M   0% /dev/shm

tmpfs          tmpfs      98M  784K   98M   1% /run

tmpfs          tmpfs     5.0M     0  5.0M   0% /run/lock

tmpfs          tmpfs     490M     0  490M   0% /sys/fs/cgroup

/dev/loop0     squashfs   34M   34M     0 100% /snap/amazon-ssm-agent/3552

/dev/loop1     squashfs   56M   56M     0 100% /snap/core18/1997

/dev/loop2     squashfs   71M   71M     0 100% /snap/lxd/19647

/dev/loop3     squashfs   33M   33M     0 100% /snap/snapd/11588

tmpfs          tmpfs      98M     0   98M   0% /run/user/1000


root@ip-10-0-0-116:~#  df -h --type=ext4

Filesystem      Size  Used Avail Use% Mounted on

/dev/root       7.7G  1.5G  6.3G  19% /



7

유틸 설치

 apt-get install bridge-utils net-tools jq tree -y




<4>  도커 설치


컨테이너는 도커가 설치된 어디에서나(온프라미스/클라우드 환경)에서 실행할수 있다.


도커 설치법

https://docs.docker.com/engine/install/ubuntu/



도커  다운을 위한 필요한 패키지  설치



1

도커  다운을 위한 필요한 패키지  설치


sudo su -

apt-get update && apt-get -y install apt-transport-https ca-certificates curl gnupg lsb-release


참고

https://roseline124.github.io/kuberdocker/2019/07/17/docker-study02.html




2

도커 다운로드

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg



3

echo \

  "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \

  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null



4

cat /etc/apt/sources.list.d/docker.list



5

# 도커 설치

apt-get update && apt-get -y install docker-ce docker-ce-cli containerd.io



6

도커 정보 확인 ?

 docker info


Client:

 Context:    default

 Debug Mode: false

 Plugins:

  app: Docker App (Docker Inc., v0.9.1-beta3)

  buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)

  scan: Docker Scan (Docker Inc., v0.8.0)


Server:

 Containers: 0

:

  userxattr: false

 Logging Driver: json-file

 Cgroup Driver: cgroupfs

 Cgroup Version: 1

:

 ID: 35OU:VQTE:TKGY:N3IU:CGCP:ZNRR:WMSR:EDWB:5IVJ:4ZYM:WRCY:K5LO

 Docker Root Dir: /var/lib/docker

 Debug Mode: false

 Registry: https://index.docker.io/v1/

 Labels:

 Experimental: false

 Insecure Registries:

  127.0.0.0/8

 Live Restore Enabled: false



7

도커 상태 확인 ?

 systemctl status docker


 docker.service - Docker Application Container Engine

     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)

     Active: active (running) since Sun 2021-06-06 12:32:01 UTC; 4min 37s ago

TriggeredBy:  docker.socket

       Docs: https://docs.docker.com

   Main PID: 2482 (dockerd)

      Tasks: 8

     Memory: 54.3M

     CGroup: /system.slice/docker.service

             └─2482 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock


Jun 06 12:32:00 ip-10-0-0-163 dockerd[2482]: time="2021-06-06T12:32:00.898013709Z" level=warning msg="Your kernel does not support CPU real>


Command 'tree' not found, but can be installed with:


snap install tree  # version 1.8.0+pkg-3fd6, or

apt  install tree  # version 1.8.0-1

See 'snap info tree' for additional versions.



8

버전 확인

docker version



9

도커 root 디렉토리 정보 확인 ?


tree -L 3 /var/lib/docker

/var/lib/docker

├── buildkit

│   ├── cache.db

│   ├── containerdmeta.db

│   ├── content

│   │   └── ingest

│   ├── executor

│   ├── metadata_v2.db

│   └── snapshots.db

├── containers

├── image

│   └── overlay2

│       ├── distribution

│       ├── imagedb

│       ├── layerdb

│       └── repositories.json

├── network

│   └── files

│       └── local-kv.db

├── overlay2

│   └── l

├── plugins

│   ├── storage

│   │   └── ingest

│   └── tmp

├── runtimes

├── swarm

├── tmp

├── trust

└── volumes

    ├── backingFsBlockDev

    └── metadata.db


23 directories, 8 files




<5> 도커 설치 후 확인


1

pstree

systemd─┬─accounts-daemon───2*[{accounts-daemon}]

        ├─acpid

        ├─2*[agetty]

        ├─amazon-ssm-agen─┬─ssm-agent-worke───7*[{ssm-agent-worke}]

        │                 └─7*[{amazon-ssm-agen}]

        ├─atd

        ├─containerd───8*[{containerd}]

        ├─cron

        ├─dbus-daemon

        ├─dockerd───7*[{dockerd}]

        ├─multipathd───6*[{multipathd}]

        ├─networkd-dispat

        ├─packagekitd───2*[{packagekitd}]

        ├─polkitd───2*[{polkitd}]

        ├─rsyslogd───3*[{rsyslogd}]

        ├─snapd───11*[{snapd}]

        ├─sshd───sshd───sshd───bash───sudo───su───bash───pstree

        ├─systemd───(sd-pam)

        ├─systemd-journal

        ├─systemd-logind

        ├─systemd-network

        ├─systemd-resolve

        ├─systemd-timesyn───{systemd-timesyn}

        ├─systemd-udevd

        └─unattended-upgr───{unattended-upgr}



2

IP 확인하면  docker0가 생겼다.

DOWN 상태


 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

    inet6 ::1/128 scope host

       valid_lft forever preferred_lft forever

2: ens5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000

    link/ether 02:61:e3:02:0f:c6 brd ff:ff:ff:ff:ff:ff

    inet 10.0.0.116/24 brd 10.0.0.255 scope global dynamic ens5

       valid_lft 2369sec preferred_lft 2369sec

    inet6 fe80::61:e3ff:fe02:fc6/64 scope link

       valid_lft forever preferred_lft forever

3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default

    link/ether 02:42:64:35:16:c8 brd ff:ff:ff:ff:ff:ff

    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0

       valid_lft forever preferred_lft forever



3

브리지 정보 확인

brctl show

bridge name     bridge id               STP enabled     interfaces

docker0         8000.0242643516c8       no



4

iptables를 보면  docker0 관련 추가 되었다


iptables -t filter -S

-P INPUT ACCEPT

-P FORWARD DROP

-P OUTPUT ACCEPT

-N DOCKER

-N DOCKER-ISOLATION-STAGE-1

-N DOCKER-ISOLATION-STAGE-2

-N DOCKER-USER

-A FORWARD -j DOCKER-USER

-A FORWARD -j DOCKER-ISOLATION-STAGE-1

-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

-A FORWARD -o docker0 -j DOCKER

-A FORWARD -i docker0 ! -o docker0 -j ACCEPT

-A FORWARD -i docker0 -o docker0 -j ACCEPT

-A DOCKER-ISOLATION-STAGE-1 -i docker0 ! -o docker0 -j DOCKER-ISOLATION-STAGE-2

-A DOCKER-ISOLATION-STAGE-1 -j RETURN

-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP

-A DOCKER-ISOLATION-STAGE-2 -j RETURN

-A DOCKER-USER -j RETURN


iptables를 보면  docker0 관련  뭐가 추가 되었다

iptables -t nat -S

-P PREROUTING ACCEPT

-P INPUT ACCEPT

-P OUTPUT ACCEPT

-P POSTROUTING ACCEPT

-N DOCKER

-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER

-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER

-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE

-A DOCKER -i docker0 -j RETURN




<6> AWS에 도커 서버 구성과 cowsay 컨테이너 실행



1

Docker 설치가 잘 되었다면 2번애서 바로 실습하기


설치가 잘 안되었다면 AWS에서 CloudFromation으로 우분트에 도커 자동 설치후 진행



로그인

ubuntu




2

cowsay 컨테이너 사용해보기

apt install cowsay -y

Reading package lists... Done



3

 cowsay hello  이름쓰기

 cowsay hello seo

___________

< hello seo >

 -----------

        \   ^__^

         \  (oo)\_______

            (__)\       )\/\

                ||----w

                ||     




4

docker ps

실행중인 docker 확인


docker ps -a

종료된 docker까지 확인




5

컨테이너 실행

docker run docker/whalesay cowsay  'hi seo'

________

< hi seo >

 --------

    \

     \

      \

                    ##        .

              ## ## ##       ==

           ## ## ## ##      ===

       /""""""""""""""""___/ ===

  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~

       \______ o          __/

        \    \        __/

          \____\______/




6

 docker images

REPOSITORY        TAG       IMAGE ID       CREATED       SIZE

docker/whalesay   latest    6b362a9f73eb   6 years ago   247MB



7

정상 종료된 exited (0) 된 contailer  확인

docker ps -a

CONTAINER ID   IMAGE COMMAND       CREATED              STATUS                          PORTS     NAMES

6ad1d0d07fe8   docker/whalesay   "cowsay 'hi seo'"   About a minute ago   Exited (0) About a minute ago             lucid_robinson


Exited (0) = 정상으로 종료된 상태라는 뜻이다.



8

공식 도커 허브  Registry에서 가져온것이다.

기본 레지스트리 주소 : docker.io 이다.  디폴트 경로


<레지스트리 이름> / <이미지 이름 > : <TAG>형식이다.

기본 사용 TAG = latest




<7>  docker.io 는  기본 경로에 포함 되어 있어 생략해도 된다.



1

docker images

REPOSITORY        TAG       IMAGE ID       CREATED       SIZE

docker/whalesay   latest    6b362a9f73eb   6 years ago   247MB



2

docker.io에서 가져오기 시도한다.

docker pull  docker/whalesay:latest

이미 존재한다고 표시 된다.


latest: Pulling from docker/whalesay

Image docker.io/docker/whalesay:latest uses outdated schema1 manifest format. Please upgrade to a schema2 image for better future compatibility. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/

e190868d63f8: Already exists

909cd34c6fd7: Already exists

0b9bfabab7c1: Already exists



3

docker images

REPOSITORY        TAG       IMAGE ID       CREATED       SIZE

docker/whalesay   latest    6b362a9f73eb   6 years ago   247MB


 docker ps -a

CONTAINER ID   IMAGE             COMMAND        CREATED         STATUS                     PORTS     NAMES

ea6c6693abbd   docker/whalesay   "cowsay soe"   7 minutes ago   Exited (0) 7 minutes ago             agitated_mclaren



4

컨테이너 이미지 이름만 확인


docker ps -a -q

ea6c6693abbd



5

지우기

docker rm $(docker ps -a -q)

ea6c6693abbd



6

지워진것 확인

 docker ps -a -q

CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES




<8>  nginx 컨테이너 실습


1

실습 내용 ?


공식 도커 허브  Registry에서 가져와서 사용해보기~

도커 허브에서 이미지를 가져온다.

컨테이너에서 Nginx를 실행한다.



2

docker run -d nginx


-d 는 Detached 모드로 컨테이너를 실행.

컨테이너를 백그라운드에서 동작

Unable to find image 'nginx:latest' locally

latest: Pulling from library/nginx

07aded7c29c6: Pull complete

bbe0b7acc89c: Pull complete

44ac32b0bba8: Pull complete

91d6e3e593db: Pull complete

8700267f2376: Pull complete


공식 도커 허브  Registry에서 가져온것이다.

기본 레지스트리 주소 : docker.io 이다.  디폴트 경로



3

docker ps

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES

4fdc8804dc31   nginx     "/docker-entrypoint.…"   56 seconds ago   Up 55 seconds   80/tcp    romantic_lehmann



4

실행중인 컨테이너의 ID만 확인

docker ps -q

4fdc8804dc31



5

컨테이너 상세 정보 확인

https://docs.docker.com/engine/reference/commandline/inspect/


docker inspect $(docker ps -q)



6

IP확인 ?

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)


ping 172.17.0.2

PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.

64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.072 ms

64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.051 ms



7

ip a

brctl show

bridge name     bridge id               STP enabled     interfaces

docker0         8000.0242966a7b18       no              vethe2cb9b6



8

curl로 웹 접속 테스트


curl `docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)`

<!DOCTYPE html>

<html>

<head>

<title>Welcome to nginx!</title>

<style>



 curl 172.17.0.2



9

컨테이너 상세 정보 확인

docker inspect <CONTAINER_ID>

docker inspect $(docker ps -q)

docker inspect $(docker ps -q) | more



10

컨테이너 IP확인 ?

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)



11

컨테이너 로그 확인?

docker logs <CONTAINER_ID>

docker logs -f $(docker ps -q)



12

다른 터미널에서 질의

curl `docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)`



13

컨테이너에 명령어 전달법 ?


docker exec <CONTAINER_ID> <CMD>

nginx 컨테이너의 index.html 파일의 위치는 /usr/share/nginx/html/index.html

nginx 컨테이너에  ls 해서 /usr/share/nginx/html 의 경로에 뭐가 있는지 확인하는것이다.


docker exec $(docker ps -q) ls /usr/share/nginx/html

50x.html

index.html



nginx 컨테이너에  cat  해서 /usr/share/nginx/html/index.html 내용을 확인하는것이다.


docker exec $(docker ps -q) cat /usr/share/nginx/html/index.html

<!DOCTYPE html>

<html>

<head>

<title>Welcome to nginx!</title>

<style>

html { color-scheme: light dark; }



컨테이너 내부의 파일을 수정해보자!!!

docker exec $(docker ps -q) sh -c 'echo WebServer > /usr/share/nginx/html/index.html'


docker exec $(docker ps -q) curl -s localhost

WebServer

// 수정 되었다!!!



14

컨테이너 중단?


docker stop <CONTAINER_ID>


docker ps

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES

4fdc8804dc31   nginx     "/docker-entrypoint.…"   11 minutes ago   Up 11 minutes   80/tcp    romantic_lehmann


멈추기

docker stop $(docker ps -q)



15

현재 사용중인 컨테이너 확인?


docker ps

CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES


종료된 컨테이너까지 확인 ?

 docker ps -a

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS         PORTS     NAMES

4fdc8804dc31   nginx     "/docker-entrypoint.…"   12 minutes ago   Exited (0) 30 seconds ago             romantic_lehmann



16

중단된 컨테이너 확인?

docker ps -a


중단된거 확인

docker start $(docker ps -aq)


확인

docker ps

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES

4fdc8804dc31   nginx     "/docker-entrypoint.…"   14 minutes ago   Up 16 seconds   80/tcp    romantic_lehmann




17

컨테이너 삭제?


docker rm <CONTAINER_ID>


중지

docker stop $(docker ps -q)


확인

docker ps -a

CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                      PORTS     NAMES

4fdc8804dc31   nginx     "/docker-entrypoint.…"   15 minutes ago   Exited (0) 10 seconds ago             romantic_lehmann


컨테이너 삭제

docker rm $(docker ps -aq) -f

4fdc8804dc31



18

종료된 컨테이너 전부 삭제

docker rm $(docker ps -a -q)



19

실행과 종료된 컨테이너 전부 삭제

docker rm -f $(docker ps -a -q)


확인

docker ps -a


이미지 확인

docker images

REPOSITORY        TAG       IMAGE ID       CREATED       SIZE

nginx             latest    f8f4ffc8092c   5 days ago    133MB

docker/whalesay   latest    6b362a9f73eb   6 years ago   247MB



20

이미지 삭제?

docker rmi



21

컨테이너 이미지는  다른 OS버전에서 설치 가능하다.


docker run -it ubuntu:16.04 bash


우분트 16.04 버전을 다운받고  해당 컨테이너를 설치하게 된다.


해당 컨테이너에서 버전 확인?


cat /etc/os-release

NAME="Ubuntu"

VERSION="16.04.7 LTS (Xenial Xerus)"

ID=ubuntu

ID_LIKE=debian

PRETTY_NAME="Ubuntu 16.04.7 LTS"


ps -ef

UID          PID    PPID  C STIME TTY          TIME CMD

root           1       0  0 10:13 pts/0    00:00:00 bash

root          12       1  0 10:15 pts/0    00:00:00 ps -ef


root@d8cf1ad5859f:/# exit



22

 docker run -it centos bash


cat /etc/os-release

NAME="CentOS Linux"

VERSION="8"

ID="centos"

ID_LIKE="rhel fedora"

VERSION_ID="8"



23

도커 허브 (이미지 저장소) 계정 만들기

도커 허브(Docker Hub)는 도커 이미지 원격 저장소 입니다.

사용자가 도커 허브에 이미지를 업로드 하여 사용한다.

https://hub.docker.com/

masterseo11-g1002!




<9> 도커 파일 만들기


개발자가 도커파일을 생성한다.

빌드하면 도커 이미지가 만들어진다.



이미지 출처

https://cultivatehq.com/posts/docker/



1

테스트

mkdir dockerfile && cd dockerfile

echo 'Test Web page' > test.html

ls



2

도커 파일 만들기


cat <<EOT> Dockerfile

FROM ubuntu:14.04

LABEL maintainer "topasvga"

LABEL "purpose"="practice"

RUN sed -i 's/archive.ubuntu.com/ftp.daum.net/g' /etc/apt/sources.list

RUN apt-get update

RUN apt-get install apache2 figlet -y

ADD test.html /var/www/html

WORKDIR /var/www/html

RUN ["/bin/bash", "-c", "echo Hello!  topasvga docker ! | figlet > /var/www/html/index.html"]

EXPOSE 80

CMD apachectl -DFOREGROUND

EOT



3

도커 빌드?

도커 파일을 읽어서 이미지 파일을 만드는것


docker build -t hello:1 ./


Sending build context to Docker daemon  3.072kB

Step 1/11 : FROM ubuntu:14.04

14.04: Pulling from library/ubuntu

:

Removing intermediate container b7eed1cae2f4

 ---> 78236e8ceba0

Successfully built 78236e8ceba0

Successfully tagged hello:1



4

생성된 이미지 확인 ?


docker images

REPOSITORY        TAG       IMAGE ID       CREATED          SIZE

hello             1         592872f2bddc   13 seconds ago   222MB

ubuntu            14.04     13b66b487594   2 months ago     197MB

docker/whalesay   latest    6b362a9f73eb   6 years ago      247MB




<10> 이미지를 컨테이너에서 실행



1

hello1 이미지를 실행

호스트 8080 포트를 컨테이너 80 포트로 매핑함.

8080를 호출해봄  

curl localhost:8080


docker run -d -p 8080:80 --name webserver1 hello:1

// -d 백그라운드로 실행 , -p 포트 포워딩  , hello:1 라는 이미지를 실행 시켜라.

cb87aee3152a6f9f12f300713d94ed7bf597f9ed5f52ec0c11154c8a5ee6fb45



2

docker ps

CONTAINER ID   IMAGE     COMMAND      CREATED     STATUS      PORTS                        NAMES

cb87aee3152a   hello:1   "/bin/sh -c 'apachec…"   About a minute ago   Up About a minute   0.0.0.0:8080->80/tcp, :::8080->80/tcp   webserver                                                       1

//  이 컨테이너로 8080 으로  접속하면, 컨테이너 80으로 접속 된다.



3

curl localhost:8080

 _   _      _ _       _   _

| | | | ___| | | ___ | | | |_ ___  _ __   __ _ _____   ____ _  __ _

| |_| |/ _ \ | |/ _ \| | | __/ _ \| '_ \ / _` / __\ \ / / _` |/ _`

|  _  |  __/ | | (_) |_| | || (_) | |_) | (_| \__ \\ V / (_| | (_|

|_| |_|\___|_|_|\___/(_)  \__\___/| .__/ \__,_|___/ \_/ \__, |\__,_

                                  |_|                   |___/

     _            _               _

  __| | ___   ___| | _____ _ __  |

 / _` |/ _ \ / __| |/ / _ \ '__| |

| (_| | (_) | (__|   <  __/ |    |_

 \__,_|\___/ \___|_|\_\___|_|    (_)




4

curl localhost:8080/test.html

Test Web page

// add로 호스트에 있는것을 컨테이너에 추가한 결과이다.



5

허용 확인 ?

도커 Proxy가 만들어진다.


ps -ef |grep proxy

root       18221    2482  0 13:44 ?        00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8080 -container-ip 172.17.0.2 -container-port 80

root       18226    2482  0 13:44 ?        00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip :: -host-port 8080 -container-ip 172.17.0.2 -container-port 80

root       18385    1282  0 13:49 pts/0    00:00:00 grep --color=auto proxy



6

8080 으로 시도하면,  컨테이너 80으로 접속


 iptables -t nat -S |grep 8080

-A DOCKER ! -i docker0 -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80



7

 iptables -t filter -S |grep 80

-A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 80 -j ACCEPT





<11> 도커 이미지  업로드를 위해 태그 달기



1

이미지 이름 확인 과 변경



docker images

REPOSITORY   TAG       IMAGE ID       CREATED         SIZE

hello        1         78236e8ceba0   9 minutes ago   222MB



2

이름 변경 ?

hello 1 을 topasvgahello:1 으로 변경해 보기


docker tag hello:1   masterseo11/topasvgahello:1

docker tag hello:1   도커허브 계정 / 이름 :1


root@ip-10-10-10-152:~/dockerfile# docker tag hello:1   masterseo11/topasvgahello:1



3

docker images

root@ip-10-10-10-152:~/dockerfile# docker images

REPOSITORY                  TAG       IMAGE ID       CREATED          SIZE

masterseo11/topasvgahello   1         592872f2bddc   15 minutes ago   222MB





<12> 도커 허브 계정생성과 로그인


도커 허브에 이미지를 올려서 사용하자!



1

사이트 접속

가입



2

docker login

Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.

Username:  masterseo11-g1002!

Password:


root@ip-10-10-10-152:~/dockerfile# docker images

REPOSITORY        TAG       IMAGE ID       CREATED          SIZE

hello             1         592872f2bddc   11 minutes ago   222MB

topasvgahello     1         592872f2bddc   11 minutes ago   222MB

ubuntu            14.04     13b66b487594   2 months ago     197MB

docker/whalesay   latest    6b362a9f73eb   6 years ago      247MB




<13>  push


도커 허브에 올리기?


만들고, 태그를 변경한 이미지를  Docker resistry 올리기


docker push masterseo11/topasvgahello:1



이미지 출처

http://erick.matsen.org/2018/04/19/docker.html




<14> 도커 허브에  이미지 올라간것  확인


도커허브 접속해서 확인하자


https://hub.docker.com/

Username:  masterseo11-g1002!




<15> 로컬에 있는 이미지  삭제하고 도커 이미지 실행해보자.


없으면 레파지토리에서  가져오는데, 제대로 가져 오는지 확인하는 것이다.



1

docker images



2

이미지 까지 전체 모두 삭제하기

docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q) -f && docker rmi $(docker images -q) -f


docker ps -a

docker images



<16>  도커 이미지 실행시키기, 로컬에 이미지가 없으면  레파지토리에서 가져옴


도커 허브에 올라간 이미지를 다른곳에서도 다운 받을수 있게 되었다!!!


1

docker run -d -p 8080:80 --name webserver masterseo11/topasvgahello:1

Unable to find image 'masterseo11/topasvgahello:1' locally

1: Pulling from masterseo11/topasvgahello

2e6e20c8e2e6: Pull complete

0551a797c01d: Pull complete

512123a864da: Pull complete

78c2f4a1b485: Pull complete

72dbc47708ba: Pull complete

fea73ff367f9: Pull complete

25fcbb10d6ac: Pull complete




<17> 확인


curl localhost:8080




<18>  모든 컨테이너 삭제


docker ps -a

docker images


docker rm $(docker ps -aq) -f

docker rmi $(docker images -q) -f




<19> 개인 정리


도커 파일로 컨테이너를 만들수 있게 되었다!!

도커 실행과 push등 알수 있게 되었다.

도커 허브에 이미지를 올려서 다른곳에서 사용할수 있게 되었다.




<20>  AWS 사이트  도커 이미지 만드는 예제



1

https://docs.aws.amazon.com/ko_kr/AmazonECS/latest/developerguide/docker-basics.html



2

AWS ECS 참고

https://brunch.co.kr/@topasvga/1363







다음 공부 도커 시작


https://brunch.co.kr/@topasvga/1646



감사합니다.


                    

매거진의 이전글  쿠버5탄-1. 도커 몰아보기 - 2022
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari