Skip to content

Instantly share code, notes, and snippets.

@adamburgess
Created June 16, 2018 06:42
Show Gist options
  • Save adamburgess/fe726cce6ab137e7a59a2316979458af to your computer and use it in GitHub Desktop.
Save adamburgess/fe726cce6ab137e7a59a2316979458af to your computer and use it in GitHub Desktop.
Starts nginx in the current directory, and tails the log output. When the script exits, nginx is also closed. By default it starts on port 8000, but it will try more ports if that isn't available. Start on a different port by passing it as the first param.
#!/bin/bash
errcho() { echo "$@" 1>&2; }
stop() {
errcho
echo "Stopped"
if [[ $started -eq 1 ]]; then
pid=$(< $FILE_PID)
errcho "Killing nginx $pid"
kill $pid
else
errcho "$nginx_output"
fi
if [[ $temp ]]; then
rm -rf $temp
fi
trap - EXIT
exit 0;
}
trap stop EXIT
port_is_free() {
port=$1
(echo "" >/dev/tcp/127.0.0.1/$port) >/dev/null 2>&1
if [[ $? -eq 0 ]]; then
return 1
fi
return 0
}
find_port() {
i=${1:-8000}
while :
do
port_is_free $i
retval=$?
if [[ $retval -eq 0 ]]; then
echo $i
exit 0
fi
errcho "Port $i in use, checking next"
i=$((i+1))
done
}
# temp
temp=$(mktemp -d)
FILE_ERROR=$temp/error.log
FILE_ACCESS=$temp/access.log
FILE_PID=$temp/nginx.pid
DIR_ROOT=$(pwd)
PORT=$(find_port $1)
config=$(cat <<EOF
error_log $FILE_ERROR;
worker_processes auto;
pid $FILE_PID;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log $FILE_ACCESS;
gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
server {
listen $PORT;
root $DIR_ROOT;
autoindex on;
}
}
EOF
)
errcho "Starting nginx to serve files in $DIR_ROOT on port $PORT"
echo "$config">$temp/nginx.conf
# start and get pid
started=0
nginx_output=$(nginx -c $temp/nginx.conf 2>&1) || stop;
errcho "Started!"
started=1
# tail the log files
tail -qf $FILE_ERROR $FILE_ACCESS
# ok, tail is finished. this calls the trap above
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment