案例 1:构建和部署一个多容器的 Web 应用(使用 Docker Compose)
1. 项目结构
web-app/
│
├── docker-compose.yml
├── Dockerfile-web
├── Dockerfile-db
├── nginx.conf
└── index.html
2. Dockerfile-web
创建一个简单的 Nginx 容器,用于提供静态网页:
# Dockerfile-web
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY index.html /usr/share/nginx/html/index.html
3. Dockerfile-db
创建一个 MySQL 容器,用于数据库服务:
# Dockerfile-db
FROM mysql:5.7
ENV MYSQL_ROOT_PASSWORD=rootpassword
ENV MYSQL_DATABASE=webapp
4. nginx.conf
配置 Nginx,指定静态文件目录:
# nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
5. index.html
创建一个简单的 HTML 文件:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Docker Web App</title>
</head>
<body>
<h1>Hello, Docker!</h1>
<p>This is a simple web application running with Docker.</p>
</body>
</html>
6. docker-compose.yml
编写 Docker Compose 配置文件,定义服务:
version: '3.8'
services:
web