拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在Docker Compose 中重建Docker 容器

在Docker Compose 中重建Docker 容器

白鹭 - 2022-09-08 2147 0 2

一、概述

在本教程中,我们将看到如何使用docker-compose独立于其他容器重建容器。

2. 问题的呈现

让我们定义一个包含两个容器docker-compose.yml配置文件:一个将引用最新的ubuntu映像,另一个将引用最新的alpine映像。我们将为每个带有“ tty: true”的伪终端添加伪终端,以防止容器在启动时直接退出:

version: "3.9"
 services:
 ubuntu:
 image: "ubuntu:latest"
 tty: true
 alpine:
 image: "alpine:latest"
 tty: true

现在让我们构建容器并启动它们。我们将使用带有-d选项的docker-compose up命令让它们在后台运行:

$ docker-compose up -d
 Container {folder-name}-alpine-1 Creating
 Container {folder-name}-ubuntu-1 Creating
 Container {folder-name}-ubuntu-1 Created
 Container {folder-name}-alpine-1 Created
 Container {folder-name}-ubuntu-1 Starting
 Container {folder-name}-alpine-1 Starting
 Container {folder-name}-alpine-1 Started
 Container {folder-name}-ubuntu-1 Started

我们可以快速检查我们的容器是否按预期运行:

$ docker-compose ps
 NAME COMMAND SERVICE STATUS PORTS
 {folder-name}-alpine-1 "/bin/sh" alpine running
 {folder-name}-ubuntu-1 "bash" ubuntu running

现在,我们将了解如何在不影响alpine容器的情况下重建和重新启动ubuntu容器。

3. 独立重建和重启容器

将容器的名称添加到docker-compose up命令就可以了。我们将在启动容器之前添加build选项来构建镜像。我们还将添加force-recreate标志,因为我们没有更改图像:

$ docker-compose up -d --force-recreate --build ubuntu
 Container {folder-name}-ubuntu-1 Recreate
 Container {folder-name}-ubuntu-1 Recreated
 Container {folder-name}-ubuntu-1 Starting
 Container {folder-name}-ubuntu-1 Started

正如我们所见,ubuntu容器被重建并重新启动,对alpine容器没有任何影响。

4.如果容器依赖于另一个容器

现在让我们稍微更新docker-compose.yml文件,使ubuntu容器依赖于alpine容器:

version: "3.9"
 services:
 ubuntu:
 image: "ubuntu:latest"
 tty: true
 depends_on:
 - "alpine"
 alpine:
 image: "alpine:latest"
 tty: true

我们将停止以前的容器并使用新配置从头开始重建它们

$ docker-compose stop
 Container {folder-name}-alpine-1 Stopping
 Container {folder-name}-ubuntu-1 Stopping
 Container {folder-name}-ubuntu-1 Stopped
 Container {folder-name}-alpine-1 Stopped
 $ docker-compose up -d
 Container {folder-name}-alpine-1 Created
 Container {folder-name}-ubuntu-1 Recreate
 Container {folder-name}-ubuntu-1 Recreated
 Container {folder-name}-alpine-1 Starting
 Container {folder-name}-alpine-1 Started
 Container {folder-name}-ubuntu-1 Starting
 Container {folder-name}-ubuntu-1 Started

在这种情况下,我们需要添加no-deps选项来明确告诉docker-compose不要重新启动链接的容器

$ docker-compose up -d --force-recreate --build --no-deps ubuntu
 Container {folder-name}-ubuntu-1 Recreate
 Container {folder-name}-ubuntu-1 Recreated
 Container {folder-name}-ubuntu-1 Starting
 Container {folder-name}-ubuntu-1 Started

5. 结论

在本教程中,我们了解了如何使用docker-compose重建容器。


标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *