容器与云原生 / 系统课时
定义与启动服务
定义与启动服务
本课将创建一个由 Nginx Web 服务和 Redis 缓存组成的最小项目,覆盖 image、build、command、ports 等常用配置,并通过构建、启动、访问和状态检查完成验收。
学习目标
- 使用
image和build定义服务来源 - 配置容器启动命令与主机端口映射
- 使用 Compose 完成构建、启动和访问验证
准备项目文件
创建目录并准备三个文件:
text
compose-demo/
├── compose.yaml
├── Dockerfile
└── index.htmlDockerfile 基于 Nginx 镜像构建自定义 Web 镜像:
dockerfile
FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.htmlindex.html 提供可见的验证内容:
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Compose Demo</title>
</head>
<body>
<h1>Compose is running</h1>
</body>
</html>定义两个服务
在项目根目录创建 compose.yaml:
yaml
services:
web:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:80"
depends_on:
- cache
cache:
image: redis:7-alpine
command: ["redis-server", "--save", "60", "1"]web.build 表示从当前目录构建镜像,cache.image 表示直接使用现成镜像。command 覆盖镜像默认命令,ports 中的 "8080:80" 表示主机 8080 端口映射到容器 80 端口。
depends_on 可以表达创建顺序,但普通短语法只保证依赖容器先启动,不保证服务已经完成初始化;需要等待“可用”状态时,应配合健康检查和 service_healthy。
构建并启动
在项目目录执行:
bash
docker compose up -d --build预期输出:
text
[+] Running 3/3
✔ Network <PROJECT>_default Created
✔ Container <PROJECT>-cache-1 Started
✔ Container <PROJECT>-web-1 Starteddocker compose up 会构建、创建并启动服务;使用 -d 后容器在后台运行,配置或镜像发生变化时再次执行该命令,Compose 会按需重建容器并保留已挂载的数据卷。检查服务状态:
bash
docker compose ps预期输出:
text
NAME SERVICE STATUS PORTS
<PROJECT>-web-1 web Up 0.0.0.0:8080->80/tcp
<PROJECT>-cache-1 cache Up 6379/tcp实际名称、状态文本和端口展示格式可能不同。
访问与停止
通过命令访问 Web 服务:
bash
curl http://localhost:8080预期输出:
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Compose Demo</title>
</head>
<body>
<h1>Compose is running</h1>
</body>
</html>查看实时日志可执行 docker compose logs -f。完成实验后停止项目:
bash
docker compose down预期结果:
text
web、cache 两个容器和项目默认网络被移除。按自己的节奏,确认真正理解。