Docker-compose check if mysql connection is ready

后端 未结 9 2015
一个人的身影
一个人的身影 2020-11-27 13:40

I am trying to make sure that my app container does not run migrations / start until the db container is started and READY TO accept connections.

So I decided to use

相关标签:
9条回答
  • 2020-11-27 14:15
    version: "2.1"
    services:
        api:
            build: .
            container_name: api
            ports:
                - "8080:8080"
            depends_on:
                db:
                    condition: service_healthy
        db:
            container_name: db
            image: mysql
            ports:
                - "3306"
            environment:
                MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
                MYSQL_USER: "user"
                MYSQL_PASSWORD: "password"
                MYSQL_DATABASE: "database"
            healthcheck:
                test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]
                timeout: 20s
                retries: 10
    

    The api container will not start until the db container is healthy (basically until mysqladmin is up and accepting connections.)

    0 讨论(0)
  • 2020-11-27 14:18

    RESTART ON-FAILURE

    Since v3 condition: service_healthy is no longer available. The idea is that the developer should implement mechanism for crash recovery within the app itself. However for simple use cases a simple way to resolve this issue is to use restart option.

    If mysql service status causes your application to exited with code 1 you can use one of restart policy options available. eg, on-failure

    version: "3"
    
    services:
    
        app:
          ...
          depends_on:
            - db:
          restart: on-failure
    
    0 讨论(0)
  • 2020-11-27 14:19

    I modified the docker-compose.yml as per the following example and it worked.

      mysql:
        image: mysql:5.6
        ports:
          - "3306:3306"
        volumes:       
          # Preload files for data
          - ../schemaAndSeedData:/docker-entrypoint-initdb.d
        environment:
          MYSQL_ROOT_PASSWORD: rootPass
          MYSQL_DATABASE: DefaultDB
          MYSQL_USER: usr
          MYSQL_PASSWORD: usr
        healthcheck:
          test:  mysql --user=root --password=rootPass -e 'Design your own check script ' LastSchema
    

    In my case ../schemaAndSeedData contains multiple schema and data seeding sql files. Design your own check script can be similar to following select * from LastSchema.LastDBInsert.

    While web dependent container code was

    depends_on:
      mysql:
        condition: service_healthy
    
    0 讨论(0)
提交回复
热议问题