.dockerignore 파일의 예

  • 예)

    *.pyc
    progect.lock.json
    bin/
    obj/
    .vs
    node_modules/

  • 개발 환경에서 사용되는 여러 파일이나 디렉토리, 특정 빌드 도구나 의존성 관리등 중간단계에서 생성된 파일들은 최종 빌드에는 필요없는 경우가 있다. 이들을 예외 없이 빌드한다면 이미지 크기를 늘리고 빌드 속도 저하를 가져온다.
  • .dockerignore 파일은 이런 파일들을 예외 처리해준다. 그럼으로서 이미지 크기를 줄이고 빌드 프로세스를 최적화할 수 있다.

비슷한 애들

  • .gitignore
  • .npmignore
  • .eslintignore
  • .hgignore

사용할 예제 : voting application

https://github.com/dockersamples/example-voting-app

 

GitHub - dockersamples/example-voting-app: Example distributed app composed of multiple containers for Docker, Compose, Swarm, a

Example distributed app composed of multiple containers for Docker, Compose, Swarm, and Kubernetes - GitHub - dockersamples/example-voting-app: Example distributed app composed of multiple containe...

github.com

 

실습 예제 파일을 깃 클론으로 받아옴

 

빌드 후 실행(하나하나 실행)

 

-> vote 시 정상 동작을 못한다. 아래 순서도를 보면 vote와 redis의 연결 부분에 문제가 있는것으로 보인다.

 


디테일한 문제점 분석

  1. vote에 로그인해서 redis로 신호(핑)을 날려보고 정상적으로 가는지 확인하면 된다.
    $ ping redis
    ping :cannot resolve redis: unknown host
    핑이 제대로 날라가지 않는다. (실제 연결이 안됨을 확인)
  2. db도 정상적인 값을 못받는듯 하다.
  3. db와 redis 의 연결에도 문제가 있어 보인다.

결론 : 컨테이너간 변수들이 전부 연결성에 문제가 있음을 추론할수있음.

 

해결방법 : 모든 컨테이너들을 --network mynetwork 로 묶어 연결

● 컨테이너를 다시 올리기 위해 초기화
docker container rm -f $(docker container ls -aq) 
● 네트워크 mynetwork 생성(존재한다면 지우고 다시 설치할것)
docker network create mynetwork
● docker run -d --name=redis --network mynetwork redis
● docker run -d --name=db -e POSTGRES_PASSWORD=password --network mynetwork postgres
● docker run -d --name=vote -p 5001:80 --network mynetwork vote 
● docker run -d --name=result -p 5002:80 --network mynetwork result 
● docker run -d --name=worker --network mynetwork worker

 


vote에서 redis 연결이 문제였으니 테스트 위해 vote쉘  접속(ping 모듈 설치위해 root로 접속)
+위에 순서도 참조 vote 다음이 redis이니까. vote에 접속해서 redis로 신호를 날려보는거임

  • weare@DESKTOP-BE1I4GE:~/example-voting-app$ docker exec -it --user root vote sh
    # apt update
  • # apt install iputils-ping
  • # ping redis (redis로 핑 날려봄)

 

정상 연결된 모습이다. 

'docker(도커) 및 쿠버네티스' 카테고리의 다른 글

docker-compose(명령어, yaml파일구조)  (0) 2023.12.29
.dockerignore 파일은 뭘까?  (1) 2023.12.28
docker 초기화(클린업)  (0) 2023.12.27
docker volume  (1) 2023.12.27
docker 명령어 모음  (0) 2023.12.27

컨테이너 하나하나 삭제하기

  1. docker container ls
  2. docker container rm -f 컨테이너id1 컨테이너id2 ....
  3. container 중단후 image 삭제

