Building a Docker image containing a static website

Published: Wednesday, 1 July 2020

This article shows how to build and run a simple docker image containing a static website served using Apache httpd.

Generate static content

Prepare a directory with the static content to be served. Assuming the directory chosen is ./public/, create the file ./public/hello.html with the following contents:

<html>
    <body>hello world!</body>
</html>

Create a Dockerfile

create ./Dockerfile with contents

FROM httpd:2.4
COPY ./public/ /usr/local/apache2/htdocs/

A Dockerfile contains commands used to build an image.

In the example above, FROM httpd:2.4 tells docker to start from the httpd:2.4 image, which is a bare apache2 server. This httpd image is automatically downloaded from Docker hub.

Next the COPY command will copy the static website contents from the local ./public/ directory, and place it into the document root directory in the image, /usr/local/apache2/htdocs/, for apache2 to serve.

Build the image

Build and tag the image. A tag is required so that the image can be referred to later.

$ docker build --tag my-website:20200425 .
Sending build context to Docker daemon  3.584kB
Step 1/2 : FROM httpd:2.4
2.4: Pulling from library/httpd
54fec2fa59d0: Pull complete
8219e18ac429: Pull complete
3ae1b816f5e1: Pull complete
a5aa59ad8b5e: Pull complete
4f6febfae8db: Pull complete
Digest: sha256:c9e4386ebcdf0583204e7a54d7a827577b5ff98b932c498e9ee603f7050db1c1
Status: Downloaded newer image for httpd:2.4
 ---> b2c2ab6dcf2e
Step 2/2 : COPY ./public/ /usr/local/apache2/htdocs/
 ---> d51669e2d7b5
Successfully built d51669e2d7b5
Successfully tagged my-website:20200425

In the above example the chosen tag is my-website:20200425

Run the image in a container

To start a container with the above image, use tag my-website:20200425. Map port 10080 on the host to port 80 on the container.

$ docker run --publish 10080:80 --detach --name my-website-on-port-10080 my-website:20200425
6bf3b59789dbed6143e7d26d221c4257dc8b71e047998a55688efa23ce0cd011

It will output the container ID.

Now the container is running and serving the website on port 10080

$ curl http://localhost:10080/hello.html
<html>
    <body>hello world!</body>
</html>

To stop the container use the container name or container ID.

$ docker container stop my-website-on-port-10080
my-website-on-port-10080

$ docker container stop 6bf3b59789dbed6143e7d26d221c4257dc8b71e047998a55688efa23ce0cd011
6bf3b59789dbed6143e7d26d221c4257dc8b71e047998a55688efa23ce0cd011