docker volumne이란?

  1. Docker에서 볼륨(Volume)은 컨테이너와 호스트 간, 컨테이너간의 데이터를 공유할수 있음
  2. 컨테이너의 상태가 갑자기 중단되어도  volumne을 통해 데이터가 보존될 수 있다.
  3. 예를들어 호스트 시스템(우분투)에서 실행했을때, /home/legoking/logs 를 docker container의 /var/lib/logs로 마운트,
    따라서 컨테이너가 중단 돼도 , 그 기록이 로그에 남게됨. 호스트 폴더, 컨테이너 폴더의 변화는 서로에게 영향을끼침
    (영향의 정도는 속성을 어떻게 설정하는지(읽기전용, 읽기쓰기 등)에 따라 조금씩 다름)

docker volumne 선언 방식

  1. host volumes
    docker run -v 호스트:컨테이너
    예) docker run -v  /home/본인id/logs:/var/lib/airflow/logs

  2. anonymous volumes
    docker run -v 컨테이너
    예) docker run -v  /var/lib/airflow/logs
    docker file에 사용되는 방식으로,호스트쪽에 액세스되지는 않지만 재시작해도 유지됨

  3. named volumes
    docker run -v name:컨테이너
    예) docker run -v  name:/var/lib/airflow/logs
    가장 선호되는 방식. 하나의 volume을 다수의 컨테이너에 공유하는 것도 가능(docker-compose에 쓰임)

    +docker compose 란?
    다수의 container로 구성된 소프트웨어를, 도커 환경에서 자유롭게 실행하고 관리할수 있게하는 툴

    + dockerfile 에도 volume이 있지만, 3가지중  anonymous volumes만 사용가능.
    docker-compose에서는 모두 사용 가능해 보통 여기서 선언한다. 

    +volume을 읽기전용(readonly)으로 지정하고 싶다면?
    name : /var/lib/mysql/data:ro

 

docker volume이 없을때의 위험성

  1. nginx를 실행.  nginx란?
    경량화된 웹서버. 주로 로드밸런서로 쓰임
    + 로드밸런서 : 트래픽 부하를 분산함으로써 서버 과부하를 방지하고, 장애 시 특정 서버에 대한 요청을 다른 서버로 전환하여 서비스의 안정성을 보장

  2. docker run -d --name=nginx -p 8081:80 nginx
  3. 브라우저 방문: http://localhost:8081/
     이 내용을 고쳐보려함

  4. docker exec --user=root -it nginx sh
    1) apt update
    2) apt install nano
    3) nano /usr/share/nginx/html/index.html 편집기 접속후 내용 수정 해봄
    welcome to nginx -> welcome to docker volumn 바뀐것 확인

    4) 컨테이너 삭제 해보자
    docker stop nginx, docker rm nginx 이후 다시 처음부터 수행
  5. docker restart nginx

    내용 확인시 수정했던 내용이 원상복구 된것을 확인-> 따라서 볼륨이 필요하다

 

 


이번엔 바뀌지 않게 볼륨 제작해서 다시 해보자 !
연결방식 : docker run -v 호스트:컨테이너 

  1. 우선 html 폴더를 만들고, index.html, test.html 파일(내용변경 확인에 사용할 페이지들) 제작
  2. 우선 mkdir html로 html 폴더를 만들고
  3. vim index.html 로 만들고 입력  <h1>Hello from Docker Volume!!</h1> 
    +모르겠다면 vim 편집기 사용방법 검색 
  4. vim test.html 로 만들고 입력  <h1> Testing . . .</h1>
  5. 기존에 있던 컨테이너 지우고
    weare@DESKTOP-BE1I4GE:~/html$ docker stop nginx
    nginx
    weare@DESKTOP-BE1I4GE:~/html$ docker rm nginx
    nginx
  6. 현재 호스트 위치 찾아냄
    weare@DESKTOP-BE1I4GE:~/html$ pwd
    /home/weare/html
    컨테이너 위치
    /usr/share/nginx/html
  7. ls -tl /Users/jobox/Downloads/grepp/kdt/nginx/html
    (index.html, test.html 파일 있어야함)
  8. docker run -p 8081:80 -d --name nginx_demo -v
    /Users/jobox/Downloads/grepp/kdt/nginx/html:/usr/share/nginx/html
  9. 볼륨 만들고 다시 연결
    docker run -p 8081:80 --name nginx -v /home/weare/html:/usr/share/nginx/html nginx
  10. 잘 연결됐는지 접속 시도 해봄 http://localhost:8081/test.html
  11. test.html 내용 수정하고 브라우저 재방문
  12. 컨테이너 멈추고 삭제
    weare@DESKTOP-BE1I4GE:~/html$ docker stop nginx
    nginx
    weare@DESKTOP-BE1I4GE:~/html$ docker rm nginx
    nginx

  13. 다시 접속해보면 내용이 유지 돼있음

 

docker volume을 airflow에서 docker-compose.yml에서 사용한 예

