欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

docker-compose 详解及示例代码

程序员文章站 2023-11-19 13:48:58
docker-compose使用示例 利用docker搭建一个mysql + java service + nginx,总共4个docker容器,如果采用docker r...

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/

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