Apache Here: How to Quickly Run httpd in the Current Directory

2020-05-31

Tags:
Categories:

Problem

You have a bunch of files representing a static site, with links relative to the document root (i.e. starting with /).

You want to see them in the browser, as if they would be in the DocumentRoot of an Apache httpd instance.

Solution

Don't move the files to a server, bring the server to the files!

Run a Docker container from the httpd image, and map the DocumentRoot directory to the current directory:

$ docker run -p 80:80 -dit --rm --name apache-here -v .:/usr/local/apache2/htdocs/ httpd:2.4

Go one step further and include the above command in a bash script which takes a directory as an argument:

#!/bin/bash

if [ $# -gt 0 ]; then
  dir=$(realpath $1)
else
  dir=$PWD
fi

docker run -p 80:80 -dit --rm --name apache-here -v "$dir":/usr/local/apache2/htdocs/ httpd:2.4

Now you can place the script somewhere in your $PATH and start it from anywhere you need it:

$ apache-here.sh

or:

$ apache-here.sh that-dir-over-there-with-the-html-files

This can be further extended with another parameter for the host port, so you can start more servers in different places. Just change the -p argument to something like -p $HOST_PORT:80.

To stop it:

$ docker stop apache-here