docker 명령 정리

  • docker image 관련
    1) docker build --platform=linux/amd64-t legoking/hangman
    2) docker images : 현재 시스템에 설치된 모든 Docker 이미지를 나열
    3) docker image ls : 위와 같음
    4) docker rmi : Docker 이미지를 삭제하는 명령
    5) docker image rm : Docker 이미지를 삭제하는 명령(쓰이고 있으면 중지하고 삭제해야함)

  • docker hub 관련
    1) docker login -u 본인id -p 본인pw
    2) docker pull 본인id/hangman 
    3) docker push 본인id/hangman

  • docker container 관련
    1) `docker create`:
       - Docker 컨테이너를 생성하지만 시작하지 않습니다. 생성된 컨테이너는 `docker start` 명령을 사용하여 나중에 시작할 수 있습니다.
    2) `docker run --name -p -v 이미지이름`:
       - Docker 컨테이너를 생성하고 실행합니다. `--name` 옵션으로 컨테이너에 이름을 할당하고, `-p` 옵션으로 포트를 매핑하며, `-v` 옵션으로 볼륨을 설정합니다. ( 컨테이너  id 대신 name을 사용할수 있음)
    3) `docker ps`:
       - 현재 실행 중인 Docker 컨테이너를 나열합니다.
    4) `docker ps -a`:
       - 모든 Docker 컨테이너를 나열합니다. 실행 중인 것 뿐만 아니라 종료된 컨테이너도 포함합니다.
    5) `docker ps -q`:
       - 실행 중인 Docker 컨테이너의 컨테이너 ID만을 나열합니다.
    6) `docker stop 컨테이너이름 or id`:
       - 실행 중인 Docker 컨테이너를 중지합니다.
    7) `docker start 컨테이너이름 or id`:
       - 중지된 Docker 컨테이너를 시작합니다.
    8) `docker restart 컨테이너이름 or id`:
       - Docker 컨테이너를 재시작합니다.
    9) `docker kill 컨테이너이름 or id`:
       - 실행 중인 Docker 컨테이너를 강제로 종료합니다.
    10) `docker pause 컨테이너이름 or id`:
        - 실행 중인 Docker 컨테이너를 일시 중지합니다.
    11) `docker unpause 컨테이너이름 or id`:
        - 중지된 Docker 컨테이너의 일시 중지를 해제합니다.
    12) `docker rm 컨테이너이름 or id`:
        - 종료된 Docker 컨테이너를 삭제합니다.
    13) docker logs -f 컨테이너이름 or id
        - Docker 컨테이너의 로그를 실시간( -f )으로 출력
    14) docker logs --tail 100 컨테이너이름 or id
        - 로그를 마지막에서부터 최대 100줄까지 출력
    15) docker run --name=hangman 본인id/hangman
        - 만들고 실행, 이름을 hangman으로 지정
    16) docker exec hangman cat/etc/hosts
        - 이 미 실행 중인 컨테이너 내에서 추가적인 명령을 실행
    17)  docker run -d 본인id /hangman
       -d 백그라운드에서 컨테이너실행
      예) a043d40*****
    18) docker attach a043
       - 이미 실행 중인 Docker 컨테이너에 접속하여 해당 컨테이너의 터미널에 연결하는 명령어
  • docker volume 관련
    1) docker volume ls : 볼륨 리스트
    2) docker volume  rm : 볼륨 삭제
    3) docker volume  prune : 사용되지 않는 모든 Docker 볼륨을 제거
    4) docker volume  inspect : 하나 이상의 Docker 볼륨에 대한 세부 정보를 제공

  1. 준비할것
  • github 계정
  • 깃헙계정에 hangman repo 생성
  • docker hub 계정
  • docker 설치
  • 무료서버 사이트 https://labs.play-with-docker.com/  docker hub 계정과 연동

실습과정

  1. 깃허브 레포에 코드 푸쉬, 깃허브 액션을 동작시킴
  2. 테스트 돌려보고,
  3. docker 이미지빌드, 도커 허브에 업로드 수행

 

행맨 레포 구조 설명

  • 전체구조
  • app.py
    브라우저를 통해 지정된 포트로 요청이 들어오면, 행맨 app을 실행시켜줌
  • requirements.txt

 


