docker-compose的yml文件中常用选项

1. 从一个示例说起

先看一下这个示例,先不用理解,因为接下来我们将解释其中各选项

version: '3'
services:
  auth:
    image: 'harbocto.xxx.com.cn/crust/crust-auth:1.0.0'
    restart: always
    container_name: auth
    networks:
      - crust-net
    volumes:
      - ./logs:/app/logs/
    ports:
      - '10001:10001'
    environment:
      JAVA_OPTS: "-Djava.security.egd=file:/dev/./urandom"
      WAIT_HOSTS: "redis:6379,postgre:5432,nacos:8848"
      NACOS_SERVER: "nacos:8848"
      NACOS_SERVER_USERNAME: "nacos"
      NACOS_SERVER_PASSWORD: "nacos"
  user:
    image: 'harbocto.xxx.com.cn/crust/crust-user:1.0.0'
    restart: always
    container_name: user
    networks:
      - crust-net
    volumes:
      - ./logs:/app/logs/
    ports:
      - '10002:10002'
    environment:
      JAVA_OPTS: "-Djava.security.egd=file:/dev/./urandom"
      WAIT_HOSTS: "redis:6379,postgre:5432,nacos:8848"
      NACOS_SERVER: "nacos:8848"
      NACOS_SERVER_USERNAME: "nacos"
      NACOS_SERVER_PASSWORD: "nacos"
  gateway:
    image: 'harbocto.xxx.com.cn/crust/crust-gateway:1.0.0'
    restart: always
    container_name: gateway
    depends_on:
    - auth
    networks:
      - crust-net
    volumes:
      - ./logs:/app/logs/
    ports:
      - '10000:10000'
    environment:
      JAVA_OPTS: "-Djava.security.egd=file:/dev/./urandom"
      WAIT_HOSTS: "auth:10001,redis:6379,postgre:5432,nacos:8848"
      NACOS_SERVER: "nacos:8848"
      NACOS_SERVER_USERNAME: "nacos"
      NACOS_SERVER_PASSWORD: "nacos"
networks:
 crust-net:
   external:
     name: postgre_crust-net

2. 常用选项

2.1 images

  • 作用: 指定镜像
  • 示例: 如 示例

2.2 restart

  • 作用: 容器重启策略
  • 示例:
restart: always

no,默认策略,在容器退出时不重启容器
on-failure,在容器非正常退出时(退出状态非0),才会重启容器
on-failure:3,在容器非正常退出时重启容器,最多重启3次
always,在容器退出时总是重启容器
unless-stopped,在容器退出时总是重启容器,但是不考虑在Docker守护进程启动时就已经停止了的容器

2.3 container_name

  • 作用: 给启动的容器命名
  • 示例:
    示例
container_name: auth

2.4 ports

  • 作用: 端口映射,将容器内端口映射到宿主机
  • 示例:
    ports:
     - 10002:10002
     - 10003:10003/udp

2.5 depends_on

  • 作用: 设置service之间的依赖

  • 示例:

version: '2'
services:
  user:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgre

说明:user服务依赖于db和redis。

2.6 volumes

  • 作用: 将容器中目录挂着到宿主机(宿主机覆盖容器中目录)
  • 示例:
    将容器中的 /app/logs 目录挂着到宿主机docker-compose所在目录的 logs目录。
    volumes:
      - ./logs:/app/logs/

2.7 environment

《docker-compose中变量的使用》

2.8 networks

《docker-compose网络》

2.9 command

  • 作用: 启动时执行的命令(将覆盖原有启动命令)

  • 示例:

command: ["/bin/sh","-c","while true;do echo hello;sleep 1;done"]

运行如下:
在这里插入图片描述

posted on 2021-12-21 19:58  运维开发玄德公  阅读(14)  评论(0编辑  收藏  举报  来源

导航