Pete Freitag Pete Freitag

Bash Loop To Wait for Server to Start

Published on April 08, 2020
By Pete Freitag
linux

I had a client working on setting up Fixinator to start up the Fixinator Enterprise Scanning server to run within their Continuous Integration pipeline. The CI script needs to pause or sleep for a few seconds while the server starts up.

I came up with a generic bash script that will loop and and attempt to ping the server using curl (makes a HTTP request), then sleep. For a script like this you don't want it to run forever, so it will timeout after a certain number of attempts.

Here's my script to loop and wait for the server to start:

#!/bin/bash

#start fixinator server in background process
docker-compose up &

max_iterations=10
wait_seconds=6
http_endpoint="http://127.0.0.1:1234/up/"

iterations=0
while true
do
	((iterations++))
	echo "Attempt $iterations"
	sleep $wait_seconds

	http_code=$(curl --verbose -s -o /tmp/result.txt -w '%{http_code}' "$http_endpoint";)

	if [ "$http_code" -eq 200 ]; then
		echo "Server Up"
		break
	fi

	if [ "$iterations" -ge "$max_iterations" ]; then
		echo "Loop Timeout"
		exit 1
	fi
done

If you are using this shell script for a different purpose, you will probably want to change docker-compose up & to another command to start your server. In my case I'm waiting for the docker container to load and start. You will want to keep the & at the end, that tells bash to run that command in the background, and allows the rest of the script to continue.

You will also want to change the http_endpoint variable to point to your server's endpoint.

Finally you may wish to change max_iterations and wait_seconds to match your needs.

That's all there is to it, you will want to make sure you have curl installed, which is installed by default on most Mac OSX or Linux OS's but may be missing in many docker containers.



bash docker shell linux

Bash Loop To Wait for Server to Start was first published on April 08, 2020.

If you like reading about bash, docker, shell, or linux then you might also like:

Weekly Security Advisories Email

Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).