To build the app as a container image we will create a simple Dockerfile.
It consists of a multistage build with two stages:
- Stage 1: Install dependencies and build the app from a Golang image
- Stage 2: Copy the final binary into the runtime image
You can build the image as follows:
docker build . -t k8s-admission-controller:latest
Test the image is running fine
If you try to run a container from this image without any argument it will try to load certificates from the default location. Since there is none in the image execution will fail:
docker run -it k8s-admission-controller
E0325 22:53:33.427023 1 main.go:32] Filed to load key pair: open /etc/certs/app.crt: no such file or directory
E0325 22:53:33.427023 1 main.go:32] glog: exiting because of error: log: cannot create log: open /tmp/k8s-admission-controller.2fbeb4dcab82.webhook.log.INFO.20230325-225333.1: no such file or directory
You can pass the local directory ($PWD) as a volume and mount it in the /etc/certs
folder. Ex:
docker run -it -v $PWD/certs:/etc/certs k8s-admission-controller -logtostderr
Once you make sure the image is working as expected you can push it to your Container Registry (CR). In my case, that's ghcr.io
.
Retag the image to match your CR:
docker tag k8s-admission-controller ghcr.io/felipempda/k8s-admission-controller
Login to the CR with your user and Personal Access Token.
docker login
And push the image:
docker push ghcr.io/felipempda/k8s-admission-controller
You can also set up a workflow to that automatically for you.