컨테이너  한번에 삭제하기

  1. 한번에 docker container rm -f$(docker container ls -aq) 로 삭제
    • docker container rm: Docker 컨테이너를 제거하는 명령어입니다.
    • -f: 강제로 제거하는 옵션입니다. 컨테이너가 실행 중이더라도 강제로 중지하고 삭제합니다.
    • $(): 명령어 서브스트리(subshell)를 실행하는 구문으로, 내부의 명령어를 실행하고 결과를 외부 명령어로 전달합니다.
    • docker container ls -aq: 현재 실행 중이거나 정지된 모든 Docker 컨테이너의 ID를 출력하는 명령어입니다. -q 옵션은 컨테이너 ID만을 출력하라는 의미입니다. (id들만 나옴)

이미지 삭제

  1. 개별적 : docker image ls, 개별적으로 rm
  2. docker image rm $(docker image ls -q) 로 한번에 삭제

삭제 잘 됐는지 확인

  • docker ps
  • docker images
  • 위 두개 쳤을때 아무것도 안나와야함
  • 안지워지면 -f 를 이용해서 강제삭제 : docker image rm -f $(docker image ls -q)


docker desktop으로 삭제

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를 통해 루트 유저로 연결가능

실습 1 : hello world

  • node.js 로 간단하게 코드를 짜보자. 
  • 순서 : os선택, node설치, 코드작성, 프로그램실행 -> 이 모든것 dockerfile에 기술

 

 

dockerfile

  • dockerfile 구조:

docker file의 구조

 

  • dockerfile 구조 예
    from node: alpine  : node(도커이름), alpine(os이름)
    copy ./app : 현재 디렉토리 내용 모두 도커의 /app에 저장 
    workdir /app : 기본 위치를 /app로 지정
    cmd node app.js : /app내의 app.js 실행
  • 그외 기타 키워드
    1) ARG : 도커 image를 만들때 사용되는 변수, 최종 이미지에는 포함안됨
    2) ENV : 최종이미지에 저장되는 변수, 컨테이너가 실행될 때 사용됨. 
    3) USER : 컨테이너 os 계정 ID
    4) EXPOSE : 서비스를 사용할 포트번호
    5) RUN : 빌드를 위해 실행 돼야 하는 명령들, 예) RUN apt-update && apt-get install -y curl 
  • CMD vs ENTRYPOINT
    1) 컨테이너 시작시 실행 돼야 하는 명령어를 지정
    2) 일반적으로 둘중에 하나쓰임
    3) 명령어를 여러개 쓰면 마지막 것만 실행됨

    4) 사용예
    # 기본 이미지로 사용할 것을 선택합니다.
    FROM python:3.8
    # 작업 디렉토리를 설정합니다.
    WORKDIR /app
    # 호스트의 현재 디렉토리에 있는 파일을 작업 디렉토리로 복사합니다.
    COPY . /app
    # 필요한 패키지를 설치합니다.
    RUN pip install -r requirements.txt
    # Python 인터프리터를 사용하여 "app.py" 스크립트를 실행하도록 지정
    CMD ["python", "app.py"]
    or ENTRYPOINT  ["python", "app.py"]

    5) 같이 사용할때(거의  사용안함)
    entry 가 기본명령 , cmd가 인자 제공
    cmd는 그냥 뒤에 쓰면 덮어쓰기가 되고, enrty는 --entrypoint 옵션을 통해서 덮어쓰는게 가능

 

 

실제 dockerfile 예

  • ARG는 최종까지, ENG는 빌드할때만 사용됨
  • copy : aiflow.cfg 파일을 복사
  • RUN : airflow라는 유저로 지정
  • EXPOSE : 포트넘버 지정
  • USER : airflow를 유저로 지정
  • WORKDIR : 기본 지정
  • ENTRY , CMD : 명령어 지정 

 

docker lmage 생성

  • 이미지 이름 hello~ '.' 은 현재 페이지를 의미 
  • --platform ~ : 도커빌드 os (M1) , 실행 os(리눅스) 차이에 의한 호환성 문제 , 해결위한 명령어
  • 생성 확인
  • 다른 컴퓨터에서 실행하려면 dorker 클라우드(docker hub) 로 먼저 등록

 

 

 

+ Recent posts