행맨 다운로드(무료 서버이용)

  1. https://labs.play-with-docker.com/ 접속 후 도커 연동 로그인, add new instance (4시간 무료서버 시작)
  2. 깃에서 컴퓨터로 행맨 다운
    git clone https://github.com/learndataeng/hangman_web.git
    Cloning into 'hangman_web'...
    remote: Enumerating objects: 25, done.
    remote: Counting objects: 100% (10/10), done.
    remote: Compressing objects: 100% (6/6), done.
    remote: Total 25 (delta 7), reused 4 (delta 4), pack-reused 15
    Receiving objects: 100% (25/25), 8.52 KiB | 8.52 MiB/s, done.
    Resolving deltas: 100% (10/10), done.

  3. 깃허브 로그인 id, pw 입력(안나올수도 있음)

  4. 행맨 폴더로 이동
    cd hangman_web

  5. requirements.txt 내부 모듈들 설치 명령
    pip3 install -r requirements.txt
    ERROR: Could not find a version that satisfies the requirement requirements.txt (from versions: none)
    HINT: You are attempting to install a package literally named "requirements.txt" (which cannot exist). Consider using the '-r' flag to install the packages listed in requirements.txt
    ERROR: No matching distribution found for requirements.txt

    [notice] A new release of pip is available: 23.2.1 -> 23.3.2
    [notice] To update, run: python.exe -m pip install --upgrade pip
    pip 버전 업그레이드 요청

  6. pip 버전 업그레이드
    python.exe -m pip install --upgrade pip
    Requirement already satisfied: pip in c:\users\weare\appdata\local\programs\python\python312\lib\site-packages (23.2.1)
    Collecting pip
      Obtaining dependency information for pip from https://files.pythonhosted.org/packages/15/aa/3f4c7bcee2057a76562a5b33ecbd199be08cdb4443a02e26bd2c3cf6fc39/pip-23.3.2-py3-none-any.whl.metadata
      Downloading pip-23.3.2-py3-none-any.whl.metadata (3.5 kB)
    Downloading pip-23.3.2-py3-none-any.whl (2.1 MB)
       ---------------------------------------- 2.1/2.1 MB 11.2 MB/s eta 0:00:00
    Installing collected packages: pip
      Attempting uninstall: pip
        Found existing installation: pip 23.2.1
        Uninstalling pip-23.2.1:
          Successfully uninstalled pip-23.2.1
    Successfully installed pip-23.3.2

  7. 다시 requirements.txt 내부 모듈들 설치 명령
    pip3 install -r requirements.txt
    Collecting Flask==2.3.2 (from -r requirements.txt (line 1))
      Downloading Flask-2.3.2-py3-none-any.whl (96 kB)
         ---------------------------------------- 96.9/96.9 kB 308.3 kB/s eta 0:00:00
    Collecting Flask-HTTPAuth==4.5.0 (from -r requirements.txt (line 2))
      Downloading Flask_HTTPAuth-4.5.0-py3-none-any.whl (6.7 kB)
    Collecting Flask-Login==0.6.2 (from -r requirements.txt (line 3))
      Downloading Flask_Login-0.6.2-py3-none-any.whl (17 kB)
    (중략)
    extensions, MarkupSafe, itsdangerous, greenlet, colorama, blinker, Werkzeug, SQLAlchemy, Jinja2, click, Flask, Flask-SQLAlchemy, Flask-Login, Flask-HTTPAuth
    Successfully installed Flask-2.3.2 Flask-HTTPAuth-4.5.0 Flask-Login-0.6.2 Flask-SQLAlchemy-3.0.3 Jinja2-3.1.2 MarkupSafe-2.1.3 SQLAlchemy-2.0.23 Werkzeug-3.0.1 blinker-1.7.0 click-8.1.7 colorama-0.4.6 greenlet-3.0.3 itsdangerous-2.1.2 typing-extensions-4.9.0

  8. 외부 접근시 행맨 실행되게 세팅
    python3 -m flask run --host=0.0.0.0 --port=4000

    + python3 -m flask run: Flask 애플리케이션을 실행합니다
    --host=0.0.0.0: 서버를 모든 네트워크 인터페이스에 바인딩하여 외부에서 접근할 수 있도록 합니다.
    --port=4000: 서버를 4000 포트에서 실행합니다.
  9. 행맨 화면이 나오지 않는다. 왜일까? 
    -> 포트 설정을 안해줬기 때문이다. (open port 버튼 클릭후 4000으로 맞춰줌)

 

로컬에서 그대로 진행해보기(우분투로)

  1. 우분투에서 위의 과정을 그대로 반복하면 실행되지 않는다.
  2. 문제 : 컨테이너 내부앱은 포트번호를 4000으로 맞춰도, 컨테이너 밖에서는 실행되지 않는다. 
  3. 해결 방법 : 컨테이너 실행시 내부 4000포트를 밖에서도 4000으로 보이게 세팅(포트포워딩 -p)
  4. 포트 포워딩을 위해 명령어를 바꿔야 한다. 이번에는 다운받은걸 올리는게 아닌, 직접 도커 이미지를 제작해보자.

 

