ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Docker] - Docker-compose
    개발/Docker 2022. 8. 3. 17:24

    Docker-compose 개요


    • Docker compose란, 여러 컨테이너 서비스를 구축, 실행하는 순서를 자동으로 하여, 관리를 간단히 하는 기능이다.
    • Docker compose에서는 docker-compose.yaml(docker-compose.yml은 우선순위가 후순위) 파일을 실행, 설정을 읽어 들여 모든 컨테이너 서비스를 실행

     

    Docker-compose Process


    Document를 보게되면, 아래와 같이 정의되어 있다.

    1. Define your app’s environment with a Dockerfile so it can be reproduced anywhere.
    2. Define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.
    3. Run docker compose up and the Docker compose command starts and runs your entire app. You can alternatively run docker-compose up using Compose standalone

    1. DockerFile을 작성한다(Image가 아닌 경우)

    즉, Build를 통하여 동작시킨다는 의미이다.

    간단하게 Python Flask 예시를 들어보자

    1-1) Create a directory for the project

    $ mkdir composetest
    $ cd composetest

    1-2) Create a app.py

    import time
    
    import redis
    from flask import Flask
    
    app = Flask(__name__)
    cache = redis.Redis(host='redis', port=6379)
    
    def get_hit_count():
        retries = 5
        while True:
            try:
                return cache.incr('hits')
            except redis.exceptions.ConnectionError as exc:
                if retries == 0:
                    raise exc
                retries -= 1
                time.sleep(0.5)
    
    @app.route('/')
    def hello():
        count = get_hit_count()
        return 'Hello World! I have been seen {} times.\n'.format(count)

    1-3) Create another file called requirements.txt

    flask
    redis

     

    #Create Dockerfile
    # syntax=docker/dockerfile:1
    
    # Build an image starting with the Python 3.7 image.
    FROM python:3.7-alpine
    
    # Set the working directory to /code
    WORKDIR /code
    
    # Set environment variables used by the flask command
    ENV FLASK_APP=app.py
    ENV FLASK_RUN_HOST=0.0.0.0
    
    # Install gcc and other dependencies
    RUN apk add --no-cache gcc musl-dev linux-headers
    
    # Copy requirements.txt and install the Python dependencies
    COPY requirements.txt requirements.txt
    RUN pip install -r requirements.txt
    
    # Add metadata to the image to describe that the container is listening on port 5000
    EXPOSE 5000
    
    # Copy the current directory . in the project to the workdir . in the image
    COPY . .
    
    # Set the default command for the container to flask run
    CMD ["flask", "run"]

    2. docker-compose.yml을 작성, 독립된 Container의 실행 환경을 정의한다.

    2개의 Container를 생성할 예정이다.

    1. Web ( 위에서 만든 Container )

    2. Redis ( Image로 처리한 Container )

    version: "3.9"
    services:
      web:
        build: .
        ports:
          - "8000:5000"
      redis:
        image: "redis:alpine"

    3. command를 실행 시켜, Container를 실행시킨다.

    $ docker-compose up -d

     

    Docker-compose.yml


    아래와 같이 Frontend/Backend를 만든다 하여 보자.

    (External user) --> 443 [frontend network]
                                |
                      +--------------------+
                      |  frontend service  |...ro...<HTTP configuration>
                      |      "webapp"      |...ro...<server certificate> #secured
                      +--------------------+
                                |
                            [backend network]
                                |
                      +--------------------+
                      |  backend service   |  r+w   ___________________
                      |     "database"     |=======( persistent volume )
                      +--------------------+        \_________________/

    1. Service

    • 실행시킬 Container Image or Component

    2. Networks

    • Service들은 Network를 통해 서로 통신한다.
    • 연결된 서비스 내에 Container 간에 IP를 설정하여 기능 추상화

     

    3. Volumes

    • Service들은 영구적으로 Data를 공유, 저장

     

    4. Configs

    • Volume과 유사하지만 runtime, platform에 종속된 config data 설정

    아래와 같이 나타낼 수 있다.

    services:
      frontend:
        image: awesome/webapp
        ports:
          - "443:8043"
        networks:
          - front-tier
          - back-tier
        configs:
          - httpd-config
        secrets:
          - server-certificate
    
      backend:
        image: awesome/database
        volumes:
          - db-data:/etc/data
        networks:
          - back-tier
    
    volumes:
      db-data:
        driver: flocker
        driver_opts:
          size: "10GiB"
    
    configs:
      httpd-config:
        external: true
    
    secrets:
      server-certificate:
        external: true
    
    networks:
      # The presence of these objects is sufficient to define them
      front-tier: {}
      back-tier: {}

    ETC Concept


    1. profile

    • 동일한 App이어도 설정에 따라 다르게 동작하도록

     

    2. healthcheck

    • Service가 정상적으로 동작하는지 확인
    • Docker Image로부터 Override 된다.

     

    3. Image

    • Container가 시작하기 위한 구체적인 Image

     

    4. Link

    • 다른 서비스들과의 Network Link
    • [Service:Alias]

    '개발 > Docker' 카테고리의 다른 글

    [Docker] - 3. Docker Command 정리  (0) 2022.08.24
    [Docker] - Docker 기본 개념  (0) 2022.07.21
    [Docker] - 4.Volume&Bind Mount  (0) 2022.07.16
    [Docker] 2. Docker 설치 & Docker-compose  (0) 2022.07.03
    [Docker] - 1. WSL 기본 설치  (0) 2022.07.03

    댓글

Designed by Tistory.