
Module 7 Lesson 5: Optimizing Builds (Kaniko)
Faster, Safer, Better. Learn how to use Google's Kaniko to build container images without root privileges or a Docker daemon, solving the performance issues of DinD.
Module 7 Lesson 5: Optimizing builds with Kaniko
In Lesson 1, we used DinD. But DinD has two problems:
- Security: It requires "Privileged Mode" on the server.
- Speed: It cannot easily share layers between builds, making it slow.
Kaniko is a tool built by Google to solve these exact problems.
1. What is Kaniko?
Kaniko builds Docker images without Docker.
- It looks at every line in your Dockerfile and executes it inside the runner's standard filesystem.
- Because it doesn't need a "Daemon," it is safer and can run on any standard GitLab runner.
2. Using Kaniko in GitLab CI
build-with-kaniko:
stage: build
image:
name: gcr.io/kaniko-project/executor:debug
entrypoint: [""]
script:
- /kaniko/executor
--context "$CI_PROJECT_DIR"
--dockerfile "$CI_PROJECT_DIR/Dockerfile"
--destination "$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG"
3. The Power of "Remote Caching"
The best feature of Kaniko is the --cache flag.
- It can push its intermediate layers to your registry.
- If "Job A" already built the
npm installlayer, "Job B" will just download that layer from the registry instead of running the command again. - Result: Build times drop from 5 minutes to 30 seconds.
4. Why Use It?
- Strict Security: If your company forbids "Privileged" containers, Kaniko is your only choice.
- Kubernetes: Kaniko is the native way to build images inside a Kubernetes cluster.
Exercise: The Speed Test
- Take a project that takes >1 minute to build with DinD.
- Rewrite the build job to use Kaniko.
- Add the
--cache=trueflag. - Run the pipeline twice. How much time did the second run save?
- Why does the Kaniko job use
entrypoint: [""]? (Research: "GitLab CI entrypoint override"). - Look at your Container Registry. Do you see a new folder/tags created by Kaniko's cache?
Summary
You have completed Module 7: Containerized Pipelines. You now have the skills to build, push, and deploy containers using the most modern and secure tools available in the industry, from the simplicity of the GitLab Registry to the advanced optimization of Kaniko.
Next Module: Watching the vitals: Module 8: Monitoring and Notifications.