← | posts / mdbook with Gitlab Pages (CI/CD) | 2020-04-05

I use mdbook for many of my project documentations and tutorials. My usual workflow was to update the documentation, run mdbook build and then push the HTML files to GitLab.

However, I wanted to automate the build process and wondered how hard it would be to implement it with GitLab CI/CD to build the documentation on GitLab’s servers before it’s deployed as a Page. Turns out it’s really easy!

Update [2020-05-24]: I created a template repository that you can find here: https://gitlab.com/yethiel/pages-mdbook.

The mdbook user guide suggests to get mdbook with cargo. However, that method downloads the source and compiles it every time which adds more than five minutes to the deploy process. I decided to just download the binaries instead which saves time and resources.

Here’s how to do it

Initialize your repository with mdbook:

mdbook init

Then adjust the book.toml so the build-dir points to public:

authors = [""]
language = "en"
multilingual = false
src = "src"
title = "GitLab Pages mdbook Template"

build-dir = "public"

command = "./mdbook-toc"
renderer = ["html"]

Then create a .gitlab-ci.yml file in your repository and paste the following contents:

  stage: deploy
  - wget https://github.com/badboy/mdbook-toc/releases/download/0.2.4/mdbook-toc-0.2.4-x86_64-unknown-linux-gnu.tar.gz
  - wget https://github.com/rust-lang/mdBook/releases/download/v0.3.7/mdbook-v0.3.7-x86_64-unknown-linux-gnu.tar.gz
  - tar xvzf mdbook-v0.3.7-x86_64-unknown-linux-gnu.tar.gz
  - tar xvzf mdbook-toc-0.2.4-x86_64-unknown-linux-gnu.tar.gz
  - ./mdbook build
    - public
  - master

You can get the link to the most recent version of mdbook here and update it.

Every time you push your changes, it will download and unpack the release binary of mdbook (only 2-3mb) and mdbook-toc. Then it’ll run mdbook build and generate HTML in the public folder (as we told it to in the book.toml file).

That’s enough to automatically build your mdbook every time you push changes to your Repository on GitLab. You can safely delete or add your local public folder to gitignore.

Here’s another example for a repository where I set this up: https://gitlab.com/re-volt/content-tutorial/

More minimal setup without mdbook-toc

Optionally, you can leave out the following lines for a more minimal setup but you won’t be able to generate tables of contents with <!-- toc -->.


command = "./mdbook-toc"
renderer = ["html"]


  - wget https://github.com/badboy/mdbook-toc/releases/download/0.2.4/mdbook-toc-0.2.4-x86_64-unknown-linux-gnu.tar.gz
  - tar xvzf mdbook-toc-0.2.4-x86_64-unknown-linux-gnu.tar.gz