# 最佳实践

我们强烈建议您查看 [Docker 的最佳实践](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) 以帮助您学习优化容器及其安全性的最佳方法。

以下是一些提示，可优化您的容器以在 Edgegap 上完美运行。

## 版本管理

在容器构建上进行版本管理是容器生命周期的关键方面，因为许多环境如果本机已有该标签的镜像就不会再次拉取该镜像。

### 标签 *latest（最新）*

默认情况下，当您运行构建命令时：

{% hint style="warning" %}
对于 ARM CPU（Mac M1、M2 等）用户，请在构建命令中添加 `--platform linux/amd64`  选项。
{% endhint %}

```bash
docker build -t repo/example .
```

该构建的输出将赋予该构建 标签 **latest（最新）**

下面的命令产生相同的输出：

```bash
docker build -t repo/example:latest .
```

但请记住， **latest（最新）** 只是和其他标签一样的一个标签，并不总是代表您最新的构建。

示例：

```bash
docker build -t repo/example:latest .
# 对您的代码进行一些修改
docker build -t repo/example:0.1 .
```

Edgegap 不会更新您的标签 **latest（最新）** 并且版本 **0.1** 将会领先于新代码。

### 标签示例

我们建议在每次镜像构建时提高或更改版本，以确保正确使用并避免系统缓存旧版本。假设您已经使用某个系统进行语义版本控制或在每次编译时增加版本号，那么您可以非常容易地实现自动为 Docker 构建打标签的流程。

示例 Bash 脚本，用于使用您传入的匹配版本参数来构建 Dockerfile。

此示例将使用给定版本构建、为仓库打标签并推送（如果使用私有仓库，请别忘了先登录）。

```bash
#!/bin/bash

if [[ $# -ne 1 ]] ; then
    echo '未提供参数，请指定要构建此镜像的版本。 --> 示例: ./docker-build.sh 0.0.1'
    exit 1
fi

docker build -t my-repo/example:$1 .

docker tag my-repo/example:$1 registry.edgegap.com/my-repo/example:$1
docker push registry.edgegap.com/my-repo/example:$1
```

使用此脚本，您现在可以使用应用构建版本来正确调用它。

示例：您构建了新的游戏服务器版本 **2021.01.29.1234**

```bash
# 从您的 CI/CD 管道或手动执行

./docker-build.sh 2021.01.29.1234
```

### 原因

每次构建提高标签的主要原因是为了防止边缘缓存。

为了能够在几秒钟内启动服务器，我们会预先拉取镜像并仅在需要时增加实例数量。我们无法保证拉取策略的频率，因为只有在边缘上尚未存在该镜像时才会拉取它。

所以基本上使用 **latest（最新）** 标签或任何持久性标签可能会给您在修复或调试时带来麻烦，因为您将更新构建并在 Edgegap 部署它，但边缘不会拉取新的 *版本* 您的标签因为它相同。

如果您从不使用 [语义化版本控制](https://semver.org/)，Edgegap 强烈建议您阅读相关内容并将其应用到您的构建版本管理中！


---

# 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://docs.edgegap.com/zh/docs/tools-and-integrations/container/good-practices.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.
