docker-compose 启动顺序的问题depends_on

项目中遇到以下场景,我的业务依赖于mysql,业务需要在mysql启动之后再启动,使用了depends_on 发现不起作用,业务里面提示数据库无法连接,此时再单独重启下业务的就可以了。 

看下我的docker-compose.yml文件

version: "3"
services:
  web:
    build: .
    container_name: "tornadoadmin-web"
#    restart: always
    volumes: # 挂载数据卷
      - .:/app
    ports:
      - "3001:3001"
    depends_on:
      - "mysql"
  mysql: # 添加 mysql 服务
    container_name: "tornadoadmin-mysql"
    image: mysql:5.7
#    restart: always
#    ports:
#      - "3306:3306"
    volumes: # 挂载数据卷
      - ./docker_data/mysql:/var/lib/mysql
    environment:
      - TZ=Asia/Shanghai # 设置时区
      - MYSQL_ROOT_PASSWORD=root # 设置 root 用户密码
    command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --innodb_use_native_aio=0 # 设置编码
networks:
  default:
    # Use a custom driver
    driver: custom-driver-1

执行 docker-compose restart 的时候,访问业务提示 数据库不能连接。

  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 353, in __init__
    self.connect()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 664, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'tornadoadmin-mysql' ([Errno 111] Connection refused)")

 原因:

depends_on 在启动web这个容器前,并不会等待mysql这个容器进入ready状态,而只是等到它们被启动状态了。

解决方案:

下载以下项目: GitHub - vishnubob/wait-for-it: Pure bash script to test and wait on the availability of a TCP host and portPure bash script to test and wait on the availability of a TCP host and port - GitHub - vishnubob/wait-for-it: Pure bash script to test and wait on the availability of a TCP host and porthttps://github.com/vishnubob/wait-for-it


# 进入项目目录
cd tornadoadmin

# git clone
git clone https://github.com/vishnubob/wait-for-it.git

# 复制文件
cp wait-for-it/wait-for-it.sh ./

# 修改文件权限 
chmod u+x wait-for-it.sh

# 修改项目启动文件中,项目启动顺序
vi start.sh

 

将 start.sh 里面启动方式调整下

#start.sh


# 原来的启动方式
#python app.py

# 改成以下方式
# https://github.com/vishnubob/wait-for-it
./wait-for-it.sh tornadoadmin-mysql:3306 -- python app.py

docker-compose 启动顺序的问题depends_on_第1张图片

以下方式也可以:

version: "3"
services:
    redis:
        image: redis:latest
        ports:
            - "6379:6379"
        container_name: im-redis-compose
        restart: always
        command: redis-server --appendonly yes
    
    rabbitmq:
        image: rabbitmq:management
        ports:
            - "5672:5672"
            - "15672:15672"
        container_name: im-rabbitmq-compose
        environment:
            RABBITMQ_DEFAULT_USER: guest
            RABBITMQ_DEFAULT_PASS: guest
            RABBITMQ_DEFAULT_VHOST: my_vhost

    backend:
        build: .
        links:
            - redis
            - rabbitmq
        container_name: im-server-compose
        restart: on-failure
        depends_on:
            - rabbitmq
            - redis
        ports:
            - "3000:3000"
        command: sh -c './wait-for-it.sh rabbitmq:15672 -- npm run start'

你可能感兴趣的:(docker,启动顺序,depends_on)