使用 Compose 构建多容器应用
使用 Docker Compose 编排多个 Docker 容器,例如 Web 应用和数据库,以支持本地开发。
使用 Compose 构建多容器应用 是 CoddyKit 上的免费 Docker & Kubernetes for Developers 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Docker & Kubernetes for Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Docker & Kubernetes for Developers 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Multi-Container Apps?
In real-world applications, you rarely have just one component. Imagine a web application: you need a web server (like Nginx), a backend application (like Python Flask), and a database (like Redis or PostgreSQL).
Each of these components has its own dependencies and configuration. Managing them individually and ensuring they communicate correctly can quickly become complex.
Meet Docker Compose
Docker Compose is a tool designed to simplify the process of defining and running multi-container Docker applications.
- You define your entire application's services (containers) in a single YAML file.
- Then, with one simple command, Compose creates and starts all the services for you.
- It's incredibly useful for local development and testing environments.
The Compose YAML File
The heart of Docker Compose is the docker-compose.yml file. This YAML file describes your application's services, networks, and volumes.
It typically starts with a version key, followed by the main services section where you define each container that makes up your application.
Defining Services
Under the services section, you list each component of your application. Each service corresponds to a Docker container.
Key properties for defining a service include:
image: Specifies the Docker image to use (e.g.,nginx:latest).build: Provides the path to a directory containing aDockerfileto build a custom image.container_name: An optional, fixed name for your container, making it easier to reference.
Exposing & Configuring Services
You often need to expose your services to the host machine or configure them with environment variables.
ports: Maps ports from the host to the container (e.g.,"8080:80"maps host port 8080 to container port 80).environment: Passes environment variables into the container (e.g.,DB_HOST: "database").
These settings are crucial for communication and customization.
Connecting Your Services
When you use Docker Compose, it automatically creates a default network for your application. All services defined in your docker-compose.yml file join this network.
This allows services to communicate with each other using their service names as hostnames. For example, a web app service can connect to a database service named redis by simply using redis as the hostname.
Example: Python + Redis
Let's build a simple multi-container application: a Python Flask web app that counts how many times it has been visited, storing the count in a Redis database.
This setup clearly shows how a 'web' service can interact with a 'database' service within a single Compose application.
Web App Code & Dockerfile
Here's our simple Python Flask application (app.py) and its Dockerfile. The Flask app connects to the redis service, and the Dockerfile packages it all up.
# app.py
import time
import redis
from flask import Flask
app = Flask(__name__)
# Connects to 'redis' service in Compose network
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello from CoddyKit! I have been seen {} times.\n'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
# requirements.txt
# flask
# redis
# Dockerfile
FROM python:3.9-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]
Your First Compose File
This docker-compose.yml ties everything together. It defines two services: web (our Python app, built from the current directory) and redis (using the official Redis image).
Try running this example!
version: '3.8'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"Managing Your Compose App
To start your multi-container application in detached mode (in the background), navigate to the directory containing your docker-compose.yml and supporting files, then run:
docker compose up -dTo see the running services and their status:
docker compose psTo stop and remove the containers, networks, and volumes created by Compose:
docker compose downCompose Configuration Check
Consider the following docker-compose.yml snippet:
version: '3.8'
services:
app:
build: .
ports:
- "8080:80"
database:
image: "postgres:13"Which statement is TRUE about this configuration?
Recap: Docker Compose
You've learned how Docker Compose simplifies managing multi-container applications for local development!
- It uses a
docker-compose.ymlfile to define all your services. - Services can communicate with each other using their service names on a default network.
- Commands like
docker compose upanddocker compose downmanage your entire application stack with ease.
Docker Compose is an essential tool for local development setups involving multiple Docker containers.
常见问题解答
「使用 Compose 构建多容器应用」课时是免费的吗?
是的 — 「使用 Compose 构建多容器应用」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Docker & Kubernetes for Developers 课程的其余内容,请升级到 CoddyKit PRO。 Docker & Kubernetes for Developers 课程共包含 4 节课。
「使用 Compose 构建多容器应用」这节课中我会学到什么?
使用 Docker Compose 编排多个 Docker 容器,例如 Web 应用和数据库,以支持本地开发。 你通过在浏览器中直接运行的动手代码来练习 Docker & Kubernetes for Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Docker & Kubernetes for Developers 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Docker & Kubernetes for Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 Compose 构建多容器应用」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Docker & Kubernetes for Developers 课中编写并运行代码吗?
能。每节 Docker & Kubernetes for Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 编写用于构建镜像的 Dockerfile
- 构建自定义 Docker 镜像
- 使用 Compose 构建多容器应用
- 使用 Docker 卷持久化数据