# 用指令建立容器

取得合適的映像檔(Image)之後，下一步就是建立容器，指令就是`docker run`

```
$ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
```

建立者要考慮使用情況，來調整`docker run`指令，以下列出常用選項：

**`--env, -e`** 用來傳入環境變數，例如 `docker run -e "pyfile=main2.py" Python:2.7`

**`-v`** 設定data volume，可先建立docker volume，再設定**docker volume與容器資料夾的對應**，例如 `docker run -v volume_nfs:/nfs my_app`  。也可以**直接設定主機資料夾與容器資料夾的對應**，例如  `docker run -v /host/nfs:/nfs my_app`

**`-d`** 讓容器在背景執行

**`--net=[Mode]`** 設定容器網路，例如 `docker run --net=host nginx`，常用的Mode包括host, none, bridge，不指定的話預設是bridge

**`--name`** 設定容器名稱，例如 `docker run --name my_python python:2.7`

**`--restart=[policy]`** 設定重啟機制，例如 `docker run --restart=on-failure:10 cassandra` 可允許在錯誤的情況下重啟容器，最多重啟5次。例如 `docker run --restart=always redis` 則只要容器一被停止，就立即嘗試重啟，適合服務不可中斷的容器。若沒指定，則預設是`--restart=none`，也就是若容器停止，則需人為手動啟動。

**`-p`** (小寫p) 代表port mapping，設定 主機port  對應到 容器的哪個port，例如 `docker run -p 8080:80 python_app`，代表container port 80 = host port 8080

**`-P`** (大寫P) 代表隨機取得一個本機未使用的port，來對應容器的port，前提是在Dockerfile要寫expose port

{% hint style="info" %}
更多`docker run`的選項可參考[官方文件](https://docs.docker.com/engine/reference/commandline/run/)
{% endhint %}

在建立容器時，根據使用情境，可加入多個選項，例如 `docker run -d -p 8080:80 -v volume_nfs:/nfs -v /etc/localtime:/etc/localtime:ro --name my_redis redis`&#x20;

分析一下這行指令，`-d`  表示這個容器要在背景執行，`-p 8080:80` 表示本機的8080 port對應到容器的80 port，`-v volume_nfs:/nfs` 表示有一個volume\_nfs與容器內的/nfs資料夾對應，`-v /etc/localtime:/etc/localtime:ro` 表示本機的/etc/localtime對應到容器內的（這裡還多加了 `:ro` 代表容器內的唯讀），`--name my_redis`代表容器名稱，最後用來建立容器映像檔是`redis`


---

# 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/yong-zhi-ling-jian-li-container.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.
