Last active
March 8, 2019 05:21
-
-
Save aehernandez/3c12bee0a4db07a9080f8c9a05d64cc6 to your computer and use it in GitHub Desktop.
Serve files in a web server from a directory with a single command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Usage: ws.sh /path/to/directory | |
# Makes all files and directories under `directory` available from port 80 (HTTP) on your local machine | |
# Check that a path was provided | |
if [ -z "$1" ] | |
then | |
echo "No target directory provided" | |
exit 1 | |
fi | |
echo -e "Mounting `realpath $1`" | |
# As a convenience, display the machine's local ip | |
echo -e "Hostname \e[1m$(hostname -I | cut -d' ' -f1)\e[0m" | |
# The nginx configuration used to serve static files | |
# autoindex gives us a directory at the index route | |
CONF="server { listen 80; server_name _; location / { autoindex on; root /www/data/; } }" | |
# Randomely generated a name for the container | |
NAME="$(cat /dev/urandom | tr -cd 'a-f0-9' | head -c 32)" | |
# Serve the static files using nginx, mount the target directory as a volume | |
docker run --name ${NAME} -v `realpath $1`:/www/data/ -p 80:80 -d nginx >/dev/null | |
# Wait for the container to come up | |
until [ "`docker inspect -f {{.State.Running}} ${NAME}`"=="true" ]; do | |
sleep 0.1; | |
done; | |
# Add the nginx configuration | |
docker exec ${NAME} bash -c "echo '${CONF}' > /etc/nginx/conf.d/default.conf" | |
# Reload nginx to pick up this configuration | |
docker exec ${NAME} nginx -s reload &>/dev/null | |
echo "Directory hosted. Press CTRL-C to exit." | |
# Attach to the container, mainly to trap signals | |
docker attach ${NAME} &>/dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment