├── Dockerfile ├── README.md └── entrypoint.sh /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.6 2 | 3 | ADD entrypoint.sh /usr/local/bin/entrypoint.sh 4 | 5 | ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Example usage: 2 | 3 | Sample `docker-compose.yml`: 4 | 5 | ```yaml 6 | version: '2' 7 | services: 8 | the_database: 9 | image: ubuntu:14.04 10 | command: > 11 | /bin/bash -c " 12 | sleep 5; 13 | nc -lk 0.0.0.0 5432; 14 | " 15 | another_service: 16 | image: ubuntu:14.04 17 | command: > 18 | /bin/bash -c " 19 | sleep 8; 20 | nc -lk 0.0.0.0 5555; 21 | " 22 | 23 | the_web_server: 24 | image: ubuntu:14.04 25 | depends_on: 26 | - the_database 27 | - another_service 28 | command: > 29 | /bin/bash -c " 30 | nc -z the_database 5432 && 31 | echo Connected to DB and started! 32 | " 33 | 34 | start_dependencies: 35 | image: dadarek/wait-for-dependencies 36 | depends_on: 37 | - the_database 38 | - another_service 39 | command: the_database:5432 another_service:5555 40 | ``` 41 | 42 | Then, to guarantee that `the_database` and `another_service` are ready before running `the_web_server`: 43 | 44 | ```bash 45 | $ docker-compose run --rm start_dependencies 46 | # Some output from docker compose 47 | $ docker-compose up the_web_server 48 | ``` 49 | 50 | By default, there will be a 2 second sleep time between each check. You can modify this by setting the `SLEEP_LENGTH` environment variable: 51 | 52 | ```yaml 53 | start_dependencies: 54 | image: dadarek/wait-for-dependencies 55 | environment: 56 | - SLEEP_LENGTH: 0.5 57 | ``` 58 | 59 | By default, there will be a 300 seconds timeout before cancelling the wait_for. You can modify this by setting the `TIMEOUT_LENGTH` environment variable: 60 | 61 | ```yaml 62 | start_dependencies: 63 | image: dadarek/wait-for-dependencies 64 | environment: 65 | - SLEEP_LENGTH: 1 66 | - TIMEOUT_LENGTH: 60 67 | ``` 68 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | : ${SLEEP_LENGTH:=2} 4 | : ${TIMEOUT_LENGTH:=300} 5 | 6 | wait_for() { 7 | START=$(date +%s) 8 | echo "Waiting for $1 to listen on $2..." 9 | while ! nc -z $1 $2; 10 | do 11 | if [ $(($(date +%s) - $START)) -gt $TIMEOUT_LENGTH ]; then 12 | echo "Service $1:$2 did not start within $TIMEOUT_LENGTH seconds. Aborting..." 13 | exit 1 14 | fi 15 | echo "sleeping" 16 | sleep $SLEEP_LENGTH 17 | done 18 | } 19 | 20 | for var in "$@" 21 | do 22 | host=${var%:*} 23 | port=${var#*:} 24 | wait_for $host $port 25 | done 26 | --------------------------------------------------------------------------------