Building a Docker image containing a static website
This article shows how to build and run a simple docker image containing a static website served using Apache httpd.
Generate static content
Section titled “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
Section titled “Create a Dockerfile”create ./Dockerfile with contents
FROM httpd:2.4COPY ./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
Section titled “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.584kBStep 1/2 : FROM httpd:2.42.4: Pulling from library/httpd54fec2fa59d0: Pull complete8219e18ac429: Pull complete3ae1b816f5e1: Pull completea5aa59ad8b5e: Pull complete4f6febfae8db: Pull completeDigest: sha256:c9e4386ebcdf0583204e7a54d7a827577b5ff98b932c498e9ee603f7050db1c1Status: Downloaded newer image for httpd:2.4 ---> b2c2ab6dcf2eStep 2/2 : COPY ./public/ /usr/local/apache2/htdocs/ ---> d51669e2d7b5Successfully built d51669e2d7b5Successfully tagged my-website:20200425In the above example the chosen tag is my-website:20200425
Run the image in a container
Section titled “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:202004256bf3b59789dbed6143e7d26d221c4257dc8b71e047998a55688efa23ce0cd011It 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-10080my-website-on-port-10080
$ docker container stop 6bf3b59789dbed6143e7d26d221c4257dc8b71e047998a55688efa23ce0cd0116bf3b59789dbed6143e7d26d221c4257dc8b71e047998a55688efa23ce0cd011