How to Pull a Kubernetes Image from a Private Docker Registry

How to Pull a Kubernetes Image from a Private Docker Registry

Introduction:

In today's world containerization has become popular for deploying applications efficiently. However, as the use of container grows, we need to secure our container. Public container registries, can be accessed and modified by anyone which can lead to securities issue. By using private Docker registries, we can enhance the security of our containerized applications. Private registries allow for better access control, ensuring that only authorize users can pull and push the images.

Prerequisites:

  1. A kubernetes cluster.

  2. Access to a private Docker registry.

  3. kubectl installed and configured to interact with your cluster.

  4. Docker installed on your local machine.

Step 1: Create a Docker Service Account

To pull images from a private registry, you first need to create a Docker service account and obtain the credentials.

  1. Create a Docker service account:
docker login <docker-regisry-url>

After entering the above command in docker we will be prompt for entering our docker username and password.

  1. Obtain the credentials.

    After logging in, Docker will create a configuration file at ~/.docker/config.json that contains your credentials.

Step 2: Create a Kubernetes Secret

Create a Kubernetes secret that stores your credentials. This secret will be used by Kubernetes as a authentication while accessing private registry.

kubectl create secret docker-registry <your-secret-name> \
--docker-server=<your-private-registry> \
--docker-username=<your-username> \
--docker-password=<your-password> \
--docker-email=<your-email>

Step 3: Reference the secret in Your Kubernetes Deployment

We have secret created already in last step so now it's time to reference that secret in Deployment file so that Kubernetes knows from where it needs to pull that image and it will use that credentials to provide the authentication.

  1. Create a deployment YAML file.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: <your-private-registry>/<your-image>:tag
        ports:
        - containerPort: 80
      imagePullSecrets:
      - name: <your-secret-name>
  1. Deploy the configuration:
kubectl apply -f deployment.yaml