Skip to content

Commit

Permalink
�lecture_material: 2강 강의 자료 업데이트 (#29)
Browse files Browse the repository at this point in the history
* ADD. 2nd lecture material

* FIX. 2nd lecture material
  • Loading branch information
drum-grammer authored May 11, 2024
1 parent fe173b6 commit fe1dab0
Show file tree
Hide file tree
Showing 12 changed files with 356 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,5 @@ docker run hello-world

## IV. 도커 커맨드 라인 명령어 정리
- [공식 문서](https://docs.docker.com/engine/reference/run/)
- [cheat sheet](/lecture/1st/cli.md)
- [cheat sheet - Docker CLI](/lecture/1st/cli.md)
- [cheat sheet - Docker Compose CLI](/lecture/2nd/docker-compose-cli.md)
146 changes: 146 additions & 0 deletions lecture/2nd/docker-compose-cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
## Docker Compose CLI Examples

### 1. [Build or rebuild services](https://docs.docker.com/compose/reference/build/)
- **Usage:**
```shell
docker-compose build [options] [--build-arg key=val...] [SERVICE...]
```
- **Example:**
```shell
docker-compose build
```

### 2. [List images used by the created containers](https://docs.docker.com/compose/reference/images/)
- **Usage:**
```shell
docker-compose images [SERVICE...]
```
- **Example:**
```shell
docker-compose images
```

### 3. [Create and start containers](https://docs.docker.com/compose/reference/up/)
- **Usage:**
```shell
docker-compose up [options] [--scale SERVICE=NUM...] [SERVICE...]
```
- **Example:**
```shell
docker-compose up
docker-compose up -d # Start in detached mode
```

### 4. [Start services](https://docs.docker.com/compose/reference/start/)
- **Usage:**
```shell
docker-compose start [SERVICE...]
```
- **Example:**
```shell
docker-compose start
```

### 5. [Stop services](https://docs.docker.com/compose/reference/stop/)
- **Usage:**
```shell
docker-compose stop [options] [SERVICE...]
```
- **Example:**
```shell
docker-compose stop
docker-compose stop -t 20 # Stop with a timeout
```

### 6. [View output from containers](https://docs.docker.com/compose/reference/logs/)
- **Usage:**
```shell
docker-compose logs [options] [SERVICE...]
```
- **Example:**
```shell
docker-compose logs
docker-compose logs -f # Follow log output
```

### 7. [Remove stopped containers](https://docs.docker.com/compose/reference/rm/)
- **Usage:**
```shell
docker-compose rm [options] [SERVICE...]
```
- **Example:**
```shell
docker-compose rm -f
```

### 8. [Execute a command in a running container](https://docs.docker.com/compose/reference/exec/)
- **Usage:**
```shell
docker-compose exec [options] SERVICE COMMAND [ARGS...]
```
- **Example:**
```shell
docker-compose exec web bash
```

### 9. [Manage services](https://docs.docker.com/compose/reference/)
- **General Usage:**
```shell
docker-compose [COMMAND] [SERVICE...]
```

### 10. [Pulls service images](https://docs.docker.com/compose/reference/pull/)
- **Usage:**
```shell
docker-compose pull [options] [SERVICE...]
```
- **Example:**
```shell
docker-compose pull
```

### 11. [Push service images](https://docs.docker.com/compose/reference/push/)
- **Usage:**
```shell
docker-compose push [options] [SERVICE...]
```
- **Example:**
```shell
docker-compose push
```

### 12. [Login to a Docker registry](https://docs.docker.com/compose/reference/login/)
- **Usage:**
```shell
docker login [OPTIONS] [SERVER]
```
- **Example:**
```shell
docker login
```

### 13. [Logout from a Docker registry](https://docs.docker.com/compose/reference/logout/)
- **Usage:**
```shell
docker logout [SERVER]
```
- **Example:**
```shell
docker logout
```

### 14. [Manage Docker system](https://docs.docker.com/compose/reference/)
- **Usage:**
```shell
docker system COMMAND
```

### 15. [Manage networks in Docker Compose](https://docs.docker.com/compose/networking/)
- **Usage:**
```shell
docker-compose network [COMMAND]
```
- **Example:**
```shell
docker-compose network inspect my-network
```
22 changes: 22 additions & 0 deletions lecture/2nd/dockerfile_example/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 기본 이미지로 파이썬 3.8을 사용
FROM python:3.8-slim

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

# 의존성 파일 복사 및 설치
COPY requirements.txt .
RUN pip install -r requirements.txt

# 애플리케이션 코드 복사
COPY . .

# `ENTRYPOINT` 설정
ENTRYPOINT ["python"]

# `CMD`는 ENTRYPOINT의 기본 매개변수 역할
CMD ["app.py"]


# `ENTRYPOINT`에 모두 설정
# ENTRYPOINT ["python", "app.py"]
72 changes: 72 additions & 0 deletions lecture/2nd/dockerfile_example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
Docker 파일 문법 및 사용법에 대한 설명과 예제를 준비했습니다. Docker의 기본 구성 요소인 `RUN`, `CMD`, `ENTRYPOINT` 등을 이해하기 위한 간단하고 명확한 설명과 함께 예제 Dockerfile을 만들어 보겠습니다. 그리고 이를 테스트할 수 있는 환경을 구성하는 방법도 제공하겠습니다.

### 1. `RUN`, `CMD`, `ENTRYPOINT` 설명 및 차이점

- **`RUN`**: Docker 이미지를 빌드하는 과정에서 사용되는 명령어입니다. 이 명령어는 이미지 빌드 시에 실행되며 결과물은 이미지에 영구적으로 반영됩니다. 예를 들어, 패키지를 설치하거나 파일을 수정하는 데 사용됩니다.
- **`CMD`**: Docker 컨테이너가 시작될 때 실행할 기본 명령을 지정합니다. Dockerfile 내에 한 번만 사용할 수 있으며, 여러 개의 `CMD`가 있을 경우 마지막 `CMD`만 적용됩니다.
- **`ENTRYPOINT`**: 컨테이너가 실행될 때 항상 실행되어야 하는 명령을 정의합니다. `CMD`와 함께 사용될 경우, `ENTRYPOINT`는 실행 파일 또는 스크립트를 지정하고 `CMD`는 그에 대한 매개변수를 제공하는 형태로 사용됩니다.

### 2. 예제 Dockerfile 작성

이 예제에서는 간단한 Python 애플리케이션을 컨테이너화하는 과정을 보여 드리겠습니다.

**Dockerfile:**
```dockerfile
# 기본 이미지로 파이썬 3.8을 사용
FROM python:3.8-slim

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

# 의존성 파일 복사 및 설치
COPY requirements.txt .
RUN pip install -r requirements.txt

# 애플리케이션 코드 복사
COPY . .

# `ENTRYPOINT` 설정
ENTRYPOINT ["python"]

# `CMD`는 ENTRYPOINT의 기본 매개변수 역할
CMD ["app.py"]
```

**requirements.txt:**
```
flask
```

**app.py:**
```python
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
return '수강생들의 빠른 취업, 연봉 상승 기원합니다!'

if __name__ == '__main__':
app.run(host='0.0.0.0')
```

### 3. 추가적인 Docker 파일 문법

- **`COPY`**: 파일이나 디렉토리를 로컬 파일 시스템에서 이미지로 복사합니다.
- **`ADD`**: `COPY`와 비슷하지만, 네트워크에서 파일을 가져오거나 로컬의 tar 파일을 자동으로 압축 해제할 수 있습니다.
- **`ENV`**: 환경 변수를 설정합니다. 예: `ENV PATH /usr/local/bin:$PATH`
- **`EXPOSE`**: 컨테이너가 리스닝할 포트를 지정합니다. 예: `EXPOSE 80`
- **`VOLUME`**: 데이터 볼륨을 마운트할 위치를 지정합니다. 예: `VOLUME /data`

### 4. 이미지 빌드 및 컨테이너 실행 명령

1. **이미지 빌드:**
```bash
docker build -t my-python-app .
```
2. **컨테이너 실행:**
```bash
docker run -p 8080:5000 my-python-app
```

위 명령을 실행하면, `8080` 포트를 통해 애플리케이션에 접근할 수 있습니다. 이렇게 설정하면 Docker의 기본적인 사용법과 문법을 이해하고 직접 테스트해 볼 수 있는 환경이 준비됩니다. 🚀
10 changes: 10 additions & 0 deletions lecture/2nd/dockerfile_example/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
return '수강생들의 빠른 취업, 연봉 상승 기원합니다!'

if __name__ == '__main__':
app.run(host='0.0.0.0')
9 changes: 9 additions & 0 deletions lecture/2nd/dockerfile_example/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
blinker==1.8.2
click==8.1.7
Flask==3.0.3
importlib_metadata==7.1.0
itsdangerous==2.2.0
Jinja2==3.1.4
MarkupSafe==2.1.5
Werkzeug==3.0.3
zipp==3.18.1
83 changes: 83 additions & 0 deletions lecture/2nd/expose_vs_ports/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
Docker Compose 파일에서 `expose``ports`는 두 가지 다 컨테이너의 네트워크 포트 설정과 관련된 명령어입니다. 각각의 기능과 차이점을 아래와 같이 설명하고 예제를 통해 살펴보겠습니다.

### `expose`
- **목적**: `expose`는 해당 컨테이너가 사용하는 포트를 문서화하고, 동일한 Docker 내부 네트워크 내에서 다른 컨테이너들이 이 포트를 통해 연결할 수 있도록 합니다.
- **접근성**: 이 명령어로 노출된 포트는 외부에는 노출되지 않으며 오직 동일한 네트워크 내의 다른 컨테이너들만 접근할 수 있습니다.

### `ports`
- **목적**: `ports` 설정은 컨테이너의 포트를 호스트의 포트에 바인딩하여 외부 네트워크에서도 접근할 수 있게 합니다.
- **접근성**: 이 설정을 통해 지정된 호스트의 포트를 통해 컨테이너의 포트에 외부에서 직접 접근할 수 있습니다.

### 차이점
- **접근 범위**: `expose`는 내부 네트워크에서만 접근 가능하게 하며, `ports`는 외부 네트워크에서도 접근할 수 있도록 합니다.
- **용도**: 개발자는 `expose`를 사용해 다른 서비스들이 컨테이너와 통신할 수 있음을 명시할 수 있으며, `ports`는 실제로 외부 요청을 컨테이너로 라우팅할 때 사용됩니다.

### 예제
다음은 간단한 `docker-compose.yml` 파일 예제입니다. 여기서는 `web` 서비스가 `5000` 포트를 사용하고 이를 외부에 노출시키며, `db` 서비스는 `5432` 포트를 사용하지만 내부적으로만 노출합니다.

```yaml
version: '3.8'
services:
web:
image: nginx
ports:
- "8000:5000"
depends_on:
- db
db:
image: postgres
expose:
- "5432"
```
#### 설명
- **Web 서비스**:
- 외부에서 `8000` 포트를 통해 접근하면, 이 요청은 내부적으로 `web` 컨테이너의 `5000` 포트로 매핑됩니다.
- 외부 사용자는 `localhost:8000`을 통해 웹 서버에 접근할 수 있습니다.

- **DB 서비스**:
- `5432` 포트는 내부 네트워크에만 노출되어 있어, `web` 서비스 같은 다른 서비스에서만 접근할 수 있습니다.
- 외부에서는 직접적으로 `db` 서비스에 접근할 수 없습니다.

이 예제를 통해 `expose`와 `ports`의 차이를 명확히 이해하고 실습할 수 있습니다.

Docker Compose 파일을 사용하여 위의 예제를 실제로 테스트하기 위한 커맨드라인 명령어를 안내해 드리겠습니다. 먼저, 주어진 `docker-compose.yml` 파일을 사용할 준비가 되어 있어야 합니다.

### 1. Docker Compose 파일 작성
위에서 제공한 `docker-compose.yml` 파일 내용을 사용합니다. 이 파일을 작업할 디렉터리에 저장하세요.

### 2. Docker Compose 프로젝트 실행
Docker Compose 프로젝트를 실행하려면, 다음 커맨드를 사용합니다:
```bash
docker-compose up -d
```
이 명령은 Docker 컨테이너를 백그라운드 모드(`-d` 옵션 사용)에서 실행합니다.

### 3. 실행 중인 서비스 확인
실행 중인 모든 Docker 컨테이너를 확인하려면 다음 커맨드를 사용하세요:
```bash
docker-compose ps
```
이 명령은 현재 실행 중인 컨테이너와 그 상태를 보여줍니다.

### 4. 포트 노출 및 접근 확인
외부에서 `web` 서비스의 `8000` 포트를 통해 Nginx 홈페이지에 접근해 볼 수 있습니다. 웹 브라우저에서 `localhost:8000`을 방문하면 Nginx 홈페이지가 표시됩니다.

### 5. 내부 네트워크 통신 테스트
`web` 컨테이너에서 `db` 컨테이너의 `5432` 포트에 접근해보려면, 다음과 같은 커맨드를 사용할 수 있습니다:
```bash
docker-compose exec web bash
```
이 커맨드는 `web` 서비스의 쉘에 접속합니다. 그 다음, `psql`을 사용하여 `db` 서비스에 접근해 보세요 (PostgreSQL 클라이언트가 필요합니다):
```bash
psql -h db -U postgres
```
여기서 `-h db`는 `db` 서비스의 호스트 이름을, `-U postgres`는 사용자 이름을 지정합니다.

### 6. 정리
테스트가 끝나고 나면, 다음 커맨드로 모든 서비스를 중지하고 컨테이너를 제거할 수 있습니다:
```bash
docker-compose down
```

이러한 단계를 통해 실제로 `docker-compose.yml` 파일의 설정을 테스트하고, `expose`와 `ports`의 차이를 경험해 볼 수 있습니다.
12 changes: 12 additions & 0 deletions lecture/2nd/expose_vs_ports/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: '3.8'
services:
web:
image: nginx
ports:
- "8000:5000"
depends_on:
- db
db:
image: postgres
expose:
- "5432"
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit fe1dab0

Please sign in to comment.