当前位置:首页 >> 服务器

docker-compose 详解及示例代码

docker-compose使用示例

利用docker搭建一个mysql + java service + nginx,总共4个docker容器,如果采用docker run的方式一个一个容器去创建十分麻烦。为了能更高效的批量创建容器,docker推出了docker-compose工具,只需要定义一个docker-compose.yml文件即可快速搞定一组容器的创建,

mysql:
 image: daocloud.io/yjmyzz/mysql-osx:latest
 volumes:
   - ./mysql/db:/var/lib/mysql
 ports:
   - 3306:3306
 environment:
   - MYSQL_ROOT_PASSWORD=123456
 
service1:
 image: java:latest
 volumes:
   - ./java:/opt/app
 expose:
   - 8080
 #ports:
 #  - 9081:8080
 links:
   - mysql:default
 command: java -jar /opt/app/spring-boot-rest-framework-1.0.0.jar
 
service2:
 image: java:latest
 volumes:
   - ./java:/opt/app
 expose:
   - 8080
 #ports:
 #  - 9082:8080
 links:
   - mysql:default
 command: java -jar /opt/app/spring-boot-rest-framework-1.0.0.jar
 
nginx1:
  image: nginx:latest
  volumes:
   - ./nginx/html:/usr/share/nginx/html:ro
   - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
   - ./nginx/conf.d:/etc/nginx/conf.d:ro
  #expose:
  #  - 80
  ports:
   - "80:80"
  links:
   - service1:service1
   - service2:service2

内容不复杂,具体的关键字说明见本文最后的参考文章链接。

问题:这个文件放在哪里?

参见下面的目录结构:

mysql-java-nginx
├── docker-compose.yml
├── java
│  └── spring-boot-rest-framework-1.0.0.jar
├── mysql
│  └── db
└── nginx
  ├── conf
  ├── conf.d
  │  └── default.conf
  ├── html
  │  └── index.html
  └── nginx.conf
 

创建容器:

cd mysql-java-nginx
docker-compose up

就是这么简单,一个up就搞定了所有容器的创建,up通常用于首次创建,可以观察终端实时输出的日志内容判断容器是否启动正常,如果没什么问题,直接Ctrl+C退出,然后

docker-compose start

以后台方式启动容器。  

其它命令还有:

Commands:
 build       Build or rebuild services
 help        Get help on a command
 kill        Kill containers
 logs        View output from containers
 pause       Pause services
 port        Print the public port for a port binding
 ps         List containers
 pull        Pulls service images
 restart      Restart services
 rm         Remove stopped containers
 run        Run a one-off command
 scale       Set number of containers for a service
 start       Start services
 stop        Stop services
 unpause      Unpause services
 up         Create and start containers
 migrate-to-labels Recreate containers to add labels
 version      Show the Docker-Compose version information

基本上看名字就知道意思了。  

参考文章:

https://docs.docker.com/compose/compose-file/

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!