kubernetes local docker registry code example

Example 1: how to pull private docker image in helm charts

# values.yaml
imageCredentials:
  name: credentials-name
  registry: private-docker-registry (eg: https://index.docker.io/v1/)
  username: user
  password: pass
  
replicaCount: 1
application:
  name: votingApp
  group: app
  container:
    image: votingAppImage
    port: 8080
  service:
    type: ClusterIP
    port: 8080

  config:
    name: app-config
    data:
       - key: POSTGRES_DB
         value: testdb
       - key: POSTGRES_USER
         value: postgres
       - key: POSTGRES_PASSWORD
         value: postgres
################  

### templates/imagePullSecret.yaml

{{- define "imagePullSecret" }}
{{- printf "{\"auths\": {\"%s\": {\"auth\": \"%s\"}}}" .Values.imageCredentials.registry (printf "%s:%s" .Values.imageCredentials.username .Values.imageCredentials.password | b64enc) | b64enc }}
{{- end }}

### templates/secret.yaml

apiVersion: v1
kind: Secret
metadata:
  name: {{ .Values.imageCredentials.name }}
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: {{ template "imagePullSecret" . }}
  
### templates/deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.application.name }}
  labels:
    app: {{ .Values.application.name }}
    group: {{ .Values.application.group }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app: {{ .Values.application.name }}
  template:
    metadata:
      labels:
        app: {{ .Values.application.name }}
        group: {{ .Values.application.group }}
    spec:
      containers:
        - name: {{ .Values.application.name }}
          image: {{ .Values.application.container.image }}  
          ports:
            - containerPort: {{ .Values.application.container.port }}
          envFrom:
            - configMapRef:
                name: {{ .Values.application.config.name }}
      imagePullSecrets:
        - name: {{ .Values.imageCredentials.name }}

Example 2: how to pass docker hub credentials for k8s pods

ambarishs-MacBook-Pro:gke ambarish$ kubectl create secret docker-registry private-registry-key --docker-username="devopsrecipes" --docker-password="xxxxxx" --docker-email="[email protected]" --docker-server="https://index.docker.io/v1/"secret "private-registry-key" created