# 4.3 新建并启动容器(run)

<mark style="color:blue;">**docker \[container] run**</mark>等价于先执行**docker \[container] create**命令，再执行**docker \[container] start**命令。例如，下面的命令输出一个“Hello World”，之后容器自动终止：

```bash
$ docker run ubuntu:latest /bin/echo "hello world"
hello world
```

当利用docker \[container] run来创建并启动容器时，Docker在后台运行的标准操作包括：

1. **检查本地是否存在指定的镜像，不存在就从公有仓库下载；**
2. 利用镜像创建一个容器，并启动该容器；
3. 分配一个文件系统给容器，并在只读的镜像层外面挂载一层可读写层；
4. 从宿主主机配置的网桥接口中桥接一个虚拟接口到容器中去；
5. 从网桥的地址池配置一个IP地址给容器；
6. 执行用户指定的应用程序；
7. 执行完毕后容器被自动终止。

## 1. 交互模式

下面的命令启动一个bash终端，允许用户进行交互：

{% code overflow="wrap" %}

```bash
$ docker run -it ubuntu:latest /bin/bash
root@7b514d55f51b:/# pwd
/
root@7b514d55f51b:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@7b514d55f51b:/# ps
   PID TTY          TIME CMD
     1 pts/0    00:00:00 bash
    10 pts/0    00:00:00 ps
```

{% endcode %}

其中，**-t** 选项让Docker分配一个伪终端（pseudo-tty）并绑定到容器的标准输入上，**-i** 则让容器的标准输入保持打开。<mark style="color:blue;">**用户可以按Ctrl+d或输入exit命令来退出容器。**</mark>

对于所创建的bash容器，当用户使用exit命令退出bash进程之后，容器也会自动退出。这是因为对于容器来说，当其中的应用退出后，容器的使命完成，也就没有继续运行的必要了。

可以使用**docker container wait CONTAINER \[CONTAINER...]**&#x547D;令来等待容器退出，并打印退出返回结果。

## 2. 守护模式

更多的时候，需要让Docker容器在后台以**守护态（Daemonized）**&#x5F62;式运行。此时，可以通过添&#x52A0;**-d** 参数来实现。

{% code overflow="wrap" %}

```bash
$ docker run -d ubuntu:latest \
/bin/sh -c "while true; do echo hello world; sleep 1; done"
004bf1f645088cf68343b5be852116fc7bc681de31d4c8bee3f3884c497ecf88

$ docker ps
CONTAINER ID   IMAGE           COMMAND                   CREATED          STATUS          PORTS     NAMES
004bf1f64508   ubuntu:latest   "/bin/sh -c 'while t…"   5 seconds ago    Up 2 seconds              xenodochial_thompson
```

{% endcode %}


---

# 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://bohans.gitbook.io/devops/ji-chu-zhi-shi/4.-docker-rong-qi/4.3-xin-jian-bing-qi-dong-rong-qi-run.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.
