K8s create a deployment using a private registry (GitHub/GitLab)

One of the first things I wondered when I started working with kubernetes was; how to configure my deployment to download my containers from a private registry.

The answer was given to my by one of my friends @playgali.

The solution was to use a secret.

Now I’m going to explain how to do it using the registries given by GitHub and GitLab.

Creating an authentication token.

The first step would be to create an authentication token to have access to your registry.

GitHub.

Go to Account SettingsDeveloper SettingsPersonal access tokens and click on Generate new token

Create a new token (you can set it to expire or not depending on your needs).

Check read_packages.

Copy the generated token, we will use it later on our secret.

GitLab.

Go to User SettingsAccess Tokens and create a token giving it a name and check read_registry.

Copy the generated token, we will use it later on our secret.

Create the secret.

Now use kubectl to create your secret:

kubectl create secret docker-registry [SECRET_NAME] \
 --docker-server=[SERVICE_REGISTRY] \ 
 --docker-username=[USERNAME] \
 --docker-password=[TOKEN] \
 --docker-email=[EMAIL]

Where:

  • [SECRET_NAME] is the name of your secret and you will use it lather in deployment, for example: mysecret.
  • [SERVICE_REGISTRY] is your registry domain.
    • For GitHub: ghcr.io
    • For GitLab: registry.gitlab.com

Configure your deployment.

Now you can add the section imagePullSecrets in your deployment.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mydeployment
spec:
  ...
    spec:
      imagePullSecrets:
        - name: mysecret
      containers:
        - image: registry.gitlab.com/myuser/myproject:latest
	...

Pay special attention to:

imagePullSecrets:
        - name: mysecret

And that’s all, your deployment will be authenticated and download your container’s image to create your pods.

Like