简体   繁体   中英

How to make docker wait for SQL script inside /docker-entrypoint-initdb.d to be executed

I am dockerizing an application with two services in docker-compose.yml: a web image build from php:7.3.28-apache and a database image build from postgres:11.12-alpine. Inside database Dockerfile I am executing a sql file to populate the database by doing:

COPY./dump.sql /docker-entrypoint-initdb.d/

In my web image I do a migration. But the migration should only occur after the database end executing the sql file. So I use the wait-for-it.sh script to wait for the database port to be available:

CMD composer install ; wait-for-it -t 0 db:5432 -- bin/console doctrine:migrations:migrate ; apache2-foreground

The problem is that the port db:5432 becomes available before dump.sql file end execution.

I already tried

depends_on:
    - db

in docker-compose.yml and the problem persists. Is there a way to lock the port db:5432 until dump is done, or a way to make web service to wait for the end of dump execution in db service?

Solution is to utilise HEALTHCHECK [OPTIONS] CMD command

The command after the CMD keyword can be either a shell command (eg HEALTHCHECK CMD /bin/check-running ) or an exec array (as with other Dockerfile commands; see eg ENTRYPOINT for details).

The command's exit status indicates the health status of the container. The possible values are:

0: success - the container is healthy and ready for use

1: unhealthy - the container is not working correctly

2: reserved - do not use this exit code

Probably you can create some shell script

#!/bin/sh

# if your last table exists we assume may be 
# we are now ready for migration 
# put whatever logic you have to ensure data import was successful

# if file exits then exit code 0 else exit code 1
[ -f  "/path/to/my/last/table" ] && exit 0 || exit 1

In docker-compose.yml you need

depends_on:
      database:
           condition: service_healthy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM