编写规则
官方文档:https://docs.docker.com/compose/compose-file/compose-file-v3/
主要分为三层
# 第一层 版本,与docker版本对应,向下兼容。最新为3.9
version: '3.9'
# 第二层 服务
services:
# 服务一
web:
# 服务配置
images:
bulid:
ports:
network:
...
redis:
...
mysql:
...
# 第三层 其他配置,如:网络、数据卷、全局配置
networks:
frontend:
backend:
volumes:
db-data:
configs:
官方实例
可根据上述三层,参考下官方例子
version: "3.9"
services:
redis:
image: redis:alpine
ports:
- "6379"
networks:
- frontend
deploy:
replicas: 2
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure
db:
image: postgres:9.4
volumes:
- db-data:/var/lib/postgresql/data
networks:
- backend
deploy:
placement:
max_replicas_per_node: 1
constraints:
- "node.role==manager"
vote:
image: dockersamples/examplevotingapp_vote:before
ports:
- "5000:80"
networks:
- frontend
depends_on:
- redis
deploy:
replicas: 2
update_config:
parallelism: 2
restart_policy:
condition: on-failure
result:
image: dockersamples/examplevotingapp_result:before
ports:
- "5001:80"
networks:
- backend
depends_on:
- db
deploy:
replicas: 1
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure
worker:
image: dockersamples/examplevotingapp_worker
networks:
- frontend
- backend
deploy:
mode: replicated
replicas: 1
labels: [APP=VOTING]
restart_policy:
condition: on-failure
delay: 10s
max_attempts: 3
window: 120s
placement:
constraints:
- "node.role==manager"
visualizer:
image: dockersamples/visualizer:stable
ports:
- "8080:8080"
stop_grace_period: 1m30s
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
deploy:
placement:
constraints:
- "node.role==manager"
networks:
frontend:
backend:
volumes:
db-data:
实战案例
搭建一个WordPress博客。
官方文档:https://docs.docker.com/samples/wordpress/
创建文件夹
用来存放项目文件
mkdir -p /test/wordpress
cd /test/wordpress
docker-compose.yml
创建docker-compose.yml文件
vim docker-compose.yml
输入以下内容
version: "3.9"
services:
db:
image: mysql:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: somewordpress
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
wordpress:
depends_on:
- db
image: wordpress:latest
volumes:
- wordpress_data:/var/www/html
ports:
- "8000:80"
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
volumes:
db_data: {}
wordpress_data: {}
启动Docker Compose
# 前台启动
docker-compose up
# 后台启动
docker-compose up -d
前台启动,Ctrl+c就能停止
后台启动成功
访问
浏览器ip:8000,如我的192.168.227.3:8000
以上如有错误,麻烦大家评论指正