How to run GCP Cron job in privilege mode

50 Views Asked by At

We have a GCP Cron job which pull docker image from Google Container Registry using docker command.

The image running by Cron job use docker:dind as the base image, when I tried to run the image on my local, I found that I have to add '--privileged' when use docker run command in order to connect to host's docker engine.

So my question is, is there a way to also run the container in privileged mode when configure Cron job? Cause if I don't do so, there's a docker: error during connect: Post "http://docker:2375/v1.24/containers/create": dial tcp: lookup docker on 10.254.133.10:53: no such host error happens which I guess may related to not using privilege mode.

Thank you in advance!

1

There are 1 best solutions below

0
Walid Ghallab On

This error seems to happen as it is being ran in a different network namespace from the host.

Easiest way to make it run is to use privileged: true to make the container run in privileged mode and hostNetwork: true to share the same network with the host machine.

An example yaml would look like this (this yaml is for example pod but you can easily use it as template for cronjob, I provided yaml for pod instead of cronjob as I recommend you trying it with pod first as it is easier and faster to try):

apiVersion: v1
kind: Pod
metadata:
  name: dind
spec:
  hostNetwork: true
  containers:
  - name: dind
    image: docker:dind
    securityContext:
      privileged: true

Note that after that you might need to login into docker (this is probably out of scope of this question but let me provide some guidance):

  • Easy one-time way is to run kubectl exec -it dind -- sh to ssh and then run docker login. Though this change will only live through the lifetime of the container inside the pod (e.g. it will be lost if the container is restarted). You can use this way just for trying, for more persistent way check the next point.
  • More persistent way is to run docker run as part of the yaml file. There are many ways of doing this. One such way is to add command: ["docker", "login", "--username", "$USERNAME", "--password", "$PASSWORD"] to the yaml file and pass the env variables using secrets.