# 用Compose建立容器

![](/files/-MAUoqEjS_6IvNi2L_87)

假設`docker run`要設定的選項太多，可以寫一個設定檔來啟動，這就是`docker compose`主要做的事情。

## 安裝Docker Compose

```
$ pip install docker-compose
$ docker-compose --version
docker-compose version 1.25.5, build unknown
```

### 撰寫Docker Compose檔

以下是單個容器container的yaml檔

```
version: '3'                                            # yaml的版本
services:     
  app:       
    image: cutejaneii/my_api:june2020                   # 映像檔
    volumes:
      - /var/lib/docker/volumes/volume_nfs/_data:/nfs   # volume
    ports:
      - 8801:8801                                       # PORT MAPPING
    restart: always                                     # 啟動POLICY
    environment:                                        # 環境變數
      - API_CASSANDRA_CONTACT_POINTS=192.168.95.1,192.168.95.2
      - API_CASSANDRA_KEY_SPACE=my_keyspace
      - API_NAME=my_api
volumes:
  volume_nfs:
```

若需要同時啟動多個容器，會長得像以下這樣，同時啟動web, redis 2個容器，以下範例來自[官網](https://docs.docker.com/compose/gettingstarted/)

```
version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"
```

### 執行Docker Compose

依照docker-compose.yml檔，在前景啟動容器

```
$ docker-compose -f docker-compose.yml up
```

依照docker-compose.yml檔，在背景啟動容器

```
$ docker-compose -d docker-compose.yml up
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cutejaneii.gitbook.io/docker/docker-container/docker-compose.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
