1. 概述
在本教程中,我们将学习如何使用 Docker Compose 独立重建某个容器,而不影响其他容器。
2. 问题场景描述
我们先定义一个包含两个服务的 docker-compose.yml
文件:
- 一个是基于
ubuntu:latest
镜像的容器 - 另一个是基于
alpine:latest
镜像的容器
为了防止容器启动后立即退出,我们为每个服务添加 tty: true
:
version: "3.9"
services:
ubuntu:
image: "ubuntu:latest"
tty: true
alpine:
image: "alpine:latest"
tty: true
接着我们使用 docker-compose up -d
启动容器:
$ 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
检查运行状态:
$ docker-compose ps
NAME COMMAND SERVICE STATUS PORTS
{folder-name}-alpine-1 "/bin/sh" alpine running
{folder-name}-ubuntu-1 "bash" ubuntu running
接下来我们演示如何仅重建并重启 ubuntu 容器而不影响 alpine 容器。
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
再使用 -d
参数重新启动所有服务:
$ 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
⚠️ 此时如果我们只想重建 ubuntu
,必须加上 --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 up
命令重建指定容器
✅ 重建时应添加 --build
和 --force-recreate
参数
✅ 如果服务有依赖关系,记得加上 --no-deps
避免连带重启
✅ 避免不必要的全量重建,提升开发效率
完整代码可在 GitHub 上查看。