도커 파일 제작

  1. 우선 도커 이미지를 제작하려면, 도커파일을 제작해야한다.
  2. dockerfile.txt 만들기
    weare@DESKTOP-BE1I4GE:~/hangman_web$ touch dockerfile

  3. 내용 넣기 위해 nano 편집기 오픈
    weare@DESKTOP-BE1I4GE:~/hangman_web$ nano dockerfile

  4. 도커파일 내용 복사 붙여넣기-> ctr+x, y 손떼고 enter(저장완료)
    # 베이스 이미지로부터 시작
    FROM python:3.8-slim-buster

    # 이미지를 유지보수하는 담당자의 정보를 라벨로 추가
    LABEL maintainer="wearelego@naver.com"

    # 작업 디렉토리를 /app으로 설정
    WORKDIR /app

    # 현재 디렉토리에 있는 app.py 파일을 이미지의 /app 디렉토리로 복사
    COPY app.py ./

    # 현재 디렉토리에 있는 requirements.txt 파일을 이미지의 /app 디렉토리로 복사
    COPY requirements.txt ./

    # requirements.txt 파일에 명시된 의존성 패키지를 설치
    RUN pip3 install -r requirements.txt

    # 컨테이너 내부에서 사용할 포트를 노출
    EXPOSE 4000

    # 컨테이너가 시작될 때 실행되는 명령을 설정
    CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0", "--port=4000"]
  5. 도커파일 이미지 제작(빌드) 
    weare@DESKTOP-BE1I4GE:~/hangman_web$ docker build -t 도커허브이름/hangman .
    [+] Building 17.7s (11/11) FINISHED                                                                                                                     docker:default
     => [internal] load .dockerignore                                                                                                                                 0.1s
    (중략)
     => [2/5] WORKDIR /app                                                                                                                                            0.8s
     => [3/5] COPY app.py ./                                                                                                                                          0.1s
     => [4/5] COPY requirements.txt ./                                                                                                                                0.1s
     => [5/5] RUN pip3 install -r requirements.txt                                                                                                                    6.3s
     => exporting to image                                                                                                                                            0.4s
     => => exporting layers                                                                                                                                           0.4s
     => => writing image sha256:f63deabbaf881311d0ba660aed5ab2f313fabdfc10b23603750518663ab7538c                                                                      0.0s
     => => naming to docker.io/legoking/hangman

    + 만약 맥북 m1칩을 쓰고 있다면 : docker build --platform=linux/amd64 -t 도커허브이름/hangman 를 입력해야함

  6. 위에서 컨테이너 내부 포트를 4000으로 설정했었지만 (EXPOSE 4000) 외부와도 4000으로 포트포워딩(-p)을 해야함
    weare@DESKTOP-BE1I4GE:~/hangman_web$ docker run -p 4000:4000 legoking/hangman
     * Debug mode: off
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
     * Running on all addresses (0.0.0.0)
     * Running on http://127.0.0.1:4000
     * Running on http://172.17.0.2:4000
    Press CTRL+C to quit
    172.17.0.1 - - [24/Dec/2023 08:49:32] "GET / HTTP/1.1" 200 -
    172.17.0.1 - - [24/Dec/2023 08:49:32] "GET /favicon.ico HTTP/1.1" 404 -

  7. 위의 주소 http://127.0.0.1:4000을 인터넷 창에 붙여넣기 하면 , 이제 행맨이 잘 출력된다.
  8. 작동중인 컨테이너 목록 확인
    weare@DESKTOP-BE1I4GE:~$ docker ps
    CONTAINER ID   IMAGE                  COMMAND                  CREATED         STATUS                             PORTS                    NAMES
    9000ad0e7bf3   legoking/hangman       "python3 -m flask ru…"   8 seconds ago   Up 7 seconds                       0.0.0.0:4000->4000/tcp   stupefied_lalande

  9. 강제로 중단해보기
    weare@DESKTOP-BE1I4GE:~$ docker stop 9000ad0e7bf3
    9000ad0e7bf3

  10. 다른 작업도 할수있게 백그라운드에서 실행( -d )해보기
    weare@DESKTOP-BE1I4GE:~/hangman_web$ docker run -p 4000:4000 -d legoking/hangman
    96d86dd5c59aa891418c36c568813131c94f9c24168a2a8e6b0b70948d515ba4
    weare@DESKTOP-BE1I4GE:~/hangman_web$ docker ps
    CONTAINER ID   IMAGE                  COMMAND                  CREATED         STATUS                      PORTS                    NAMES
    96d86dd5c59a   legoking/hangman       "python3 -m flask ru…"   6 seconds ago   Up 4 seconds                0.0.0.0:4000->4000/tcp   gifted_blackburn


제작한 도커파일 도커허브에 업로드

  • weare@DESKTOP-BE1I4GE:~$ docker push legoking/hangman
    Using default tag: latest
    The push refers to repository [docker.io/legoking/hangman]
    dc98c5bce72d: Pushed
    4d02b9d087c0: Pushed
    b3a0754f0b99: Pushed
    b9318d6e19ee: Pushed
    e6c5004ee77f: Mounted from library/python
    997b8e79e84f: Mounted from library/python
    3054512b6f71: Mounted from library/python
    ae2d55769c5e: Mounted from library/python
    e2ef8a51359d: Mounted from library/python
    latest: digest: sha256:5423af489767acf74d147fd86b81d6683b8c0c1b057f86b9007fa5115a916d29 size: 2203

 

 

목표 : mysql 서버를 다운받고 이것저것 작업해본다

어디서 : 우분투, cmd 등에서
어떻게 : 리눅스 명령어를 입력해서

1. MySQL 서버 다운(진한글씨만 입력하는 부분)

  • weare@DESKTOP-BE1I4GE:~$ docker pull mysql/mysql-server:8.0
    8.0: Pulling from mysql/mysql-server
    6a4a3ef82cdc: Pull complete
    5518b09b1089: Pull complete
    b6b576315b62: Pull complete
    349b52643cc3: Pull complete
    abe8d2406c31: Pull complete
    c7668948e14a: Pull complete
    c7e93886e496: Pull complete
    Digest: sha256:d6c8301b7834c5b9c2b733b10b7e630f441af7bc917c74dba379f24eeeb6a313
    Status: Downloaded newer image for mysql/mysql-server:8.0
    docker.io/mysql/mysql-server:8.0

 

