close

Running Hugo Website From Docker Container

Building Hugo website then serving the static files from caddy web server all contained inside a docker container.

We are using Hugo docker image to build static files of our site, then move those static files inside Caddy web server, which is going to serve those files for our website.

  • Start with creating Caddyfile into your project folder. It is a config file for the Caddy web server. We will configure it as a static file server.

  • Configuring Caddy to serve static files from /srv folder as the root of our website. You can change it as per your needs.

  • [optional] You can add your domain to leverage automatic https features of Caddy.

example.com

root * /srv
file_server

Once the web server has been configured, we may proceed with the creation of the website image.

  • Create a Dockerfile. which serves as the means to create our website image.

  • Hugo docker image; It comes in two flavors, ext and non-ext, use ext images if you need Hugo extended version to build your website. Some sites requires extended version to properly compile the whole website.

  • Compile your website via hugo image, which will generate static files inside the /public folder.

  • Caddy docker image; copy our Caddyfile into /etc/caddy/Caddyfile.

  • Then copy all the static files from hugo to the caddy. Copy it to the folder which is configured in Caddyfile to serve as a fileserver.

FROM klakegg/hugo:latest-ext AS build-stage
WORKDIR /src
COPY . .

# compile the website into /src/public/ folder
RUN hugo

#---------------------------------------------------
FROM caddy:latest
COPY Caddyfile /etc/caddy/Caddyfile
# copy build files to /srv
COPY --from=build-stage /src/public /srv

After finishing our Dockerfile and Caddyfile.

  • We can build the image by executing docker build command.
docker build -t hugo-website .
  • Create and run a container from the hugo-website image. caddy_data and caddy_confg volumes are necessary to properly run caddy web server.
docker run -d -p 80:80 -p 443:443 -p 443:443/udp -v ${PWD}/caddy_data:/data -v ${PWD}/caddy_config:/config hugo-website

Now the container should be serving the static website.