Search code examples
kuberneteskubectlminikubedockerhubkubernetes-secrets

How to use Kubernetes Secret to pull a private docker image from docker hub?


I'm trying to run my kuberntes app using minikube on ubuntu20.04 and applied a secret to pull a private docker image from docker hub, but it doesn't seem to work correctly.

Failed to pull image "xxx/node-graphql:latest": rpc error: code = Unknown desc = Error response from daemon: pull access denied for xxx/node-graphql, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

Here's the secret generated by

kubectl create secret generic regcred \                     
    --from-file=.dockerconfigjson=<pathtofile>.docker/config.json \
    --type=kubernetes.io/dockerconfigjson

And here's the secret yaml file I have created

apiVersion: v1
data:
  .dockerconfigjson: xxx9tRXpNakZCSTBBaFFRPT0iCgkJfQoJfQp9
kind: Secret
metadata:
  name: node-graphql-secret
  uid: xxx-2e18-44eb-9719-xxx
type: kubernetes.io/dockerconfigjson

Did anyone try to pull a private docker image into Kubernetes using a secret? Any kind of help would be appreciated. Thank you!


Solution

  • I managed to add the secrets config in the following steps.

    First, you need to login to docker hub using:

    docker login
    

    Next, you create a k8s secret running:

    kubectl create secret generic <your-secret-name>\\n    --from-file=.dockerconfigjson=<pathtoyourdockerconfigfile>.docker/config.json \\n    --type=kubernetes.io/dockerconfigjson
    

    And then get the secret in yaml format

    kubectl get secret -o yaml
    

    It should look like this:

    apiVersion: v1
    items:
    - apiVersion: v1
      data:
        .dockerconfigjson: xxxewoJImF1dGhzIjogewoJCSJodHRwczovL2luZGV4LmRvY2tl
      kind: Secret
      metadata:
        creationTimestamp: "2022-10-27T23:06:01Z"
        name: <your-secret-name>
        namespace: default
        resourceVersion: "513"
        uid: xxxx-0f12-4beb-be41-xxx
      type: kubernetes.io/dockerconfigjson
    kind: List
    metadata:
      resourceVersion: ""
    

    And I have copied the content for the secret in the secret yaml file:

    apiVersion: v1
    data:
      .dockerconfigjson: xxxewoJImF1dGhzIjogewoJCSJodHRwczovL2luZGV4LmRvY2tlci
    kind: Secret
    metadata:
      creationTimestamp: "2022-10-27T23:06:01Z"
      name: <your-secret-name>
      namespace: default
      resourceVersion: "513"
      uid: xxx-0f12-4beb-be41-xxx
    type: kubernetes.io/dockerconfigjson
    

    It works! This is a simple approach to using Secret to pull a private docker image for K8s.

    As a side note, to apply the secret, run kubectl apply -f secret.yml

    Hope it helps