Hugo : how to run my static site in a Docker container

Overview

Using Hugo for several years now and hosting it on Netlify and really happy of the result, I ve been wondering if I could create autoamte the creation of a docker container to publish the static website in a nginx image. So here are my findings !

Using Docker to build the image

Create a dockerfile file in the root of the hugo project. The file will be use 2 images :

  • a temporary ‘build’ image will run the hugo engine to create the static content.
  • a ‘base’ image will host the nginx engine and the static website. This image will be the final result hosted in our Docker system.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Build Container
FROM alpine:latest AS build

# Install the Hugo go app (Extended version).
RUN apk add --update hugo

WORKDIR /opt/HugoApp

COPY . .

# Setup Arguments values
ARG BASE_URL=http://localhost:8100/
ENV BASE_URL=$BASE_URL

# Run Hugo to build the static website
RUN hugo --baseURL=$BASE_URL --minify

# Base Container
FROM nginx:alpine AS base

# Set workdir to Nginx html directory
WORKDIR /usr/share/nginx/html

COPY --from=build /opt/HugoApp/public .

EXPOSE 80/tcp

# Start NGinx
CMD ["nginx", "-g", "daemon off;"]

Isn’t this funny that we only have one variable in this script which is the url of the website. This url must be the url used when accessing the website. Thus in my case as I m going through CloudFlare, I should use ‘ https://myproject.mycloudflare.com ’ .

Run the script to build the image and push it to the local Docker. I m using this convention to name my images and containers :

  • hugo-{projectname} : for all images hosting a hugo static site.
  • website-{projectname} : for all websites published and running in docker.
1
docker build -t hugo-myproject .

At this stage the Image is created and ready in Docker. Now I m running the container.

1
docker run --name website-myproject -p 8100:80 -d hugo-myproject  

When I am happy with the result on my local machine, I just stop and remove the container.

1
2
docker stop website-myproject
docker rm -f website-myproject

While creating the scripts I have found some docker images related to Hugo, but I’ve decided to build mine from scratch. There is no real motivation in my choice, it was really just for the exercise.

Conclusion

After creating a few dockerfile and understanding how it is working, it s really becoming easy to automate the creation of the containers. The image is quite small (55Mb) and working pretty good.

References