2. 다운받은 이미지(mysql 서버)를 docker 컨테이너 내에서 실행

  • weare@DESKTOP-BE1I4GE:~$ docker run --name=mysql_container mysql/mysql-server:8.0
    [Entrypoint] MySQL Docker Image 8.0.32-1.2.11-server
    [Entrypoint] No password option specified for new database.
    [Entrypoint]   A random onetime password will be generated.
    [Entrypoint] Initializing database
    2023-12-24T04:29:20.955914Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
    2023-12-24T04:29:20.956019Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.32) initializing of server in progress as process 18
    2023-12-24T04:29:20.976964Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
    2023-12-24T04:29:22.388125Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
    2023-12-24T04:29:26.271228Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
    [Entrypoint] Database initialized
    2023-12-24T04:29:34.688538Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
    2023-12-24T04:29:34.689584Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.32) starting as process 61
    2023-12-24T04:29:34.707921Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
    2023-12-24T04:29:34.995939Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
    2023-12-24T04:29:35.466111Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
    2023-12-24T04:29:35.466167Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
    2023-12-24T04:29:35.491364Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
    2023-12-24T04:29:35.491546Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.32'  socket: '/var/lib/mysql/mysql.sock'  port: 0  MySQL Community Server - GPL.
    Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
    Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it.
    Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it.
    Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
    Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
    [Entrypoint] GENERATED ROOT PASSWORD: +4ua5uBgh#vIo=8?;?88JCueH/q61o0/

    [Entrypoint] ignoring /docker-entrypoint-initdb.d/*

    2023-12-24T04:29:37.735110Z 11 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.32).
    2023-12-24T04:29:41.845476Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.32)  MySQL Community Server - GPL.
    [Entrypoint] Server shut down
    [Entrypoint] Setting root user as expired. Password will need to be changed before database can be used.

    [Entrypoint] MySQL init process done. Ready for start up.

    [Entrypoint] Starting MySQL 8.0.32-1.2.11-server
    2023-12-24T04:29:42.927093Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
    2023-12-24T04:29:42.928040Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.32) starting as process 1
    2023-12-24T04:29:42.933698Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
    2023-12-24T04:29:43.129131Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
    2023-12-24T04:29:43.386345Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
    2023-12-24T04:29:43.386395Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
    2023-12-24T04:29:43.436052Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
    2023-12-24T04:29:43.436145Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.32'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server - GPL.
  • 정상 실행 중 -> 터미널 따로 하나 열어야함

3. mysql root의 비밀번호 찾아보기

  • MySQL 컨테이너의 로그에서 표준에러(2)를 표준 출력(1)으로 가져오고, 이를 다시 grep GENERATED 명령어로 전달하여 "GENERATED" 라는 문자열이 포함된 라인을 찾습니다.
    weare@DESKTOP-BE1I4GE:~$ docker logs mysql_container 2>&1|grep GENERATED
    [Entrypoint] GENERATED ROOT PASSWORD: +4ua5uBgh#vIo=8?;?88JCueH/q61o0/
    +A | B : A명령어를 B에 전달
    + & : 리다이렉트하는 역할

4. 구한 비밀번호 이용해서 mysql shell 열어보기

  • weare@DESKTOP-BE1I4GE:~$ docker exec -it mysql_container mysql -uroot -p
    • it  : Docker 컨테이너를 interactive(대화형) 모드로 실행하고 터미널에 연결할 때 사용
    • docker exec: 이 명령은 실행 중인 컨테이너 내에서 명령을 실행할 수 있게 합니다.
    • -it: 이 옵션들은 대화형 터미널을 사용하여 명령을 실행할 수 있게 합니다.
    • mysql_container: 이는 명령을 실행할 MySQL 컨테이너의 이름입니다.
    • mysql -uroot -p: 이는 MySQL 명령행 클라이언트 명령입니다. 지정된 사용자 (-uroot는 root 사용자를 나타냄)로 MySQL 서버에 연결하고 비밀번호를 입력하도록 요청합니다.
      -p 는 비밀번호를 요청

    Enter password:
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 24
    Server version: 8.0.32

    Copyright (c) 2000, 2023, Oracle and/or its affiliates.

    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.

    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

    mysql>

5. 임시비밀번호에서 원하는 비밀번호로 변경 

  • mysql> show databases;
    ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

    mysql> alter USER root@localhost IDENTIFIED BY '새비밀번호';
    Query OK, 0 rows affected (0.02 sec)

6. 데이터 베이스 구경

  1. 데이터 베이스가 4개 저장돼있는것 확인
    mysql> show databases
        -> exit
        -> show databases;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'exit
    show databases' at line 2
    mysql> show databases;
    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | mysql              |
    | performance_schema |
    | sys                |
    +--------------------+
    4 rows in set (0.01 sec)

  2. 데이터 베이스 mysql로 선택
    mysql> use mysql;
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A

    Database changed

  3. mysql 내부 테이블 보기
    mysql> show tables;
    +------------------------------------------------------+
    | Tables_in_mysql                                      |
    +------------------------------------------------------+
    | columns_priv                                         |
    | component                                            |
    | db                                                   |
    | default_roles                                        |
    | engine_cost                                          |
    | func                                                 |
    | general_log                                          |
    | global_grants                                        |
    | gtid_executed                                        |
    | help_category                                        |
    | help_keyword                                         |
    | help_relation                                        |
    | help_topic                                           |
    | innodb_index_stats                                   |
    | innodb_table_stats                                   |
    | ndb_binlog_index                                     |
    | password_history                                     |
    | plugin                                               |
    | procs_priv                                           |
    | proxies_priv                                         |
    | replication_asynchronous_connection_failover         |
    | replication_asynchronous_connection_failover_managed |
    | replication_group_configuration_version              |
    | replication_group_member_actions                     |
    | role_edges                                           |
    | server_cost                                          |
    | servers                                              |
    | slave_master_info                                    |
    | slave_relay_log_info                                 |
    | slave_worker_info                                    |
    | slow_log                                             |
    | tables_priv                                          |
    | time_zone                                            |
    | time_zone_leap_second                                |
    | time_zone_name                                       |
    | time_zone_transition                                 |
    | time_zone_transition_type                            |
    | user                                                 |
    +------------------------------------------------------+
    38 rows in set (0.00 sec)

7. 사용한 명령어 몇개 살펴보기

docker run --name : 사용하기 편한 컨테이너 아이디 지정
docker logs : container쪽에서 생성된 stdout, stderr단의 로그를 읽어옴, --follow 사용시 로그 계속적으로 스트리밍됨

목표 : docker 컨테이너에 ubuntu를 받고 이것 저것 만져본다.
어디서 : 우분투, cmd 등 프로그램에서
어떻게: 리눅스 명령어를 입력해서

리눅스 커널과 배포판

  • 배포판의 종류 
    우분투, 데비안, 알파인, 페도라, 센트os 등등
  • 배포판에 따른 패키지 매니저
    파이썬 : 우분투(apt, pip) , 데비안 (apt, pip), 알파인리눅스 (apt, pip), 페도라(dnf,pip), 센트os(yum,pip), 
    JavaScript(Node.js)  : npm, yarn
    C# 등의 언어 : NuGut

실습(진한글씨만 입력하는것)

  • 우분투를 실행 (로컬에 없기 때문에 알아서 다운받는다)
    weare@DESKTOP-BE1I4GE:~$ docker run ubuntu
    Unable to find image 'ubuntu:latest' locally
    latest: Pulling from library/ubuntu
    a48641193673: Pull complete
    Digest: sha256:6042500cf4b44023ea1894effe7890666b0c5c7871ed83a97c36c76ae560bb9b
    Status: Downloaded newer image for ubuntu:latest
    unable to upgrade to tcp, received 404

  • 도커컨테이너 목록중에 우분투가 실행되는지 확인
    weare@DESKTOP-BE1I4GE:~$ docker ps
    CONTAINER ID   IMAGE                  COMMAND                  CREATED        STATUS                      PORTS                    NAMES
    실행 안된다. 그 이유는 동작완료하고 동작을 유지하지 않았기 때문

  •  -a를 추가해 완료된 도커 컨테이너도 확인
    weare@DESKTOP-BE1I4GE:~$ docker ps -a
    CONTAINER ID   IMAGE                  COMMAND                  CREATED         STATUS                             PORTS                    NAMES
    d70342287a9a   ubuntu                 "/bin/bash"              2 minutes ago   Exited (0) 2 minutes ago                                    stoic_lamarr

  • ubuntu 컨테이너 실행 및 nano 에디터 접속 시도
    weare@DESKTOP-BE1I4GE:~$ docker run -it ubuntu
    root@8334f78ad747:/# nano
    bash: nano: command not found

    root@8334f78ad747:/# apt install nano
    Reading package lists... Done
    Building dependency tree... Done
    Reading state information... Done
    Package nano is not available, but is referred to by another package.
    This may mean that the package is missing, has been obsoleted, or
    is only available from another source

    E: Package 'nano' has no installation candidate
    root@8334f78ad747:/# apt update
    Get:1 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
    Get:2 http://archive.ubuntu.com/ubuntu jammy InRelease [270 kB]
    Get:3 http://security.ubuntu.com/ubuntu jammy-security/multiverse amd64 Packages [44.0 kB]
    Get:4 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [119 kB]
    Get:5 http://security.ubuntu.com/ubuntu jammy-security/universe amd64 Packages [1046 kB]
    Get:6 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [109 kB]
    Get:7 http://archive.ubuntu.com/ubuntu jammy/universe amd64 Packages [17.5 MB]
    Get:8 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64 Packages [1572 kB]
    Get:9 http://security.ubuntu.com/ubuntu jammy-security/main amd64 Packages [1326 kB]
    Get:10 http://archive.ubuntu.com/ubuntu jammy/multiverse amd64 Packages [266 kB]
    Get:11 http://archive.ubuntu.com/ubuntu jammy/main amd64 Packages [1792 kB]
    Get:12 http://archive.ubuntu.com/ubuntu jammy/restricted amd64 Packages [164 kB]
    Get:13 http://archive.ubuntu.com/ubuntu jammy-updates/restricted amd64 Packages [1602 kB]
    Get:14 http://archive.ubuntu.com/ubuntu jammy-updates/universe amd64 Packages [1305 kB]
    Get:15 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages [1599 kB]
    Get:16 http://archive.ubuntu.com/ubuntu jammy-updates/multiverse amd64 Packages [49.8 kB]
    Get:17 http://archive.ubuntu.com/ubuntu jammy-backports/main amd64 Packages [50.4 kB]
    Get:18 http://archive.ubuntu.com/ubuntu jammy-backports/universe amd64 Packages [28.1 kB]
    Fetched 28.9 MB in 1min 37s (300 kB/s)
    Reading package lists... Done
    Building dependency tree... Done
    Reading state information... Done
    All packages are up to date.

  • ubuntu에 nano를 설치해봄
    root@8334f78ad747:/# apt install nano
    Reading package lists... Done
    Building dependency tree... Done
    Reading state information... Done
    Suggested packages:
      hunspell
    The following NEW packages will be installed:
      nano
    0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
    Need to get 280 kB of archives.
    After this operation, 881 kB of additional disk space will be used.
    Get:1 http://archive.ubuntu.com/ubuntu jammy/main amd64 nano amd64 6.2-1 [280 kB]
    Fetched 280 kB in 1s (198 kB/s)
    debconf: delaying package configuration, since apt-utils is not installed
    Selecting previously unselected package nano.
    (Reading database ... 4393 files and directories currently installed.)
    Preparing to unpack .../archives/nano_6.2-1_amd64.deb ...
    Unpacking nano (6.2-1) ...
    Setting up nano (6.2-1) ...
    update-alternatives: using /bin/nano to provide /usr/bin/editor (editor) in auto mode
    update-alternatives: warning: skip creation of /usr/share/man/man1/editor.1.gz because associated file /usr/share/man/man1/nano.1.gz (of link group editor) doesn't exist
    update-alternatives: using /bin/nano to provide /usr/bin/pico (pico) in auto mode
    update-alternatives: warning: skip creation of /usr/share/man/man1/pico.1.gz because associated file /usr/share/man/man1/nano.1.gz (of link group pico) doesn't exist

  • nano 에디터 접속 해봄
    root@8334f78ad747:/# nano

  • nano 삭제
    root@8334f78ad747:/# apt remove nano
    Reading package lists... Done
    Building dependency tree... Done
    Reading state information... Done
    The following packages will be REMOVED:
      nano
    0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
    After this operation, 881 kB disk space will be freed.
    Do you want to continue? [Y/n] y
    (Reading database ... 4466 files and directories currently installed.)
    Removing nano (6.2-1) ...

실습 내용 : hello world 실행하기

1. 회원 등록 : https://hub.docker.com/

(id, pw 기억해놓것! 나중에 쓰임)

 

Docker Hub Container Image Library | App Containerization

Build and Ship any Application Anywhere Docker Hub is the world's easiest way to create, manage, and deliver your team's container applications. Create your account Signing up for Docker is fast and free. Continue with GoogleContinue with GitHubContinue wi

hub.docker.com

 

2. 레포 작성 : create repository -> hello-world-docker(레포이름) -> create

 

3. 무료 서버에서 도커 이미지 받는 실습 해보기
https://labs.play-with-docker.com/   login(도커허브 연동해 로그인) ->  ADD NEW INSTANCE 클릭

  • 아래 명령어 순서대로 입력
  • docker pull legoking/hello-world-docker
    이미지 받아옴
  • docker image ls
    이미지 받아졌는지 확인
  • docker run legoking/hello-world-docker
    실행해봄 (꼭 pull 안하고 이거만 써도 한번에 됨)

 

4. docker registry에 등록(로컬에 있을때)

  • docker tag A B : 레포의 이름을 A에서 B로 변경
    + tag는 기본값은 latest , ' : ' 뒤에 나타냄  
  • docker login~ : 도커에 id pw로 로그인 (로그인은 최초 1번만 필요)


5.결과 확인

6.docker 명령 정리

  • docker version
  • docker build -t 이미지이름:태그 . -> 현재 티렉토리(.)에 dockerfile을 사용해서 도커 이미지 빌드, -t 태그지정
  • docker push 이미지이름:태그
  • docker tag 소스이미지:태그 새이미지:새태그
  • docker pull 이미지이름:태그
  • docker run 옵션 이미지이름:태그
    옵션(p) 호스트 머신과 컨테이너 간의 포트를 매핑
    옵션(v)  호스트 머신의 디렉토리나 파일을 컨테이너에 매핑

5. docker run , docker exec

  • docker run은 새로운 컨테이너를 생성하고 실행하는 데 사용됨
  • docker exec는 이미 실행 중인 컨테이너 내에서 명령을 실행하는 데 사용됨
  • 두 명령 모두 --user root or -u root를 통해 루트 유저로 연결가능

docker 개발 프로세스

  • docker화 할 대상과 범위 선택 :  다수의 컴포넌트라면 각각 docker image가 필요할수 있음
  • docker 파일 : 기본적으로 텍스트 파일, 기본 소프트웨어(from), 어떤 프로그램 설치할건지(run), 어떻게 실행할건지
    예) 음식의 레시피, 계량법, 요리도구 까지 상세한 정보들 
  • docker 파일이 만들어지면 -> docker화 해서 -> image 제작


docker image 구성 요소

  • 기본 os(리눅스라면 우분투, 데비안 등) 같은 소프트웨어 실행환경
  • 소프트웨어 코드 및 소프트웨어 동작에 필요한 라이브러리
  • 파일 시스템 스냅샷 : 특정 시점의 상태를 캡처하여 백업, 데이터 손실을 방지하거나 롤백 및 테스트 목적으로 사용된다. 스텍화된 형태로 구현된다.
  • 환경 설정 변수 : 빌드할 때 변수, 실행할때 변수 (ENG, ARB 이후 더 설명)
  • 메타데이터 : 이미지 자체에 대한 정보( 버전, 작성자 등 설명)
  • docker image ls 명령어로 조회 가능
  • image를 다른환경에서 container를 통해 실행
    예) 에어프라이어용 냉동 식품 -> 각 집의 에어프라이어에서 조리 가능 


docker image 공유 하기

  • on-prem registry : 기업 내부에서 호스팅되는 도커 이미지 저장소로, 보안 및 데이터 제어를 강화하며 내부 네트워크에서 동작

  • cloud registry : 클라우드 플랫폼에서 제공되는 도커 이미지 저장소로, 확장성과 유연성을 제공하여 클라우드 기반 애플리케이션 배포에 적합 (docker hub가 유명)

docker hub

  • 도커 업계의 깃허브 느낌 , 전체 공유 부분공유 가능
  • 레포를 만들고 push , pull 등 가능하다. (docker 데스크탑과 연동)
  • 도커 이미지 만드는 과정(소스코드는 깃헙과 공유)
  • 만들고 나서는 도커허브 이용 

Docker desktop 설치링크 : http://docs.docker.com/get-docket 

 

필요한것 : 여유 램 4GB 이상, 윈도우 10 이상, Hyper-v와 container 기능 활성화, wsl 설치

 

설치 :  설정 기본 값으로 쭉쭉

 

정상설치 확인 : 

ㅋㅋ 별거 없어 ㅈㅅ

내가 만든 프로그램이 다른 컴퓨터에서는 안돌아간다면?

  1. 설치 과정에서 중요한 파일이 빠질수 있음
  2. 운영체제가 다르고, 다른 버전이 설치되면 라이브러리 버전간 호환이슈 발생

일정하게 똑같은 환경에서 만들어 주는법 (like 밀키트)

  1. 도커 이미지(모듈 버전등 환경변수)와, 도커 컨테이너(도커이미지+운영시스템) 필요
    예) 중화요리 밀키트(도커이미지)를 웍(도커 컨테이너) 에서 센불로 요리해야 제맛!

 

Virtual Machine(docker 등장 이전의 강자) 

  • 예 ) EC2가 대표적인 VM, 맥 컴퓨터 위에서 윈도우, 리눅스들 가상 운영체제를 돌리는 경우
  • VM 구조 : 호스트 os(macitosh) 위에 VM 관리 툴( hypervisors) 가 필요하고, 그 위에 운영체제
  • VM 장단점
    장점 : 독립적이고 분리된 공간 제공, 다수의 소프트를 각 VM에서 독립적으로 실행가능
    단점 : 각 os 별로 비용, VM끼리 cpu,램, 용량들을 나눠야 해서 성능이 떨어짐

 

 

docker container

  • docker의 운영체제는 일반 운영체제에 비해서 경량화 됌(필요한 만큼만 사용)

  • Docker 제작시 사용한 호스트 OS와, 그 컨테이너 가 호환되는 OS 
    맥 : 경량화 리눅스 / 윈도우 : 윈도우, 리눅스 / 리눅스 : 리눅스 only
    +리눅스는 어디서 만들든 다 사용할수 있음

  • 장점
    1) 각 컨테이너 별로 독립적이고 분리된 공간, 소프트 각각 실행도 가능
    2) 수십 수백 컨테이너 사용시 , 각각 따로 구현에 비해 자원소비가 적음
    3) 별도의 os 라이센스 비용 필요없고, 경량화 os라 빠르게 실행됨
  • 단점
    1) 많은 컨테이너 관리 쉽지 않음
    2) 컨테이너 제작 os, 동작 os 간의 호환성 이슈
    3) GUI 소프트 개발에 적합치 않음(VM이 더 적합)

건물에 월세 세입자를 구하는것 vs 에어비엔비로 호스트를 자주 유치하는것

 

+ Recent posts