docker Compose
Docker Compose
Basic Operations
| Command | Description | Example Command |
|---|---|---|
docker-compose up | Create and start containers according to the docker-compose.yml. | docker-compose up |
docker-compose down | Stop and remove containers, networks, images, and volumes. | docker-compose down |
Service Management
| Command | Description | Example Command |
|---|---|---|
docker-compose start | Start existing containers. | docker-compose start |
docker-compose stop | Stop running containers without removing them. | docker-compose stop |
docker-compose restart | Restart services. | docker-compose restart |
docker-compose pause | Pause services. | docker-compose pause |
docker-compose unpause | Unpause services. | docker-compose unpause |
Configuration and Inspection
| Command | Description | Example Command |
|---|---|---|
docker-compose config | Validate and view the Compose file. | docker-compose config |
docker-compose ps | List containers. | docker-compose ps |
docker-compose logs | View output from containers. | docker-compose logs |
docker-compose exec | Execute a command in a running container. | docker-compose exec web bash |
compose文件结构
docker-compose.yml通常需要包含以下几个顶级元素:version已弃用,早期版本需要此元素。services必要元素,定义一个或多个容器的运行参数,在services中可以通过以下元素定义容器的运行参数image容器 镜像ports端口映射environment环境变量networks容器使用的网络volumes容器挂载的存储卷command容器启动时执行的命令depends_on定义启动顺序- 复数形式(例如
ports,networks,volumes,depends_on)参数需要传入列表
networks创建自定义网络volumes创建存储 卷
Yaml 文件格式
- 缩进代表上下级关系
- 缩进时不允许使用Tab键,只允许使用空格
:键值对,后面必须有空格-列表,后面必须有空格[ ]数组#注释{key:value,k1:v1}map|多行文本块
如果一个文件中包含多个文档
---表示一个文档的开始
healthcheck
healthcheck在Docker Compose中用于检查容器内服务的健康状态。它可以定期运行命令来验证服务是否正常运作。对于MySQL容器,healthcheck通常会检查MySQL服务是否已经开始在预期端口上监听请求。
通过在Docker Compose文件中定义healthcheck,你可以设定一系列条件和检测手段,Docker会根据这些条件自动检测服务状态。如果服务未按预期运行,healthcheck可以帮助快速发现问题。
数据库启动问题
数据库初始化完成之前,不会建立connections。
depends_on只能保证容器的启动和销毁顺序,不能确保依赖的容器是否ready。
要确保应用服务在数据库初始化完成后再启动,需要配合condition和healthcheck使用。
condition有三种状态:
service_started容器已启动service_healthy容器处于健康状态service_completed_successfully容器执行完成且成功退出(退出状态码为0)
应用程序启动问题
和mysql一样,应用程序启动启动并并不关系服务是否有异常,需要healthcheck去确定。