docker compose 命令

概念

docker compose是一个工具,可以通过一个yml文件定义多容器的docker应用,并且可以通过一条命令去创建和管理多个容器

构建过程

  1. 编写Dockerfile文件
  2. 编写docker-compose.yml文件
  3. 通过 docker-compose up 命令启动服务

docker-compose.yml

services

  • 一个service代表一个container,这个container可以从dockerhub的image来创建,也可以从本地的Dockerfile build出来的image来创建
  • service的启动类似docker run,我们可以给其指定network和volume
...
services:
 wordpress:
  image: wordpress
  ports:
   - 8080:80
  environment:
   WORDPRESS_DB_HOST: mysql
   WORDPRESS_DB_PASSWORD: root
  networks:
   - my-bridge

 mysql:
  image: mysql
  environment:
   MYSQL_ROOT_PASSWORD: root
   MYSQL_DATABASE: wordpress
  volumes:
   - mysql-data:/var/lib/mysql
  networks:
   - my-bridge
...
...

等价于

docker run -d --network my-bridge -e WORDPRESS_DB_HOST=mysql WORDPRESS_DB_PASSWORD=root -p 8080:80 wordpress

docker run -d --network my-bridge -e MYSQL_ROOT_PASSWORD=root MYSQL_DATABASE=wordpress -v mysql-data:/var/lib/mysql mysql

volumes

自定义数据挂载,挂载container中的数据,挂载是双向的

...
...
volumes:
 mysql-data:
...
...

等价于

docker volume create mysql-data

networks

自定义网络,container与container之间天生可以通过服务名ping通

...
...
networks:
 my-bridge:
  driver: bridge 
...
...

等价于

docker networks create -d bridge my-bridge

完整docker-compose.yml

用docker-compose在docker容器中运行wordpress,数据库存储用的是mysql

# docker-compose.yml

version: '3'

services:
 wordpress:
  image: wordpress
  ports:
   - 8080:80
  environment:
   WORDPRESS_DB_HOST: mysql
   WORDPRESS_DB_PASSWORD: root
  networks:
   - my-bridge 

 mysql:
  image: mysql
  environment:
   MYSQL_ROOT_PASSWORD: root
   MYSQL_DATABASE: wordpress
  volumes:
   - mysql-data:/var/lib/mysql
  networks:
   - my-bridge

volumes:
 mysql-data:

networks:
 my-bridge:
  driver: bridge 

docker-compose常用相关命令

docker-compose up # 启动containers

docker-compose stop # 停止containers

docker-compose down # 停止并删除containers

docker-compose ps # 查看当前docker-compose.yml中运行的containers

docker-compose images # 查看当前docker-compose.yml中containers以及对应的images

docker-compose exec [sevice] /bin/bash # 进入当前docker-compose.yml中运行的[service]

Leave a Comment