Docker.3.2-更新应用程序

您将更新应用程序和容器镜像。您还将学习如何停止和删除容器。

更新源码

在下面的步骤中,您将在没有任何待办事项列表项时将“空文本”更改为“您还没有待办事项!上面加一个!”

  1. src/static/js/app.js文件中,更新第 56 行以使用新的空文本。

    1
    2
    - <p className="text-center">No items yet! Add one above!</p>
    + <p className="text-center">You have no todo items yet! Add one above!</p>
  2. docker build使用您在Docker.3.1-将应用程序容器化中使用的相同命令构建镜像的更新版本。

    1
    docker build -t getting-started .

    你可能会看到这样的错误:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    22.97 error An unexpected error occurred: "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz: connect ECONNREFUSED 104.16.27.34:443".
    22.97 info If you think this is a bug, please open a bug report with the information provided in "/app/yarn-error.log".
    22.97 info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
    ------
    Dockerfile:6
    --------------------
    4 | WORKDIR /app
    5 | COPY . .
    6 | >>> RUN yarn install --production
    7 | CMD ["node", "src/index.js"]
    8 | EXPOSE 3000
    --------------------
    ERROR: failed to solve: process "/bin/sh -c yarn install --production" did not complete successfully: exit code: 1

    这是由于资源地址请求超时造成的,更换一下请求地址,可以修改Dockerfile

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    # syntax=docker/dockerfile:1

    FROM node:18-alpine
    WORKDIR /app
    COPY . .
    RUN yarn config set registry https://registry.npmmirror.com
    RUN yarn cache clean
    RUN yarn install --production
    CMD ["node", "src/index.js"]
    EXPOSE 3000

    其他解决方案,详见

  3. 使用更新的代码启动一个新容器。

    1
    docker run -dp 127.0.0.1:3000:3000 getting-started

您可能会看到这样的错误(ID 会不同):

1
2
docker: Error response from daemon: driver failed programming external connectivity on endpoint laughing_burnell
(bb242b2ca4d67eba76e79474fb36bb5125708ebdabd7f45c8eaf16caaabde9dd): Bind for 127.0.0.1:3000 failed: port is already allocated.

发生错误的原因是您无法在旧容器仍在运行时启动新容器。原因是旧容器已经在使用主机的 3000 端口,并且机器上只有一个进程(包括容器)可以监听特定端口。要解决此问题,您需要删除旧容器。

删除旧容器

要删除容器,您首先需要停止它。一旦停止,您就可以将其删除。您可以使用 CLI 或 Docker Desktop 的图形界面删除旧容器。选择您最满意的选项。

使用 CLI 删除容器

  1. 使用命令获取容器的 ID docker ps

    1
    docker ps
  2. 使用docker stop命令停止容器。将 替换为 中的 ID docker ps

    1
    docker stop <the-container-id>
  3. 容器停止后,您可以使用docker rm命令将其删除。

    1
    docker rm <the-container-id>

您可以通过向命令添加标志force来在单个命令中停止和删除容器docker rm。例如:docker rm -f <the-container-id>

使用 Docker Desktop 删除容器

  1. 打开 Docker Desktop 到容器视图。
  2. 选择要删除的当前正在运行的旧容器的“操作”列下的垃圾桶图标。
  3. 在确认对话框中,选择“永久删除”

启动更新的应用程序容器

  1. 现在,使用命令启动更新的应用程序docker run

    1
    docker run -dp 127.0.0.1:3000:3000 getting-started
  2. http://localhost:3000上刷新浏览器,您应该会看到更新后的帮助文本。

    image-20230703234456487

后续步骤

当您能够构建更新时,您可能注意到了两件事:

  • 您的待办事项列表中的所有现有项目都消失了!这不是一个很好的应用程序!您很快就会解决这个问题。
  • 如此小的改变涉及很多步骤。在接下来的部分中,您将了解如何查看代码更新,而无需在每次进行更改时重建并启动新容器。

在讨论持久性之前,您将了解如何与其他人共享这些镜像。