prompt
stringlengths
65
38.7k
response
stringlengths
41
29.1k
<p>I have installed <a href="https://www.katacoda.com/courses/kubernetes/helm-package-manager" rel="noreferrer"><code>redis</code></a>. The default given name to me is <code>plinking-narwhal</code>. Now I would like to install a service with my assigned name. But first I want to remove the existing one. I had tried deleting them without success.</p> <pre class="lang-sh prettyprint-override"><code>$ kubectl get all NAME READY STATUS RESTARTS AGE pod/plinking-narwhal-redis-master-0 1/1 Running 0 12m pod/plinking-narwhal-redis-slave-9b645b597-2vh82 1/1 Running 7 12m NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/kubernetes ClusterIP 10.96.0.1 &lt;none&gt; 443/TCP 15m service/plinking-narwhal-redis-master ClusterIP 10.109.186.189 &lt;none&gt; 6379/TCP 12m service/plinking-narwhal-redis-slave ClusterIP 10.99.122.12 &lt;none&gt; 6379/TCP 12m NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE deployment.apps/plinking-narwhal-redis-slave 1 1 1 1 12m NAME DESIRED CURRENT READY AGE replicaset.apps/plinking-narwhal-redis-slave-9b645b597 1 1 1 12m NAME DESIRED CURRENT AGE statefulset.apps/plinking-narwhal-redis-master 1 1 12m master $ helm delete stable/redis Error: invalid release name, must match regex ^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])+$ and the length must not longer than 53 master $ helm delete --name plinking-narwhal stable/redis Error: unknown flag: --name </code></pre>
<p>You probably need:</p> <pre><code>$ helm delete redis </code></pre> <p>or if you completely want to remove the release:</p> <pre><code>$ helm delete redis --purge </code></pre> <p><code>stable/redis</code> is not allowed as an expression because of the slash(<code>/</code>)</p> <p>If you'd like to see the name of the releases you can simply run:</p> <pre><code>$ helm list -aq </code></pre>
<p>When I run a docker image using <strong>KubernetesPodOperator</strong> in Airflow version 1.10</p> <p>Once the pod finishes the task successfullly, airflow tries to get the xcom value by making a connection to the pod via k8s stream client.</p> <p>Following is the error which I encountered:</p> <pre><code>[2018-12-18 05:29:02,209] {{models.py:1760}} ERROR - (0) Reason: Handshake status 403 Forbidden Traceback (most recent call last): File &quot;/usr/local/lib/python3.6/site-packages/kubernetes/stream/ws_client.py&quot;, line 249, in websocket_call client = WSClient(configuration, get_websocket_url(url), headers) File &quot;/usr/local/lib/python3.6/site-packages/kubernetes/stream/ws_client.py&quot;, line 72, in __init__ self.sock.connect(url, header=header) File &quot;/usr/local/lib/python3.6/site-packages/websocket/_core.py&quot;, line 223, in connect self.handshake_response = handshake(self.sock, *addrs, **options) File &quot;/usr/local/lib/python3.6/site-packages/websocket/_handshake.py&quot;, line 79, in handshake status, resp = _get_resp_headers(sock) File &quot;/usr/local/lib/python3.6/site-packages/websocket/_handshake.py&quot;, line 152, in _get_resp_headers raise WebSocketBadStatusException(&quot;Handshake status %d %s&quot;, status, status_message) websocket._exceptions.WebSocketBadStatusException: Handshake status 403 Forbidden </code></pre> <blockquote> <p>I'm using K8s service account for this</p> </blockquote> <p>DAG configs</p> <blockquote> <p>xcom=true,</p> <p>get_logs=True,</p> <p>in_cluster=true</p> </blockquote>
<p>So we also hit this problem, we had to modify our rbac rules, in particular we had to add the resource "pods/exec" with the verbs "create" and "get"</p> <pre><code>--- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: airflow-runner rules: - apiGroups: [""] resources: ["deployments", "pods", "pods/log", "pods/exec", "persistentvolumeclaims"] verbs: ["*"] - apiGroups: [""] resources: ["secrets"] resourceNames: ["singleuser-image-credentials"] verbs: ["read","list","watch","create","get"] </code></pre>
<p>I have below StatefulSet postgres for EKS. When I run it I am getting below error.</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning FailedCreate 7s (x17 over 1m) statefulset-controller create Pod postgres-0 in StatefulSet postgres failed error: Pod "postgres-0" is invalid: spec.containers[0].volumeMounts[0].name: Not found: "postgredb" </code></pre> <p>StatefulSet:</p> <pre><code> apiVersion: apps/v1 kind: StatefulSet metadata: name: postgres spec: selector: matchLabels: app: postgres # has to match .spec.template.metadata.labels serviceName: "postgres" replicas: 1 template: metadata: labels: app: postgres spec: terminationGracePeriodSeconds: 10 containers: - name: postgres image: postgres:10.4 imagePullPolicy: "IfNotPresent" ports: - containerPort: 5432 volumeMounts: - name: postgredb mountPath: /var/lib/postgresql/data volumeClaimTemplates: - metadata: name: postgresdb annotations: volume.beta.kubernetes.io/storage-class: "aws-efs" spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi </code></pre> <p>I have StorageClass configured as well. What am I doing wrong here?</p>
<p>Just a typo. </p> <pre><code>volumeMounts: - name: postgredb </code></pre> <p>It should be <code>name:postgresdb</code>, not <code>name:postgredb</code>.</p>
<p>I have Kubernetes cluster runnning and created the ELK stack on different machine. Now I want to ship the logs from Kubernetes cluster to ELK how can I achieve it? The ELK stack is outside the cluster. </p>
<p>Have you tried <a href="https://docs.fluentd.org/v0.12/articles/kubernetes-fluentd" rel="nofollow noreferrer">fluentd</a>? Logging agent that collects logs and able to ship logs to Elastic search.</p> <p><strong>UPDATE</strong></p> <p>I just found some examples in <code>kops</code> repo. You can check <a href="https://github.com/kubernetes/kops/tree/master/addons/logging-elasticsearch" rel="nofollow noreferrer">here</a></p>
<h2>I have a question around K8S Service Type "LoadBalancer".</h2> <p>I am working on developing a new "Kubernetes As a Service" Platform (like GKE etc.) for multi cloud.</p> <p>Question is: K8S Service Type "LoadBalancer" works with Cloud Load Balancers (which are external to Kubernetes). GKE &amp; other cloud based solution provides direct integration with them, so If I create a GKE Cluster &amp; implement a Service Type "LoadBalancer", it will transparently create a new GCP Load Balancer &amp; show Load Balancer IP in Kubernetes (as External IP). Same applies to other Cloud Providers also.</p> <p>I want to allow a similar feature on my new "Kubernetes As a Service" platform, where users can choose a cloud provider, create a Kubernetes Cluster &amp; then apply a K8S Service Type "LoadBalancer" &amp; this will result creating a Load Balancer on the (user selected) cloud platform.</p> <p>I am able to automate the flow till Kubernetes Cluster Creation, but clueless when it comes to "K8S Service &amp; External Load Balancer" Integration.</p> <p>Can anyone please help me how can I approach integrating K8S Service Type "LoadBalancer" with Specific Cloud Load Balancers? Do I need to write a new CRD or is there any similar code available in Git (in case anyone know any link for reference) ?</p>
<p>You have to understand how kubernetes is interacting with cloud provider. Like for example previously I deployed the Kubernetes on AWS with <code>kops</code>. I see that kubernetes uses aws access key &amp; access secret to interact with aws. If I remember correctly, I saw some CLI options in <code>kube-proxy</code> or <code>kubelet</code> to support AWS. (I have searched man pages for all kubernetes binaries for aws options, but I couldn't find any to provide to you).</p> <p>For example look at the <a href="https://manpages.debian.org/experimental/kubernetes-node/kubelet.1.en.html" rel="nofollow noreferrer">kubelet man page</a>, they provided an option called <code>--google-json-key</code> to authenticate GCP. You will get some idea if you deploy kubernetes on AWS with <code>kops</code> or <code>kube-aws</code> and dig through the setup and its configuration/options etc.(Same applies to other cloud providers) </p>
<p>I have to deploy my application software which is a linux based package (.bin) file on a VM instance. As per system requirements, it needs minimum 8vCPUs and 32GB RAM.</p> <p>Now, i was wondering if it is possible to deploy this software over multiple containers that load share the CPU and RAM power in the kubernetes cluster, rather than installing the software on a single VM instance.</p> <p>is it possible?</p>
<p>Yes, it's possible to achieve that.</p> <p>You can start using docker compose to build your customs docker images and then build your applications quickly.</p> <p>First, I'll show you my GitHub <code>docker-compose</code> <a href="https://github.com/hugolesta/multi-docker" rel="nofollow noreferrer">repo</a>, you can inspect the folders, they are separated by applications or servers, so, one <code>docker-compose.yml</code> build the app, only you must run a command <code>docker-compose up -d</code></p> <p>if you need to create a custom image with docker you should use this docker command <code>docker build -t &lt;user_docker&gt;/&lt;image_name&gt; &lt;path_of_files&gt;</code> </p> <p><code>&lt;user_docker&gt;</code> = your docker user</p> <p><code>&lt;image_name&gt;</code> = the image name that you choose</p> <p><code>&lt;path_of_files&gt;</code> = somelocal path, if you need to build in the same folder you should use . (dot) </p> <p>So, after that, you can upload this image to Dockerhub using the following commands.</p> <p>You must login with your credentials </p> <pre><code>docker login </code></pre> <p>You can check your images using the following command</p> <pre><code>docker images </code></pre> <p>Upload the image to DockerHub registry</p> <pre><code>docker push &lt;user_docker&gt;/&lt;image_name&gt; </code></pre> <p>Once the image was uploaded, you can use it in different projects, make sure to make the image lightweight and usefully </p> <p>Second, I'll show a similar <a href="https://github.com/hugolesta/multi-k8s" rel="nofollow noreferrer">repo</a> but this one has a k8s configuration into the folder called k8s. This configuration was made for Google cloud but I think you can analyze it and learn how you can start in your new project.</p> <p>The <code>Nginx</code> service was replaced by ingress service <code>ingress-service.yml</code> and <code>https certificate</code> was added <code>certificate.yml</code> and <code>issuer.yml</code> files</p> <p>If you need dockerize dbs, make sure the db is lightweight, you need to make a persistent volume using <code>PersistentVolumeClaim</code> (database-persistent-volume-claim.yml file) or if you use larger data onit you must use a dedicated db server or some db service in the cloud.</p> <p>I hope this information will be useful to you.</p>
<p>I have a working production environment on a Ubuntu 18.04 machine with an application running with docker-compose (dedicated 8gb RAM and a Intel i7-4790). As an intermediate step for going cloud, I am migrating it to Kubernetes with Kompose. For the development environment, I am using minikube which is not intended for production.</p> <p>From reading <a href="https://discuss.kubernetes.io/t/out-of-the-clouds-onto-the-ground-how-to-make-kubernetes-production-grade-anywhere/1358" rel="nofollow noreferrer">Out of the Clouds onto the Ground: How to Make Kubernetes Production Grade Anywhere</a> I’ve seen some recommended standards for production-grade, but I can sacrifice some of the distributed advantages of Kubernetes in the beginning because this applications availability is not critical.</p> <p>I would like to give a step ahead of using minikube in production, for further cloud deployment, but I only have this machine to start with. What would you recommend in my case?</p>
<p>If you consider to bootstrap Kubernetes cluster on bare metal platform, then I would take a look at <a href="https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/" rel="nofollow noreferrer">kubeadm</a>. It is most suitable for Kubernetes clusters with multi nodes support and provides a lot of features and customization options. </p> <ul> <li>Infrastructure provisioning - <a href="https://github.com/kubernetes-sigs/cluster-api" rel="nofollow noreferrer">Cluster API</a></li> <li>Third-party network <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/" rel="nofollow noreferrer">CNI</a> plugins support</li> <li>Addons for monitoring, logging, and visualization.</li> <li>Specific cloud provider integrations (Load balancers, Storage classes, etc.)</li> </ul> <p>However, moving Kubernetes to cloud environment can bring a more efficient way for managing Kubernetes cluster. As most of cloud providers natively offer Kubernetes engine (<a href="https://cloud.google.com/kubernetes-engine/" rel="nofollow noreferrer">GKE</a>, <a href="https://www.google.com/aclk?sa=L&amp;ai=DChcSEwjIrean2O_gAhUP2bIKHdAKB0sYABAAGgJscg&amp;sig=AOD64_2b-rE2OHlvduVomGwt6MWOnyCJtQ&amp;q=&amp;ved=2ahUKEwjZ7eGn2O_gAhU0xMQBHT6lAPYQ0Qx6BAgGEAE&amp;adurl=" rel="nofollow noreferrer">EKS</a>, <a href="https://azure.microsoft.com/en-us/services/kubernetes-service/" rel="nofollow noreferrer">AKS</a>, etc.). </p>
<p>Currently I enter the pod as a mysql user using the command:</p> <p><code>kubectl exec -it PODNAME -n NAMESPACE bash</code></p> <p>I want to enter a container as root. I've tried the following command:</p> <p><code>kubectl exec -it PODNAME -n NAMESPACE -u root ID /bin/bash</code></p> <p><code>kubectl exec -it PODNAME -n NAMESPACE -u root ID bash</code></p> <p>There must be a way. :-)</p>
<p>I found the answer. </p> <p>You cannot log into the pod directly as root via kubectl. </p> <p>You can do via the following steps.</p> <p>1) find out what node it is running on <code>kubectl get po -n [NAMESPACE] -o wide</code></p> <p>2) ssh node </p> <p>3) find the docker container <code>sudo docker ps | grep [namespace]</code></p> <p>4) log into container as root <code>sudo docker exec -it -u root [DOCKER ID] /bin/bash</code></p>
<p>I'm trying to run <code>elasticsearch</code> container in my openshift project. </p> <p>I got errors:</p> <blockquote> <p>Privileged containers are not allowed capabilities.add: Invalid value: "IPC_LOCK": capability may not be added capabilities.add: Invalid value: "SYS_RESOURCE": capability may not be added</p> </blockquote> <p>I've found out that you need to add <code>privileged scc</code> to user account (or create own dedicated one). </p> <p>I've tried to follow docu <a href="https://docs.openshift.com/container-platform/3.4/admin_guide/manage_scc.html" rel="nofollow noreferrer">https://docs.openshift.com/container-platform/3.4/admin_guide/manage_scc.html</a> where the following commands are given:</p> <pre><code>oc create serviceaccount mysvcacct -n myproject oc adm policy add-scc-to-user privileged system:serviceaccount:myproject:mysvcacct </code></pre> <p>However, no single clue is given what is <code>mysvcacct</code> and why it is called <code>mysvcacct</code>.</p> <p>Because my project is called <code>logging</code>, I've tried the following: </p> <pre><code>oc create serviceaccount logging -n logging oc adm policy add-scc-to-user privileged system:serviceaccount:logging:logging </code></pre> <p>but it didn't change anything. I keep getting the same error. </p> <p>What I'm missing there? What name should I use instead of <code>mysvcacct</code>?</p>
<p>FYI, I introduce the example of <code>yaml</code> format.</p> <ul> <li>You can modify the <code>ServiceAccount</code> name using <code>oc patch dc/your-deploymentConfigName</code> cmd as follows.</li> </ul> <pre><code># oc patch dc/elasticsearch --patch '{"spec":{"template":{"spec":{"serviceAccountName": "logging"}}}}'</code></pre> <ul> <li>Or using <code>oc edit dc/your-deploymentConfigName</code>, take a look around <code>serviceAccountName</code>.</li> </ul> <pre><code># oc edit dc/elasticsearch ... spec: containers: - image: docker-registry.default.svc:5000/test/... imagePullPolicy: Always name: web ports: - containerPort: 8080 protocol: TCP resources: {} terminationMessagePath: /dev/termination-log terminationMessagePolicy: File dnsPolicy: ClusterFirst restartPolicy: Always schedulerName: default-scheduler securityContext: {} serviceAccount: logging serviceAccountName: logging </code></pre>
<p>i need small help. What is the best option for tagging docker images. I am looking to make bash script. Is that recommended or is there any different solution? I would like to add a way to tag my docker images generated by the jenkins build step. I need to auto-increment the BuildNumber, but to manually set the MajorVersion and MinorVersion.</p> <p>I can't find any example related to this. Could you provide me any example to manage my version numbers. </p>
<p>In my experience, it's not a very good practice to tag your images with build numbers as part of your image "version". <a href="https://semver.org/" rel="noreferrer">As stated in SemVer</a>, the third part of the version number is the "Patch", representing a non-breaking fix.</p> <p>The problem with just adding a build number as the patch version is that you aren't necessarily representing a patch with every build. For example, imagine you're working on a fix (which will get released as a patch version). But you don't nail that fix correctly on your first commit/push to your working branch. That first build will already be a build-number increment, as will any other pushes from other devs to other branches. And this will all depend on how your CI is set up.</p> <p>If you <em>need</em> to put the build number, then you can use your CI build number (I think all CI solutions provide that) and add them to your tag as a fourth element in the semver (e.g.: <code>2.4.1-2312</code>, where <code>2312</code> is the build number), and once it gets released you can bump the tag to <code>2.4.2</code>.</p> <p>If you want to be compliant with the docker usual practices, you should also tag <code>2.4.2</code> as <code>2.4</code>, <code>2</code> and <code>latest</code>, if you're to release it.</p> <p>My last advise would be to always tag an image with the full SHA of the commit you're building, as there's no easier way for matching an image to a point in time in your codebase.</p>
<p>I am running <code>Ingress</code> for some services on Kubernetes, and although services are re-directing to those cluster IPs (somewhat correctly), I am not sure how to correctly resolve paths after just those basic paths, for example, if I have Tomcat in path <code>/</code> and Nginx on path <code>/nginx</code>, any Tomcat path after <code>/</code> does not resolve and neither does any Nginx path resolve for even <code>/</code>. I already have <code>nginx.ingress.kubernetes.io/rewrite-target: /</code> set in my <code>ingress.yaml</code>:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: tomcat-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / namespace: kube-system spec: rules: - http: paths: - path: / backend: serviceName: tomcat-deployment-service servicePort: 8080 - path: /nginx backend: serviceName: nginx-deployment-service servicePort: 80 </code></pre> <p>If Tomcat requires a <code>/main.css</code> file, for example, the browser would try to fetch <code>/main.css</code>, but this returns the <code>default-backend</code>.</p> <p>Also, if I try to visit <code>/nginx</code> (attempting to hit <code>/</code>) on the Nginx server, Nginx says <code>/nginx</code> is not found (obviously).</p> <pre><code>2019/03/02 08:12:04 [error] 8#8: *343 open() &quot;/usr/share/nginx/html/nginx&quot; failed (2: No such file or directory), client: 10.128.0.7, server: localhost, request: &quot;GET /nginx HTTP/1.1&quot;, host: &quot;REDACTED_SERVER_IP&quot; 10.128.0.7 - - [02/Mar/2019:08:12:04 +0000] &quot;GET /nginx HTTP/1.1&quot; 404 153 &quot;-&quot; &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:65.0) Gecko/20100101 Firefox/65.0&quot; &quot;REDACTED_CLIENT_IP, REDACTED_SERVER_IP&quot; 10.40.1.1 - - [02/Mar/2019:08:12:05 +0000] &quot;GET /nginx HTTP/1.1&quot; 404 153 &quot;-&quot; &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:65.0) Gecko/20100101 Firefox/65.0&quot; &quot;REDACTED_CLIENT_IP, REDACTED_SERVER_IP&quot; 2019/03/02 08:12:05 [error] 8#8: *344 open() &quot;/usr/share/nginx/html/nginx&quot; failed (2: No such file or directory), client: 10.40.1.1, server: localhost, request: &quot;GET /nginx HTTP/1.1&quot;, host: &quot;REDACTED_SERVER_IP&quot; </code></pre> <p><strong>How can I make paths after a specified <code>path</code> in <code>ingress.yaml</code> resolve considering the beginning part of the path as viewed from the service?</strong></p> <p>i.e.</p> <ol> <li>If Tomcat was ingress pathed to <code>/tomcat</code>, how could I make <code>/tomcat/main.css</code> appear as <code>/main.css</code> to the Tomcat server (and not resolve to default backed)?</li> <li>If Nginx was ingress pathed to <code>/nginx</code>, how could I make <code>/nginx</code> appear as <code>/</code> to the Nginx server (and not appear as <code>/nginx</code>)?</li> </ol> <p>I thought this was what <code>/rewrite-target</code> was suppose to do.</p> <p><strong>Would I need to use wildcards or something?</strong></p> <p>My ingress is the following:</p> <pre><code>Name: tomcat-ingress Namespace: kube-system Address: REDACTED_SERVER_IP Default backend: default-http-backend:80 (10.40.0.6:8080) Rules: Host Path Backends ---- ---- -------- * / tomcat-deployment-service:8080 (10.40.2.15:8080) /nginx nginx-dep-ser:80 (10.40.0.26:80,10.40.1.46:80) Annotations: ingress.kubernetes.io/url-map: k8s-um-kube-system-tomcat-ingress--b0fc8aa23db1001d kubectl.kubernetes.io/last-applied-configuration: {&quot;apiVersion&quot;:&quot;extensions/v1beta1&quot;,&quot;kind&quot;:&quot;Ingress&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{&quot;nginx.ingress.kubernetes.io/rewrite-target&quot;:&quot;/&quot;},&quot;name&quot;:&quot;tomcat-ingress&quot;,&quot;namespace&quot;:&quot;kube-system&quot;},&quot;spec&quot;:{&quot;rules&quot;:[{&quot;http&quot;:{&quot;paths&quot;:[{&quot;backend&quot;:{&quot;serviceName&quot;:&quot;tomcat-deployment-service&quot;,&quot;servicePort&quot;:8080},&quot;path&quot;:&quot;/&quot;},{&quot;backend&quot;:{&quot;serviceName&quot;:&quot;nginx-dep-ser&quot;,&quot;servicePort&quot;:80},&quot;path&quot;:&quot;/nginx&quot;}]}}]}} nginx.ingress.kubernetes.io/rewrite-target: / ingress.kubernetes.io/backends: {&quot;k8s-be-30985--b0fc8aa23db1001d&quot;:&quot;HEALTHY&quot;,&quot;k8s-be-31229--b0fc8aa23db1001d&quot;:&quot;HEALTHY&quot;,&quot;k8s-be-32736--b0fc8aa23db1001d&quot;:&quot;HEALTHY&quot;} ingress.kubernetes.io/forwarding-rule: k8s-fw-kube-system-tomcat-ingress--b0fc8aa23db1001d ingress.kubernetes.io/target-proxy: k8s-tp-kube-system-tomcat-ingress--b0fc8aa23db1001d Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal CREATE 33m nginx-ingress-controller Ingress kube-system/tomcat-ingress Normal ADD 33m loadbalancer-controller kube-system/tomcat-ingress Normal UPDATE 3m (x65 over 33m) nginx-ingress-controller Ingress kube-system/tomcat-ingress Normal CREATE 3m (x31 over 33m) loadbalancer-controller ip: REDACTED_SERVER_IP </code></pre>
<p>I assume that you have quite recent version of ingress controller, and according to the <a href="https://kubernetes.github.io/ingress-nginx/examples/rewrite/" rel="noreferrer">documentation</a>:</p> <blockquote> <p>Starting in Version 0.22.0, ingress definitions using the annotation <code>nginx.ingress.kubernetes.io/rewrite-target</code> are not backwards compatible with previous versions. In Version 0.22.0 and beyond, any substrings within the request URI that need to be passed to the rewritten path must explicitly be defined in a <strong>capture group</strong>.</p> </blockquote> <p>E.g:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/rewrite-target: /$1 name: tomcat-ingress namespace: default spec: rules: - host: rewrite.bar.com http: paths: - backend: serviceName: tomcat-deployment-service servicePort: 8080 path: /tomcat/?(.*) - backend: serviceName: nginx-deployment-service servicePort: 80 path: /nginx/?(.*) </code></pre> <p>Your current configuration works well for <code>/</code> and <code>/nginx</code> destinations only with the recent version of ingress controller.</p> <p>Another important thing, the Ingress object should be created in the same namespace with the service(s) it refers to. Otherwise ingress-nginx usually returns <code>503 Service Temporarily Unavailable</code> error. </p> <p>And it's not allowed to refer to a service in the different namespace in the <code>serviceName</code>:</p> <blockquote> <p>a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character (e.g. 'my-name', or 'abc-123', regex used for validation is 'a-z?')</p> </blockquote>
<p>Anyone tried to make an arithmetic division in <a href="https://helm.sh/" rel="noreferrer">Helm</a>? </p> <p>According to <a href="http://masterminds.github.io/sprig/math.html" rel="noreferrer">sprig/Math Functions</a>, the following should work:</p> <pre><code>{{ .Values.myvalue | div 2 }} </code></pre> <p>However, the result is wrong. e.g. <code>6/2 = 0</code>, <code>4/2 = 0</code>, <code>1/2 = 2</code>.</p> <p>Any hint ?</p>
<p>You use the function the wrong way: See function <a href="https://github.com/Masterminds/sprig/blob/bf29da0d74f74aeb5c3e3e7207eab76c28ac4049/functions.go#L182" rel="noreferrer">declaration</a>.</p> <p>Your template should be:</p> <pre><code>{{ div .Values.myvalue 2 }} </code></pre>
<p>Worker nodes upgraded to latest k8s version and I am facing the 'NotReady' status of those worker nodes. I see 'PIDPressure - False' when I do a 'kubectl describe' for these nodes.</p>
<blockquote> <p>PIDPressure - False</p> </blockquote> <p>^^ is an expected condition of the healthy node, it means that kubelet has sufficient PIDs available for normal operation. </p> <p>Need more details:</p> <ul> <li>Kubelet version? <code>kubectl version</code></li> <li>Can you share a full output of the describe command? <code>kubectl describe node &lt;node-name&gt;</code></li> <li>ssh to the node and run <code>sudo journalctl -u kubelet --all|tail</code></li> </ul>
<p>I am practicing k8s from <a href="https://www.katacoda.com/courses/kubernetes/create-kubernetes-ingress-routes" rel="nofollow noreferrer">katacoda</a>. Currently I am working on <code>ingress.yaml</code>. This is chapter has extra kind of services come to the <code>yaml</code> file. They are <code>Namespace, Secret, ServiceAccount, and ConfigMap</code>. For <code>Secret</code> I can read on other chapter to understand it later.</p> <p><strong>Questions:</strong><br></p> <ol> <li><p>Do I need to use <code>Namespace, ServiceAccount, and ConfigMap</code> in my <code>ingress.yaml</code>?</p></li> <li><p>Suppose I <code>Caddy</code> to make <code>https</code>. <code>Secret</code> from the example is a hardcode. How can I achieve automatically renew after certain period?</p></li> </ol>
<blockquote> <p>Do I need to use Namespace, ServiceAccount, and ConfigMap in my ingress.yaml?</p> </blockquote> <p>No, it's not required. They are different Kubernetes resources and can be created independently. But you can place several resource definition in one YAML file just for convenience. </p> <p>Alternatively you can create separate YAML file for each resource and place them all in the same directory. After that one of the following commands can be used to create resources <a href="https://kubernetes.io/docs/concepts/cluster-administration/manage-deployment/#bulk-operations-in-kubectl" rel="nofollow noreferrer">in bulk</a>:</p> <pre><code>kubectl create -f project/k8s/development kubectl create -f project/k8s/development --recursive </code></pre> <p><a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/" rel="nofollow noreferrer"><strong>Namespace</strong></a> is just a placeholder for Kubernetes resources. It should be created before any other resources use it.</p> <p><a href="https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/" rel="nofollow noreferrer"><strong>ServiceAccount</strong></a> is used as a security context to restrict permission for specific automation operations.</p> <p><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/" rel="nofollow noreferrer"><strong>ConfigMap</strong></a> is used as a node independent source of configuration/file/environment for pods.</p> <hr> <blockquote> <p>Suppose I Caddy to make https. Secret from the example is a hardcode. How can I achieve automatically renew after certain period?</p> </blockquote> <p>Not quite clear question, but I believe you can use cert-manager for that. </p> <p><a href="https://docs.cert-manager.io/en/latest/" rel="nofollow noreferrer"><strong>cert-manager</strong></a> is quite popular solution to manage certificates for Kubernetes cluster.</p>
<p>There's a bit of a vagueness in the Kubernetes documentation about what happens if a pod's memory footprint increases to a point where it exceeds the value specified under <code>resources.limits</code>.</p> <p><a href="https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#how-pods-with-resource-limits-are-run" rel="noreferrer">https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#how-pods-with-resource-limits-are-run</a></p> <p>It specifies that if a pod's footprint grows to exceed its <code>limits</code> value, it "might be" terminated. What does the "might be" mean? What conditions would result in it being terminated vs which ones would allow it to continue on as-is?</p>
<blockquote> <p>Q: What happens if a Kubernetes pod exceeds its memory resources 'limit'?</p> </blockquote> <p>It will be restarted.</p> <blockquote> <p>Unlike Pod eviction, if a Pod container is OOM killed, it may be restarted by the <code>kubelet</code> based on its <code>RestartPolicy</code>.</p> </blockquote> <p>You can <a href="https://kubernetes.io/docs/tasks/administer-cluster/out-of-resource/" rel="noreferrer">Configure Out Of Resource Handling</a> for your <code>Node</code>.</p> <blockquote> <h3>Evicting end-user Pods<a href="https://kubernetes.io/docs/tasks/administer-cluster/out-of-resource/#evicting-end-user-pods" rel="noreferrer"></a></h3> <p>If the <code>kubelet</code> is unable to reclaim sufficient resource on the node, <code>kubelet</code> begins evicting Pods.</p> <p>The <code>kubelet</code> ranks Pods for eviction first by whether or not their usage of the starved resource exceeds requests, then by <a href="https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/" rel="noreferrer">Priority</a>, and then by the consumption of the starved compute resource relative to the Pods’ scheduling requests.</p> </blockquote>
<p>I am putting docker image into POD. We can exec into a Docker container using "docker exec..." Similarly is there a way to exec into container in a POD to check some data ?</p>
<p>There are several ways of how to get inside the Kubernetes container in a Pod. </p> <ul> <li><a href="https://kubernetes.io/docs/tasks/debug-application-cluster/get-shell-running-container/" rel="nofollow noreferrer">kubectl exec</a> (<a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#exec" rel="nofollow noreferrer">reference link</a>) creates additional process in the Pod's namespace and connects your console to it's stdin/stdout.</li> </ul> <p>Examples:</p> <pre><code>kubectl exec 123456-7890 date kubectl exec 123456-7890 -c ruby-container date kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il kubectl exec 123456-7890 -i -t -- ls -t /usr </code></pre> <ul> <li><a href="https://kubernetes.io/docs/reference/kubectl/docker-cli-to-kubectl/" rel="nofollow noreferrer">kubectl attach</a> (<a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#attach" rel="nofollow noreferrer">reference link</a>) connects your console to stdin/stdout existing container process.</li> </ul> <p>Example:</p> <pre><code>kubectl attach 123456-7890 kubectl attach 123456-7890 -c ruby-container kubectl attach 123456-7890 -c ruby-container -i -t kubectl attach rs/nginx </code></pre> <p>You can also connect to stdout/stderr of pod container(s) using <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs" rel="nofollow noreferrer">kubectl logs</a> command.</p> <p>Examples:</p> <pre><code>kubectl logs nginx kubectl logs nginx --all-containers=true kubectl logs -lapp=nginx --all-containers=true kubectl logs -p -c ruby web-1 kubectl logs -f -c ruby web-1 </code></pre> <p>These answers on StackOverflow give you more information related to your question:</p> <ul> <li><a href="https://stackoverflow.com/questions/39979880/kubectl-exec-into-contain-of-multi-container-pod">kubectl exec into contain of multi container pod</a></li> <li><a href="https://stackoverflow.com/questions/51247619/execute-bash-command-in-pod-with-kubectl/51247696">Execute bash command in pod with kubectl?</a></li> <li><a href="https://stackoverflow.com/questions/50030252/kubectl-attach-vs-kubectl-exec">Kubectl attach vs kubectl exec?</a></li> <li><a href="https://stackoverflow.com/questions/54874683/how-do-you-debug-python-code-with-kubernetes-and-skaffold">How do you debug python code with kubernetes and skaffold?</a></li> </ul>
<p>I was using NodePort to host a webapp on Google Container Engine (GKE). It allows you to directly point your domains to the node IP address, instead of an expensive Google load balancer. Unfortunately, instances are created with HTTP ports blocked by default, and an update locked down manually changing the nodes, as they are now created using and Instance Group/and an Immutable Instance Template.</p> <p><strong>I need to open port 443 on my nodes, how do I do that with Kubernetes or GCE? Preferably in an update resistant way.</strong></p> <p><a href="https://i.stack.imgur.com/cBa5b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cBa5b.png" alt="enter image description here"></a></p> <p>Related github question: <a href="https://github.com/nginxinc/kubernetes-ingress/issues/502" rel="nofollow noreferrer">https://github.com/nginxinc/kubernetes-ingress/issues/502</a></p>
<p>Update: A deamonset with a nodeport can handle the port opening for you. nginx/k8s-ingress has a nodeport on 443 which gets exposed by a custom firewall rule. the GCE UI will not show「Allow HTTPS traffic」as checked, because its not using the default rule.</p> <hr /> <p>You can do everything you do on the GUI Google Cloud Console using the Cloud SDK, most easily through the Google Cloud Shell. Here is the command for adding a network tag to a running instance. This works, even though the GUI disabled the ability to do so</p> <pre><code>gcloud compute instances add-tags gke-clusty-pool-0-7696af58-52nf --zone=us-central1-b --tags https-server,http-server </code></pre> <p>This also works on the beta, meaning it should continue to work for a bit. See <a href="https://cloud.google.com/sdk/docs/scripting-gcloud" rel="nofollow noreferrer">https://cloud.google.com/sdk/docs/scripting-gcloud</a> for examples on how to automate this. Perhaps consider running on a webhook when downtime is detected. Obviously none of this is ideal.</p> <p>Alternatively, you can change the templates themselves. With this method you can also add a startup to new nodes, which allows you do do things like fire a webhook with the new IP Address for a round robin low downtime dynamic dns.</p> <p>Source (he had the opposite problem, his problem is our solution): <a href="https://stackoverflow.com/a/51866195/370238">https://stackoverflow.com/a/51866195/370238</a></p>
<p>I've been reading the kubernetes documentation <a href="https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#resource-requests-and-limits-of-pod-and-container" rel="noreferrer">https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#resource-requests-and-limits-of-pod-and-container</a> </p> <p>But it's still not clear for me what's the difference between <code>spec.containers[].resources.limits.cpu</code> and <code>spec.containers[].resources.requests.cpu</code> and what's the impact on the resource limitation</p> <p>Can you please suggest some reads or books where this is explained in common english? </p> <p>Thanks in advance</p>
<p>When Kubernetes pod is scheduled on a particular node it is required the pod to have enough resources to run. Kubernetes knows resources of it's node but how does kubernetes knows the how much resources will pod takes beforehand to schedule it effectively in nodes. For that <code>requests</code> will be used. When we specify a <code>request</code> of resource kubernetes will guarantee that pod will get that amount of resource. </p> <p>On other hand <code>limit</code> limits the resource usage by a pod. Kubernetes will not allow a pod to take more resources than the <code>limit</code>. When it comes to CPU if you request more kubernetes will throttle pods CPU artificially. If pod exceed a <code>limit</code> pod will be it will be terminated. To make it simple it simple <code>limit</code> is always bigger than <code>request</code>.</p> <p>This example will give you idea about <code>request</code> and <code>limit</code>. Think that there is a pod where you have specify its memory request as 7GB and memory limit as 10GB. There are three nodes in your cluster where node1 has 2GB of memory, node2 has 8GB memory and node3 has 16GB. Your pod will never be scheduled on node1. But it will either be sceduled on node2 or node3 depending on pod current memory usage. But if it is scheduled on node3 it will be terminated in any scenario it will exceed the memory usage of 10GB.</p>
<p>I have a local minikube installation. I want to change the authentication mechanism for the api-server and restart and test it out. All the documentation I have read lacks this information.</p>
<p>Yes you can. The kubernetes API Server, Controller manager, and scheduler are all run as static manifests in minikube.</p> <p>So, in fact, in your example: Any change to the manifest will <em>automatically</em> lead to them being restarted instantly.</p> <p>In order to make the modification, just use <code>vi</code> inside of /etc/kubernetes/manifests on whatever file you want to edit, and you'll see that the apiserver instantly restarts.</p> <p>To look at the logs of the restart, you can look in /var/log/containers/ where each of the individual minikube services run.</p>
<blockquote> <p>OS: RHEL7 | k8s version: 1.12/13 | kubespray | baremetal</p> </blockquote> <p>I have a standard kubespray bare metal cluster deployed and I am trying to understand what is the simplest recommended way to deploy nginx-ingress-controller that will allow me to deploy simple services. There is no load balancer provided. I want my MASTER public IP as the endpoint for my services.</p> <p><a href="https://i.stack.imgur.com/GKWjG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GKWjG.png" alt="look-up"></a></p> <p>Github k8s ingress-nginx <a href="https://github.com/kubernetes/ingress-nginx/blob/master/docs/deploy/index.md#bare-metal" rel="nofollow noreferrer">suggests</a> NodePort service as a "mandatory" step, which seems not to be enough to make it works along with kubespray's <em>ingress_controller</em>.</p> <p>I was able to make it working forcing LoadBalancer service type and setting externalIP value as a MASTER public IP into nginx-ingress-controller via <code>kubectl edit svc</code> but it seems not to be a correct solution due to lack of a load balancer itself.</p> <p>Similar results using helm chart:</p> <pre><code>helm install -n ingress-nginx stable/nginx-ingress --set controller.service.externalIPs[0]="MASTER PUBLIC IP" </code></pre>
<blockquote> <p>I was able to make it working forcing LoadBalancer service type and setting externalIP value as a MASTER public IP into nginx-ingress-controller via kubectl edit svc but it seems not to be a correct solution due to lack of a load balancer itself.</p> </blockquote> <p>Correct, that is not what <a href="https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer" rel="nofollow noreferrer">LoadBalancer</a> is intended for. It's intended for provisioning load balancers with cloud providers like AWS, GCP, or Azure, or a load balancer that has some sort of API so that the kube-controller-manager can interface with it. If you look at your kube-controller-manager logs you should see some errors. The way you made it work it's obviously a hack, but I suppose it works.</p> <p>The standard way to implement this is just to use a <a href="https://kubernetes.io/docs/concepts/services-networking/service/#nodeport" rel="nofollow noreferrer">NodePort</a> service and have whatever proxy/load balancer (i.e. nginx, or haproxy) on your master to send traffic to the NodePorts. Note that I don't recommend the master to front your services either since it already handles some of the critical Kubernetes pods like the kube-controller-manager, kube-apiserver, kube-scheduler, etc.</p> <p>The only exception is <a href="https://metallb.universe.tf" rel="nofollow noreferrer">MetalLB</a> which you can use with a LoadBalancer service type. Keep in mind that as of this writing the project is in its early stages.</p>
<p>I have deployed the rabbitmq-ha chart to kubernetes, then used kubectl port-forwarding to access the management ui. I can log in, but I dont see any data in the ui, some tabs are showing the error:</p> <pre><code>TypeError: Cannot read property 'name' of undefined TypeError: Cannot read property 'name' of undefined at Array.process (eval at compile (http://localhost:15672/js/ejs-1.0.min.js:1:6654), :100:139) at EJS.render (http://localhost:15672/js/ejs-1.0.min.js:1:1885) at format (http://localhost:15672/js/main.js:1086:21) at http://localhost:15672/js/main.js:444:24 at with_reqs (http://localhost:15672/js/main.js:1068:9) at http://localhost:15672/js/main.js:1064:17 at XMLHttpRequest.req.onreadystatechange (http://localhost:15672/js/main.js:1144:17) </code></pre> <p><a href="https://github.com/helm/charts/tree/master/stable/rabbitmq-ha" rel="nofollow noreferrer">https://github.com/helm/charts/tree/master/stable/rabbitmq-ha</a></p> <p>I have deployed in the following way. I have a chart with a single requirement, rabbitmq.</p> <p>I run the commands</p> <pre><code>$ helm dependency build ./rabbitmq $ helm template --namespace rabbitmq-test --name rabbitmq-test . --output-dir ./output $ kubectl apply -n rabbitmq-test -Rf ./output </code></pre> <p>/rabbitmq/Chart.yaml</p> <pre><code>apiVersion: v1 appVersion: "1.0" description: A Helm chart for Kubernetes name: rabbitmq-ha version: 0.1.0 </code></pre> <p>/rabbitmq/requirements.yaml</p> <pre><code>dependencies: - name: rabbitmq-ha version: 1.19.0 repository: https://kubernetes-charts.storage.googleapis.com </code></pre> <p>/rabbitmq/values.yaml (default settings from github, indented under <code>rabbitmq-ha</code></p> <pre><code>rabbitmq-ha: ## RabbitMQ application credentials ## Ref: http://rabbitmq.com/access-control.html ## rabbitmqUsername: guest # rabbitmqPassword: ... </code></pre> <p>Everything appears to deploy correctly, I see no errors, I can enter the pod and use <code>rabbitmqctl</code>, the node_health_check command is successful, I can create queues etc.</p> <p>To access management ui I run the command</p> <pre><code>kubectl port-forward -n rabbitmq-test rabbitmq-test-rabbitmq-ha-0 15672:15672 </code></pre> <p>Then visit localhost:15672 and log in.</p> <p><a href="https://i.stack.imgur.com/otEOI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/otEOI.png" alt="enter image description here"></a></p>
<p>Which username are you logging in with? The helm values define application and management credentials. I had the same errors when logging in using the management user, that user only has permission for health checks etc. You need to login with the guest user</p> <blockquote> <h2>charts/values.yaml</h2> <pre><code>## RabbitMQ application credentials ## Ref: http://rabbitmq.com/access-control.html ## rabbitmqUsername: guest # rabbitmqPassword: ## RabbitMQ Management user used for health checks managementUsername: management managementPassword: E9R3fjZm4ejFkVFE </code></pre> </blockquote>
<p>lets take this example of a config map</p> <pre><code>apiVersion: v1 kind: ConfigMap data: abc.yml: |- &lt;yml here&gt; </code></pre> <p>Getting an error like failed to parse yaml to Json.</p>
<p>Yes you can do that, but you should care about the syntax. You can also follow techniques for yaml from <a href="https://github.com/helm/helm/blob/master/docs/chart_template_guide/yaml_techniques.md#strings-in-yaml" rel="nofollow noreferrer">here</a>.</p> <p>If you use <code>kubectl create configmap myconfig --from-file=abc.yml</code>, then it is ok.</p> <p>But if you write the whole yaml file for your configmap in myconfig.yaml and then run <code>kubectl create -f myconfig.yaml</code>, then you should care about syntax.</p> <p>Say your <code>abc.yml</code> file is as followings:</p> <pre><code>a: b: b1 c: c1 d: d1 </code></pre> <p>Then write your <code>myconfig.yaml</code> file:</p> <pre><code>apiVersion: v1 kind: ConfigMap data: abc.yml: | a: b: b1 c: c1 d: d1 </code></pre> <p>Now just run <code>kubectl create -f myconfig.yaml</code>. That's it.</p> <p>Happy Kubernetes!!!.</p>
<p>Hi I am playing around with Kubernetes secrets. My deployment file is :</p> <pre><code>--- apiVersion: v1 kind: Secret metadata: name: my-secrets labels: app: my-app data: username: dXNlcm5hbWU= password: cGFzc3dvcmQ= </code></pre> <p>I am able to create secrets and I am mounting them in my deployments as below:</p> <pre><code>--- apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app: my-service ports: - protocol: TCP port: 80 targetPort: 8080 type: NodePort --- apiVersion: apps/v1 kind: Deployment metadata: name: spring-service labels: app: spring-service spec: replicas: 1 selector: matchLabels: app: spring-service template: metadata: labels: app: spring-service spec: containers: - name: spring-service image: my-image:tag imagePullPolicy: Always ports: - containerPort: 8080 volumeMounts: - name: my-secret-vol mountPath: "/app/secrets/my-secret" readOnly: true volumes: - name: my-secret-vol secret: secretName: my-secrets </code></pre> <p>My question is how can I access <code>username</code> and <code>password</code> I created in secret in spring-boot app?</p> <p>I have tried loading in with <code>${my-secrets.username}</code> and <code>${username}</code>, but it fails to find values.</p> <p>I also tried adding secrets as enviroment variables as below in deployment.yml:</p> <pre><code>env: - name: username valueFrom: secretKeyRef: name: my-secrets key: username - name: password valueFrom: secretKeyRef: name: my-secrets key: password </code></pre> <p>In this case, values are loaded from secrets and when I change values of secrets in minikube dashboard, it does not reflect the changes.</p> <p>Please help me to understand how this works.</p> <p>I am using <code>minikube</code> and <code>docker</code> as containers</p>
<p>For the first approach you'll find the values on: </p> <pre><code>- /app/secrets/my-secret/username - /app/secrets/my-secret/password </code></pre> <p>and for the second approach you can't change the value of env vars during runtime, you need to restart or redeploy the pod</p>
<p>I use external docker registry in my GKE cluster to pull containers. This docker registry has security access list (which is basically list of client's public IP addresses). However, GKE cluster creates nodes with ephemeral IP addresses and makes it inconvenient to add each new IP address into access list.</p> <p><strong>How can I create proxy or port forwarding in google cloud to forward all requests via one external IP to access my external registry ?</strong></p> <p><img src="https://i.imgur.com/U3lLOV9.png" alt="graph"></p>
<p>You should use <a href="https://cloud.google.com/nat/docs/overview" rel="nofollow noreferrer">Cloud NAT</a>. It will act at the proxy in your diagram and you can use the addresses of the NAT in the ACLs of the container registry. Also check out <a href="https://medium.com/google-cloud/using-cloud-nat-with-gke-cluster-c82364546d9e" rel="nofollow noreferrer">this tutorial</a> on setting up Cloud NAT with GKE. </p>
<p>I have Elasticsearch Pod, and a Service. I also have another Pod (same namespace - default) called "website", that want to get the html content of the Elasticsearch (using curl). </p> <p>When I access the "website" Pod (using exec), and run <code>$curl -v elasticsearch-service</code>,I get:</p> <pre><code>curl -v elasticsearch-service * Rebuilt URL to: elasticsearch-service/ * Trying 10.111.159.30... * TCP_NODELAY set </code></pre> <p>note: 10.111.159.30 is the elasticsearch-service IP.</p> <p>But when I run <code>$curl 172.15.0.5:9200</code> (POD IP), I get the correct output:</p> <pre><code> $curl 172.15.0.5:9200 { "name" : "1X7ZARS", "cluster_name" : "docker-cluster", "cluster_uuid" : "V8GX-5STSoW_PJ8Qguu7Jw", "version" : { "number" : "6.6.1", "build_flavor" : "default", "build_type" : "tar", "build_hash" : "1fd8f69", "build_date" : "2019-02-13T17:10:04.160291Z", "build_snapshot" : false, "lucene_version" : "7.6.0", "minimum_wire_compatibility_version" : "5.6.0", "minimum_index_compatibility_version" : "5.0.0" }, "tagline" : "You Know, for Search" } </code></pre> <p>For some reason, Elasticsearch's service, doesn't redirect to the els app.</p> <p>This is the yaml of the Pod:</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: elasticsearch spec: containers: - name: elasticsearch image: yageldhn/els-java8:6.6.1 ports: - containerPort: 9200 - containerPort: 9300 env: - name: discovery.type value: "single-node" </code></pre> <p>This is the yaml of the service:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: elasticsearch-service spec: ports: - port: 9200 name: serving protocol: TCP - port: 9300 name: node2node protocol: TCP selector: app: elasticsearch </code></pre> <p>I'm pretty new with K8s, what I did wrong?</p>
<p>You need to label your pod with <em>app: elasticsearch</em> because of the selector in you service definition: <code>selector: app: elasticsearch</code></p> <p>Edit: There is a pretty good explanation in the official <a href="https://kubernetes.io/docs/concepts/services-networking/service/#defining-a-service" rel="nofollow noreferrer">docs</a> </p>
<p>I've created a service which wraps an nfs, and I need to get the cluster IP for it so that I can set it to persistent volumne using it.</p> <p>I know I can use the following to get this:</p> <pre><code>$ kubectl get svc nfs-server NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nfs-server ClusterIP 10.59.243.58 &lt;none&gt; 2049/TCP,20048/TCP,111/TCP 2m </code></pre> <p>What I want to know is, how do I extract that cluster IP in a bash script? It's generated as part of a deployment process, so I can't just type it in to my persistent volume manifest.</p>
<p>You can parse the of <code>kubectl get svc</code> command something like below to get the inner details of the deployment.</p> <pre><code>export CLUSTER_IP=$(kubectl get services/nfs-server -o go-template='{{(index.spec.clusterIP)}}');echo CLUSTER_IP=$CLUSTER_IP </code></pre> <p>Alternatively, you can try any combination of shell hacks involving <code>cut and awk</code>. One such example is;</p> <pre><code>kubectl describe svc/nfs-server | grep IP: | awk '{print $2;}' </code></pre>
<p>In the <a href="https://kubernetes.io/docs/concepts/configuration/overview/#container-images" rel="noreferrer">Kubernetes documentation</a> it mentions that the caching semantic of using <code>ImagePullPolicy: Always</code> makes the ImagePullPolicy quite efficient. What reasons would I want to choose a different ImagePullPolicy?</p>
<p>It heavily depends on your versioning/tagging strategy. </p> <p>When new replicas of your application are created (because your app has scaled up, or a pod has died and it's been replaced by a new pod), if you use <code>ImagePullPolicy: Always</code> and you have pushed a different version of your application using the same tag (like people do when using <code>latest</code>), the new created replicas might run a totally different version of the application than the rest of the replicas, leading to an inconsistent behavior.</p> <p>You also may want to use a different value than <code>Always</code> when <a href="https://stackoverflow.com/a/42564211/563072">on a development environment like minikube</a>.</p>
<p><strong>TL;DR</strong>: I want to setup cookie-based session affinity in K8s over the nginx-ingress controller with SSL passthrough - can this be done?</p> <hr> <p>Hey all, </p> <p>I have a working Azure Kubernetes Service (AKS) running (1.11.3) and have configured the <a href="https://github.com/kubernetes/ingress-nginx" rel="nofollow noreferrer">NGINX-Ingress</a> controller to route requests to a ClusterIP Service for my app (which has a minimum of 2 pods running).</p> <p>I have successfully configured SSL passthrough on the ingress controller so that the TLS is terminated at the Pods and so I can use HTTP2 (as per this <a href="https://www.thenativeweb.io/blog/2018-07-03-16-17-kubernetes-using-ingress-with-ssl-tls-termination-and-http2/" rel="nofollow noreferrer">article</a>). Now I'd like to setup Session Affinity (using Cookies) so that connections are routed to the same pod for stateful behaviours (logging into to the app). </p> <p>I have tried using the following annotations on the ingress object for this:</p> <pre><code>nginx.ingress.kubernetes.io/affinity: "cookie" nginx.ingress.kubernetes.io/session-cookie-name: "route" nginx.ingress.kubernetes.io/session-cookie-expires: "172800" nginx.ingress.kubernetes.io/session-cookie-max-age: "172800" nginx.ingress.kubernetes.io/session-cookie-hash: "sha1" </code></pre> <p>However, I'm not seeing the "route" cookie returned on the first request. I've worked through the issue described <a href="https://github.com/kubernetes/ingress-nginx/issues/1980" rel="nofollow noreferrer">here</a> and ensured the ingress is setup correctly. Then I've spotted this message over at the <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#ssl-passthrough" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>Because SSL Passthrough works on layer 4 of the OSI model (TCP) and not on the layer 7 (HTTP), using SSL Passthrough invalidates all the other annotations set on an Ingress object.</p> </blockquote> <p><strong>Q</strong>: Would this mean that using session affinity with SSL passthrough is off the table? In that the Ingress isn't going to be able to identify the connection / cookie (as it's SSL encrypted) and direct it to the previously associated pod?</p>
<p>Short answer: no it's impossible. Layer 4 has no clue on what http is, it just sees bytes flowing back and forth. You could have affinity based on ip address instead, just not with cookies as it would need a layer 7 proxy solution. Depending on your situation, you could run a proxy in layer 7 which would be able to decrypt the traffic and then encrypt it with another certificate for internal use. All of the payload (minus SNI for example) is not encrypted as per SSL, which means that in order to do some kind of affinity on cookies, the proxy will need to decrypt the data before inspecting it.</p>
<p>I am new to kubernetes and I am attempting to create a new cluster in aws with Kops. Unfortunately I can't seem proceed without specifying a dns-zone, which is something that I was never required to do when I used tools like docker-machine and docker swarm for the same purpose. Moreover, I do not need nor want services such as Route53. </p> <p>Therefore my question is how can I create a kubernetes cluster in aws without having to worry about dns zones and route 53? </p> <p>Thanks</p>
<p>From <a href="https://github.com/kubernetes/kops/blob/master/docs/aws.md#configure-dns" rel="noreferrer">Kops documentation</a></p> <blockquote> <p>Note: If you are using Kops 1.6.2 or later, then DNS configuration is optional. Instead, a gossip-based cluster can be easily created. The only requirement to trigger this is to have the cluster name end with .k8s.local. If a gossip-based cluster is created then you can skip this section.</p> </blockquote> <pre><code>aws s3 mb s3://k8s-kops-gossib-bucket-name export KOPS_STATE_STORE=s3://k8s-kops-gossib-bucket-name aws configure kops create secret --name mycluster.k8s.local sshpublickey admin -i ~/.ssh/id_rsa.pub kops create cluster mycluster.k8s.local --zones us-east-2a --yes kops validate cluster </code></pre> <p>Note: If you see such error when you validate <code>unexpected error during validation: error listing nodes: Get https://api-cluster-k8s-local-ohpk1a-466508885.us-east-2.elb.amazonaws.com/api/v1/nodes: dial tcp: lookup api-mycluster-k8s-local-ohpk1a-466508885.us-east-2.elb.amazonaws.com on 169.234.149.254:53: no such host</code> You need to wait for DNS update. Try again after 5-10 mins, then it will be ok.</p> <pre><code>$ kubectl get nodes NAME STATUS ROLES AGE VERSION ip-172-20-37-144.us-east-2.compute.internal Ready node 25m v1.11.7 ip-172-20-45-27.us-east-2.compute.internal Ready master 26m v1.11.7 ip-172-20-51-112.us-east-2.compute.internal Ready node 25m v1.11.7 </code></pre>
<p>I have a pod with 3 containers A, B, and C. I would like to access service in Container A and B from C. Neither <code>localhost:&lt;port&gt;</code> is working nor the <code>127.0.0.1</code>.</p> <p>my yaml </p> <pre><code>apiVersion: "v1" kind: Pod metadata: name: web3 labels: name: web app: demo spec: containers: - name: client image: ubuntu command: ['cat'] tty: true - name: apache1 image: nimmis/apache-php5 ports: - containerPort: 8080 name: apacheport1 protocol: TCP - name: apache2 image: nimmis/apache-php5 command: ['cat'] tty: true ports: - containerPort: 8088 name: apacheport2 protocol: TCP </code></pre> <p>what I am doing</p> <pre><code>kubectl apply -f example.yaml kubectl exec -it web3 -c client bash </code></pre> <p>and then try to reach other 2 services</p> <pre><code>root@web3:/# curl http://localhost:8080 curl: (7) Failed to connect to localhost port 8080: Connection refused root@web3:/# curl http://localhost:8088 curl: (7) Failed to connect to localhost port 8088: Connection refused root@web3:/# curl http://localhost:80 &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;!-- Modified from the Debian original for Ubuntu </code></pre> <p>Questions How to make the first 2 curl work. (I do not want to use the service since my use case is only for testing purpose) Why there is an open port 80 when I haven't exposed the port.</p>
<p>The point is that with <code>nimmis/apache-php5</code> Apache is listening on port 80. So, it's port 80 which is exposed. Through <code>containerPort: &lt;P&gt;</code> you are not saying to expose container's port 80 to <code>&lt;P&gt;</code>, but rather exposing port <code>&lt;P&gt;</code> itself. Also, as written in the docs, <code>Not specifying a port here DOES NOT prevent that port from being exposed.</code>.</p> <p>I did not find a way to map an internal container port to a different port in the pod. However, you may map the internal container port to a host port through field <code>hostPort</code>.</p> <pre><code>apiVersion: "v1" kind: Pod metadata: name: web3 labels: name: web app: demo spec: containers: - name: client image: ubuntu command: ['cat'] tty: true - name: apache1 image: nimmis/apache-php5 ports: - containerPort: 80 name: apacheport1 hostPort: 8002 protocol: TCP - name: apache2 image: nimmis/apache-php5 command: ['cat'] tty: true ports: - containerPort: 80 hostPort: 8001 name: apacheport2 protocol: TCP </code></pre> <p>Then you get the IP of the node, e.g., on Minikube</p> <pre><code>$ minikube ip # e.g., 192.168.97.100 </code></pre> <p>and check that, from <code>client</code>, you can access the Apache services:</p> <pre><code>$ kubectl exec -it web3 -c client bash # apt-get update &amp;&amp; apt-get install curl # curl 192.168.99.100:8002 </code></pre>
<p>I'm struggling to find an example of performing a rolling update of a kubernetes deployment using client-go. Currently I scale to 0 and then back to 1 but that causes downtime.</p> <p>I wonder if there is a way to trigger a rolling update. I have nothing to change in the deployment itself. All I need is to restart a pod so that it consumes an updated ConfigMap.</p> <p>I have not found a direct way to initiate a rolling update rather than editing a deployment. But this does not work for me.</p>
<p>I ended up with just updating a deployment. Introduced an env which holds resourceVersion of a configMap that I need to watch. This causes rolling update. I have not found a direct way to initiate it</p>
<p>I'm setting up a mixed-mode kubernetes cluster (CentOS7 master, WS2019 worker) using Flannel in overlay (VXLAN) mode. I've gotten through the <a href="https://learn.microsoft.com/en-us/virtualization/windowscontainers/kubernetes/joining-windows-workers?tabs=ManagementIP" rel="nofollow noreferrer">Microsoft Kubernetes for Windows Instructions</a> but when I kick off start.ps1 I'm stuck in the "Waiting for the Network to be created" loop referenced <a href="https://learn.microsoft.com/en-us/virtualization/windowscontainers/kubernetes/common-problems#after-launching-startps1-flanneld-is-stuck-in-waiting-for-the-network-to-be-created" rel="nofollow noreferrer">here</a>. Launching flanneld directly per their instructions, I get the following error:</p> <blockquote> <p>E0306 16:43:21.218797 2576 main.go:289] Error registering network: Cannot find network with Management IP [IPAddrofWorkerNIC].</p> </blockquote> <p>The IP referenced is the main IP of the worker on the "Ethernet" NIC as called per the <code>--iface</code> argument to flanneld.</p> <p>The master and worker are both Hyper-v VMs off of a Win10 1809 box with MAC spoofing enabled. I confirmed that 6433/tcp, 10250/tcp, 4096/udp, and 4789/udp are opened in firewalld of the master. I also tried again after disabling firewalld, with no change, so I don't think the issue is on the master side.</p> <p>I tried digging through the <a href="https://github.com/coreos/flannel/blob/master/main.go" rel="nofollow noreferrer">flanneld Go code</a> at the referenced line 289 for clues but I'm not familiar with Go and had to concede defeat.</p> <p>Any ideas why I would be getting this error?</p>
<p>Apparently I didn't read the requirements closely enough. Flannel VXLAN on Windows isn't supported until Kubernetes 1.14 which will release March 25.</p> <pre><code>Overlay networking: use Flannel in vxlan mode to configure a virtual overlay network - requires either Windows Server 2019 with KB4482887 installed or Windows Server vNext Insider Preview Build 18317+ - requires Kubernetes v1.14 (or above) with WinOverlay feature gate enabled - requires Flannel v0.11.0 (or above) </code></pre>
<p>I setup a new k8s in a single node, which is tainted. But the <code>PersistentVolume</code> can not be created successfully, when I am trying to create a simple PostgreSQL.</p> <p>There is some detail information below.</p> <hr> <p>The <code>StorageClass</code> is copied from the official page: <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/#local" rel="noreferrer">https://kubernetes.io/docs/concepts/storage/storage-classes/#local</a></p> <pre><code>kind: StorageClass apiVersion: storage.k8s.io/v1 metadata: name: local-storage provisioner: kubernetes.io/no-provisioner volumeBindingMode: WaitForFirstConsumer </code></pre> <p>The <code>StatefulSet</code> is:</p> <pre><code>kind: StatefulSet apiVersion: apps/v1beta1 metadata: name: postgres spec: serviceName: postgres replicas: 1 ... volumeClaimTemplates: - metadata: name: postgres-data spec: storageClassName: local-storage accessModes: - ReadWriteOnce resources: requests: storage: 1Gi </code></pre> <p>About the running <code>StorageClass</code>:</p> <pre><code>$ kubectl describe storageclasses.storage.k8s.io Name: local-storage IsDefaultClass: No Annotations: kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"storage.k8s.io/v1","kind":"StorageClass","metadata":{"annotations":{},"name":"local-storage"},"provisioner":"kubernetes.io/no-provisioner","volumeBindingMode":"WaitForFirstConsumer"} Provisioner: kubernetes.io/no-provisioner Parameters: &lt;none&gt; AllowVolumeExpansion: &lt;unset&gt; MountOptions: &lt;none&gt; ReclaimPolicy: Delete VolumeBindingMode: WaitForFirstConsumer Events: &lt;none&gt; </code></pre> <p>About the running <code>PersistentVolumeClaim</code>:</p> <pre><code>$ kubectl describe pvc Name: postgres-data-postgres-0 Namespace: default StorageClass: local-storage Status: Pending Volume: Labels: app=postgres Annotations: &lt;none&gt; Finalizers: [kubernetes.io/pvc-protection] Capacity: Access Modes: VolumeMode: Filesystem Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal WaitForFirstConsumer &lt;invalid&gt; (x2 over &lt;invalid&gt;) persistentvolume-controller waiting for first consumer to be created before binding </code></pre> <p>K8s versions:</p> <pre><code>$ kubectl version Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.4", GitCommit:"c27b913fddd1a6c480c229191a087698aa92f0b1", GitTreeState:"clean", BuildDate:"2019-02-28T13:37:52Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:31:33Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"} </code></pre>
<p>The app is waiting for the Pod, while the Pod is waiting for a <code>PersistentVolume</code> by a <code>PersistentVolumeClaim</code>. However, the <code>PersistentVolume</code> should be prepared by the user before using.</p> <p>My previous YAMLs are lack of a <code>PersistentVolume</code> like this:</p> <pre><code>kind: PersistentVolume apiVersion: v1 metadata: name: postgres-data labels: type: local spec: storageClassName: local-storage capacity: storage: 1Gi local: path: /data/postgres persistentVolumeReclaimPolicy: Retain accessModes: - ReadWriteOnce storageClassName: local-storage nodeAffinity: required: nodeSelectorTerms: - matchExpressions: - key: app operator: In values: - postgres </code></pre> <p>The local path <code>/data/postgres</code> should be prepared before using. Kubernetes will not create it automatically.</p>
<p>I have PHP app+Apache on a Kubernetes POD. The PHP app, access Elasticsearch API on port 9200, and show a simple website, to the users, on port 5000.</p> <p>I run proxy, using <code>kubectl proxy --address='0.0.0.0' --port=8001 --accept-hosts='.*'</code>.</p> <p>When I enter to <code>"http://localhost:8001/api/v1/namespaces/default/pods/website/proxy/"</code>, I see the following error:</p> <pre><code>Error: 'dial tcp 172.17.0.6:5000: connect: connection refused' Trying to reach: 'http://172.17.0.6:5000/' </code></pre> <p>*172.17.0.6 is the POD ip address.</p> <p>This is the website POD yaml:</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: website labels: app: website spec: containers: - name: website image: website_k8s:latest ports: - containerPort: 5000 - containerPort: 80 </code></pre> <p>This is the dockerfile of website_k8s:latest:</p> <pre><code>FROM php:7.0-apache RUN echo "ServerName 0.0.0.0" &gt;&gt; /etc/apache2/apache2.conf COPY ./index.php /var/www/html/ EXPOSE 5000 </code></pre> <hr> <p>I also tried to run service:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: website-service spec: ports: - port: 5000 targetPort: 80 protocol: TCP name: serving - port: 80 targetPort: 9200 protocol: TCP name: readfromelasticsearch selector: app: website </code></pre> <p>And when I enter to <code>http://localhost:8001/api/v1/namespaces/default/services/website-service/proxy/</code>, I see:</p> <pre><code>{ "kind": "Status", "apiVersion": "v1", "metadata": { }, "status": "Failure", "message": "no endpoints available for service \"website-service\"", "reason": "ServiceUnavailable", "code": 503 } </code></pre> <p>Even though, when I run <code>$kubectl get endpoints website-service</code>, I see:</p> <pre><code>NAME ENDPOINTS AGE website-service 172.17.0.6:80,172.17.0.6:9200 59m </code></pre> <p>I see the service's POD endpoint.</p> <p>How could I access my website via proxy?</p>
<p>The problem is that Apache is listening on port 80, not 5000.</p> <p>If you remove <code>containerPort: 5000</code> then you can access the website via <code>http://localhost:8001/api/v1/namespaces/default/pods/website/proxy/</code>.</p> <p>Secondly, the endpoints you see for the service are internal to the cluster. So, you can access the service through those IP endpoints from within a pod: <code>kubectl exec website -- curl 172.17.0.6/</code>. If you want to expose your service externally, the service should be of type <code>NodePort</code> or <code>LoadBalancer</code>.</p> <p>Finally, the problem you have when querying the service through the proxy is that, when you give a name to a port, you have to include it in the proxy call: <code>curl localhost:8001/api/v1/namespaces/default/services/website-service:serving/proxy/</code>.</p>
<p>I am creating a Pod Security Policy to stop ALL users from creating a Pod as Root user. My cluster is on GKE. The steps Ive carried out till now are</p> <p>1) Enable PodSecurityPolicy in my cluster</p> <pre><code>gcloud beta container clusters update standard-cluster-11 --enable-pod-security-policy </code></pre> <p>2) Define the Policy. The policy is simple and restricts root user.</p> <pre><code>apiVersion: extensions/v1beta1 kind: PodSecurityPolicy metadata: name: a-restrict-root spec: privileged: false runAsUser: rule: MustRunAsNonRoot # &lt;------ Root user restricted. seLinux: rule: RunAsAny fsGroup: rule: RunAsAny supplementalGroups: rule: RunAsAny volumes: - '*' </code></pre> <p>3) And then ofcourse implementing the correct RBAC rules so that it can be implemented for ALL users.</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: gce:podsecuritypolicy:a-restrict-root labels: addonmanager.kubernetes.io/mode: Reconcile kubernetes.io/cluster-service: "true" rules: - apiGroups: - policy resourceNames: - a-restrict-root resources: - podsecuritypolicies verbs: - use --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: gce:podsecuritypolicy:a-restrict-root labels: addonmanager.kubernetes.io/mode: Reconcile kubernetes.io/cluster-service: "true" roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: gce:podsecuritypolicy:a-restrict-root subjects: - kind: Group apiGroup: rbac.authorization.k8s.io name: system:serviceaccounts </code></pre> <p>Now comes the part where I try to spin up a Pod. The pod definition looks like this :</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: security-context-demo spec: securityContext: runAsUser: 0 fsGroup: 0 volumes: - name: sec-ctx-vol emptyDir: {} containers: - name: sec-ctx-demo image: gcr.io/google-samples/node-hello:1.0 volumeMounts: - name: sec-ctx-vol mountPath: /data/demo securityContext: allowPrivilegeEscalation: false </code></pre> <p>As you can see, the <code>runAsUser</code> is set to <code>0</code> meaning <code>root</code>.</p> <p>When I run <code>kubectl create -f pod.yaml</code>, the pod is creating and goes into <code>Running</code> state.</p> <p>When I exec into the Pod, I can see all process running as root</p> <pre><code>$ kubectl exec -it security-context-demo -- sh # ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 4336 812 ? Ss 19:25 0:00 /bin/sh -c node server.js root 6 0.4 0.5 772124 22656 ? Sl 19:25 0:00 node server.js root 11 0.0 0.0 4336 724 ? Ss 19:26 0:00 sh root 16 0.0 0.0 17500 2072 ? R+ 19:26 0:00 ps aux </code></pre> <p>But based on my PodSecurityPolicy this should NOT be allowed. Is there something I have missed ? </p> <p><strong>UPDATE :</strong></p> <p>I spun up a default nginx pod that I know always starts as root user. Its manifest is :</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: nginx spec: containers: - name: nginx image: nginx </code></pre> <p>And when I create it, it too starts up successfully.</p> <pre><code>$ kubectl get po NAME READY STATUS RESTARTS AGE nginx 1/1 Running 0 2m </code></pre> <p>Whereas because of the PSP, it should not start up.</p>
<p>If you fetch the created pod from the API, it will contain an annotation indicating which PSP allowed the pod. I expect a different PSP is in place which allows the pod</p>
<p>I am running <strong>kubernetes single node on coreos</strong>. </p> <p>I have created a pod running a python application and exposing an http endpoint.</p> <p>I have created a kubernetes service that exposes the HTTP endpoint. I have exposed this service using NodePort and can call it successfully from outside the cluster.</p> <p>What I am then trying is to call the HTTP service from a docker container. To test I am just using the same running container and using curl. </p> <p>I can <code>docker exec</code> into the docker container running my service. nslookup for 'my-service' resolves to an IP address. So I am happy that <strong>DNS service registration is working correctly</strong>. (I have also checked that the ENV variables for the service exist - and they do and are the same as the value returned from <code>nslookup</code>) </p> <p>However, if I then try:</p> <pre><code>curl http://my-service:9042/status </code></pre> <p>It just hangs with no response. (Port 9042 is the correct port and status is a valid resource)</p> <p>I'm assuming that I'm missing something really obvious. Any suggestions warmly received.</p> <p>Update: </p> <p>The response of curl -v is:</p> <pre><code>root@lake-cluster-manager:/# curl -v http://lake-service:9042/status * Hostname was NOT found in DNS cache * Trying 10.3.0.128... </code></pre> <p>The output from nslookup is:</p> <pre><code>root@lake-cluster-manager:/# nslookup lake-service Server: 10.3.0.10 Address: 10.3.0.10#53 Name: lake-service.default.svc.cluster.local Address: 10.3.0.128 </code></pre>
<p>since Kubernetes v1.10 <code>kubectl port-forward</code> allows using resource name, such as a service name, to select a matching pod to port forward With this connection in place you can use your local workstation to debug the application that is running in the pod.</p> <p>capture your pod PORT NUMBER </p> <pre><code>kubectl get pods [YOUR_PODE_NAME] --template='{{(index (index .spec.containers 0).ports 0).containerPort}}{{"\n"}}' </code></pre> <p>let's say we got PORT NUMBER 8080</p> <pre><code>kubectl port-forward [YOUR_PODE_NAME] 8080:8080 </code></pre> <p>Now Navigate to <a href="http://localhost:8080/" rel="nofollow noreferrer">http://localhost:8080/</a> on your local machine to see your application running </p>
<p>I am trying to expose my pod</p> <pre><code>kubectl expose deployment hello-node-64c578bdf8-jp7dt --type=LoadBalancer --port=8080 Error from server (NotFound): deployments.extensions "hello-node-64c578bdf8-jp7dt" not found </code></pre> <p>These are my pods</p> <pre><code>kubectl get pods NAME READY STATUS RESTARTS AGE hazelcast-76c4785db6-wnzsb 0/1 ImagePullBackOff 0 120m hello-minikube-7bdc84f4b7-qfjv9 1/1 Running 0 113m hello-node-64c578bdf8-jp7dt 1/1 Running 0 114m </code></pre> <p>My kubectl version</p> <pre><code>Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.4", GitCommit:"c27b913fddd1a6c480c229191a087698aa92f0b1", GitTreeState:"clean", BuildDate:"2019-02-28T13:37:52Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.4", GitCommit:"c27b913fddd1a6c480c229191a087698aa92f0b1", GitTreeState:"clean", BuildDate:"2019-02-28T13:30:26Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"} </code></pre> <p>What are these deployment extensions?</p> <pre><code>kubectl get deployments NAME READY UP-TO-DATE AVAILABLE AGE hazelcast 0/1 1 0 139m hello-minikube 1/1 1 1 132m hello-node 1/1 1 1 133m </code></pre>
<p>Get the deployment using:</p> <pre><code>kubectl get deployments </code></pre> <p>then use that name in expose command. maybe you are trying to expose the pod name</p> <p>So the correct command is:</p> <pre><code>kubectl expose deployment hello-node --type=LoadBalancer --port=8080 </code></pre>
<p>In my application, I have a rest server which locally interacts with a database via the command line (it's a long story). Anyway, the database is mounted in a local ssd on the node. I can guarantee that only pods of that type will by scheduled in the node pool, as I have tainted the nodes and added tolerances to my pods.</p> <p>What I want to know is, how can I prevent kubernetes from scheduling multiple instances of my pod on a single node? I want to avoid this as I want my pod to be able to consume as much CPU as possible, and I also don't want multiple pods to interact via the local ssd.</p> <p>How do I prevent scheduling of more than one pod of my type onto the node? I was thinking daemon sets at first, but I think down the line, I want to set my node pool to auto scale, that way when I have n nodes in my pool, and I request n+1 replicas, the node pool automatically scales up.</p>
<p>You can use <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/" rel="nofollow noreferrer"><code>Daemonsets</code></a> in combination with <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/#running-pods-on-only-some-nodes" rel="nofollow noreferrer"><code>nodeSelector</code> or <code>affinity</code></a>. Alternatively you could configure <a href="https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#never-co-located-in-the-same-node" rel="nofollow noreferrer"><code>podAntiAffinity</code></a> on your <code>Pod</code>s, for example:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: rest-server spec: selector: matchLabels: app: rest-server replicas: 3 template: metadata: labels: app: rest-server spec: affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: app operator: In values: - rest-server topologyKey: "kubernetes.io/hostname" containers: - name: rest-server image: nginx:1.12-alpine </code></pre>
<p>I have set up a Kubernetes cluster using Kubernetes Engine on GCP to work on some data preprocessing and modelling using Dask. I installed Dask using Helm <a href="http://docs.dask.org/en/latest/setup/kubernetes-helm.html" rel="nofollow noreferrer">following these instructions</a>.</p> <p>Right now, I see that there are two folders, <code>work</code> and <code>examples</code></p> <p><a href="https://i.stack.imgur.com/7wIcs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7wIcs.png" alt="enter image description here"></a></p> <p>I was able to execute the contents of the notebooks in the <code>example</code> folder confirming that everything is working as expected.</p> <p>My questions now are as follows</p> <ul> <li>What are the suggested workflow to follow when working on a cluster? Should I just create a new notebook under <code>work</code> and begin prototyping my data preprocessing scripts? </li> <li>How can I ensure that my work doesn't get erased whenever I upgrade my Helm deployment? Would you just manually move them to a bucket every time you upgrade (which seems tedious)? or would you create a simple vm instance, prototype there, then move everything to the cluster when running on the full dataset?</li> </ul> <p>I'm new to working with data in a distributed environment in the cloud so any suggestions are welcome.</p>
<blockquote> <p>What are the suggested workflow to follow when working on a cluster? </p> </blockquote> <p>There are many workflows that work well for different groups. There is no single blessed workflow.</p> <blockquote> <p>Should I just create a new notebook under work and begin prototyping my data preprocessing scripts?</p> </blockquote> <p>Sure, that would be fine.</p> <blockquote> <p>How can I ensure that my work doesn't get erased whenever I upgrade my Helm deployment? </p> </blockquote> <p>You might save your data to some more permanent store, like cloud storage, or a git repository hosted elsewhere.</p> <blockquote> <p>Would you just manually move them to a bucket every time you upgrade (which seems tedious)? </p> </blockquote> <p>Yes, that would work (and yes, it is)</p> <blockquote> <p>or would you create a simple vm instance, prototype there, then move everything to the cluster when running on the full dataset?</p> </blockquote> <p>Yes, that would also work.</p> <h3>In Summary</h3> <p>The Helm chart includes a Jupyter notebook server for convenience and easy testing, but it is no substitute for a full fledged long-term persistent productivity suite. For that you might consider a project like JupyterHub (which handles the problems you list above) or one of the many enterprise-targeted variants on the market today. It would be easy to use Dask alongside any of those.</p>
<p>I would like to run some <code>kubectl</code> commands to verify the cluster post install of Helm charts. I could not find any documentation around this. In Helm, theres the concept of showing notes as part of <code>NOTES.txt</code> but doesnt look like you can run any commands at that stage.</p> <p>Is this currently impossible to do with Helm ?</p>
<p>You can define a <code>job</code> that is executed at a certain point in the <a href="https://helm.sh/docs/topics/charts_hooks/#hooks-and-the-release-lifecycle" rel="nofollow noreferrer">lifecycle</a> during <code>helm install</code>. The <a href="https://helm.sh/docs/topics/charts_hooks/#the-available-hooks" rel="nofollow noreferrer">list of available hooks</a> also contains a <code>post-install</code> hook you are probably looking for. An <a href="https://helm.sh/docs/topics/charts_hooks/#writing-a-hook" rel="nofollow noreferrer">example</a> can be found in the official documentation.</p> <p>You basically provide a Kubernetes Job, add necessary helm labels and then also an annotation like this:</p> <pre class="lang-yaml prettyprint-override"><code> annotations: &quot;helm.sh/hook&quot;: post-install </code></pre> <p>In case you are looking for something running on the client side, maybe you can <a href="https://helm.sh/docs/topics/plugins/" rel="nofollow noreferrer">use or create a Helm plugin</a>. There is a list in the official documentation: <a href="https://helm.sh/docs/community/related/#helm-plugins" rel="nofollow noreferrer">Helm Plugins</a>. You can find some more by filtering GitHub repositories for the topic <a href="https://github.com/topics/helm-plugin" rel="nofollow noreferrer">helm-plugin</a>.</p> <p>There are ideas for <a href="https://github.com/helm/community/blob/master/hips/archives/helm/helm-v3/005-plugins.md" rel="nofollow noreferrer">future development</a> to support <code>Lua</code> for scripting plugins. But the current format will still be supported.</p>
<p>I am trying to deploy a kubernetes cluster using Travis CI and I get the following error</p> <p>EDIT:</p> <blockquote> <p>invalid argument &quot;myAcc/imgName:&quot; for t: invalid reference format</p> <p>See docker build --help</p> <p>./deploy.sh: line 1: kubectl: command not found</p> </blockquote> <p>This is my travis config file</p> <p><code>travis.yml</code></p> <pre><code>sudo: required services: - docker env: global: - SHA-$(git rev-parse HEAD) - CLOUDSDK_CORE_DISABLE_PROMPTS=1 before-install: - openssl aes-256-cbc -K $encrypted_0c35eebf403c_key -iv $encrypted_0c35eebf403c_iv -in service-account.json.enc -out service-account.json -d - curl https://sdk.cloud.google.com | bash &gt; /dev/null - source $HOME/google-cloud-sdk/path.bash.inc - gcloud components update kubectl - gcloud auth activate-service-account --key-file service-account.json - gcloud config set project robust-chess-234104 - gcloud config set compute/zone asia-south1-a - gcloud container clusters get-credentials standard-cluster-1 - echo &quot;$DOCKER_PASSWORD&quot; | docker login -u &quot;$DOCKER_USERNAME&quot; --password-stdin deploy: provider: script script: bash ./deploy.sh on: branch: master </code></pre> <p>This is my deploy script</p> <p><code>deploy.sh</code></p> <pre><code>doccker build -t myAcc/imgName:$SHA docker push myAcc/imgName:$SHA kubectl apply -k8s </code></pre> <p>I guess the <code>gcloud components update kubectl</code> command is not working. Any ideas?</p> <p>Thanks !</p>
<p>The first issue <code>invalid argument "myAcc/imgName:" for t: invalid reference format</code> because the variable <code>$SHA</code> is not defined as expected. There is a syntax issue with defining the variable you should use <code>=</code> instead of <code>-</code> after SHA, so it should be like this:</p> <pre><code>- SHA=$(git rev-parse HEAD) </code></pre> <p>The second issue which is related to kubectl you need to install it using the following command according to the <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/#download-as-part-of-the-google-cloud-sdk" rel="nofollow noreferrer">docs</a>:</p> <pre><code>gcloud components install kubectl </code></pre> <p><strong>Update</strong>:</p> <p>After testing this file on Travis-CI I was able to figure out the issue. You should use <code>before_install</code> instead of <code>before-install</code> so in your case the before installation steps never get executed.</p> <pre><code># travis.yml --- env: global: - CLOUDSDK_CORE_DISABLE_PROMPTS=1 before_install: - curl https://sdk.cloud.google.com | bash &gt; /dev/null - source $HOME/google-cloud-sdk/path.bash.inc - gcloud components install kubectl script: kubectl version </code></pre> <p>And the final part of the build result:</p> <pre><code>$ kubectl version Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.7", GitCommit:"65ecaf0671341311ce6aea0edab46ee69f65d59e", GitTreeState:"clean", BuildDate:"2019-01-24T19:32:00Z", GoVersion:"go1.10.7", Compiler:"gc", Platform:"linux/amd64"} </code></pre>
<p>I am trying to run jenkins with kubernetes. I am able to make a successful connection to kubernetes using jenkins kubernetes plugin. Now, I am running a pipeline example, but while running, I always get an error saying:</p> <pre><code>Still waiting to schedule task ‘default-amd64-cm2rx’ is offline </code></pre> <p>And it hangs there. If I check pods using <code>kubectl get pods</code>, I see that the pod <code>default-amd64-cm2rx</code> was running, then state changed to completed and then it was gone. Then another pod with similar name, started and finished and the cycle continues. The last state of these pods come as:</p> <pre><code>Normal Created 10s kubelet, xx.xx.xx.xx Created container Normal Started 10s kubelet, xx.xx.xx.xx Started container </code></pre> <p>If I check the jenkins logs, I get an error as:</p> <pre><code>Mar 09, 2019 8:47:42 AM org.csanchez.jenkins.plugins.kubernetes.KubernetesLauncher launch WARNING: Error in provisioning; agent=KubernetesSlave name: default-amd64-g5bgh, template=PodTemplate{inheritFrom='', name='default-amd64', namespace='', label='jenkins-latest-jenkins-slave-amd64', nodeSelector='beta.kubernetes.io/arch=amd64', nodeUsageMode=NORMAL, workspaceVolume=EmptyDirWorkspaceVolume [memory=false], volumes=[HostPathVolume [mountPath=/var/run/docker.sock, hostPath=/var/run/docker.sock]], containers=[ContainerTemplate{name='jnlp', image='myregistry;8500/jenkins-slave:latest', workingDir='/home/jenkins', command='/bin/sh -c', args='cat', resourceRequestCpu='200m', resourceRequestMemory='256Mi', resourceLimitCpu='200m', resourceLimitMemory='256Mi', livenessProbe=org.csanchez.jenkins.plugins.kubernetes.ContainerLivenessProbe@1e7ac0a6}], yaml=} java.lang.IllegalStateException: Pod has terminated containers: default/default-amd64-g5bgh (jnlp) at org.csanchez.jenkins.plugins.kubernetes.AllContainersRunningPodWatcher.periodicAwait(AllContainersRunningPodWatcher.java:149) at org.csanchez.jenkins.plugins.kubernetes.AllContainersRunningPodWatcher.periodicAwait(AllContainersRunningPodWatcher.java:170) at org.csanchez.jenkins.plugins.kubernetes.AllContainersRunningPodWatcher.await(AllContainersRunningPodWatcher.java:122) at org.csanchez.jenkins.plugins.kubernetes.KubernetesLauncher.launch(KubernetesLauncher.java:121) at hudson.slaves.SlaveComputer$1.call(SlaveComputer.java:293) at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46) at jenkins.security.ImpersonatingExecutorService$2.call(ImpersonatingExecutorService.java:71) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) </code></pre> <p>Here is my kuebrnetes plugin config:</p> <p><a href="https://i.stack.imgur.com/VPI79.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VPI79.png" alt="enter image description here"></a></p> <p>As, you can see the connection is successful, and the pod is spawning.</p> <p>Any idea why it stays offline? TIA.</p>
<p>jnlp might be trying to use the same port for slave and Kubernetes, since it looks like your pod is terminating and you’re running this job on a slave. Set jnlp to use random port so that you can guarantee no collisions.</p> <p>In Jenkins, it’s under Configure Security.</p> <p>From Jenkins Documentation: <a href="https://jenkins.io/doc/book/managing/security/" rel="nofollow noreferrer">https://jenkins.io/doc/book/managing/security/</a></p> <p>JNLP TCP Port</p> <p>Jenkins uses a TCP port to communicate with agents launched via the JNLP protocol, such as Windows-based agents. As of Jenkins 2.0, by default this port is disabled.</p> <p>For administrators wishing to use JNLP-based agents, the two port options are:</p> <p>Random: The JNLP port is chosen random to avoid collisions on the Jenkins master. The downside to randomized JNLP ports is that they’re chosen during the boot of the Jenkins master, making it difficult to manage firewall rules allowing JNLP traffic.</p> <p>Fixed: The JNLP port is chosen by the Jenkins administrator and is consistent across reboots of the Jenkins master. This makes it easier to manage firewall rules allowing JNLP-based agents to connect to the master.</p>
<p>I am following the instructions <a href="https://kubernetes.io/docs/tasks/debug-application-cluster/audit/" rel="noreferrer">here</a> on how to create a policy to audit actions in Kubernetes. </p> <p>When I run the following YAML file: </p> <pre><code>kubectl apply -f - &lt;&lt;EOF apiVersion: audit.k8s.io/v1 # This is required. kind: Policy # Don't generate audit events for all requests in RequestReceived stage. omitStages: - "RequestReceived" rules: # Log pod changes at RequestResponse level - level: RequestResponse resources: - group: "" # Resource "pods" doesn't match requests to any subresource of pods, # which is consistent with the RBAC policy. resources: ["pods"] EOF </code></pre> <p>I received the following error: </p> <blockquote> <p>error: unable to recognize "STDIN": no matches for kind "Policy" in version "audit.k8s.io/v1" </p> </blockquote> <p>I tried to change the <code>apiVersion</code> to <code>audit.k8s.io/v1beta1</code> and also <code>v1</code> but it failed with the same error. </p> <p>Notice the flag <code>--audit-policy-file</code> doesn't appear in <code>/etc/kubernetes/manifests/kube-apiserver.yaml</code> but I don't think it is related because this is just about creating an object. </p> <p>If you want to reproduce you can go to <a href="https://labs.play-with-k8s.com" rel="noreferrer">https://labs.play-with-k8s.com</a>, create a cluster and try to create the policy. </p>
<p>Got the same on Kubernetes 1.11 using:</p> <pre><code>apiVersion: audit.k8s.io/v1 </code></pre> <p>Fixed by changing to:</p> <pre><code>apiVersion: audit.k8s.io/v1beta1 </code></pre>
<p>So i have a configmap config.json </p> <pre><code>{ "apiUrl": "http://application.cloudapp.net/", "test": "1232" } </code></pre> <p>called 'continuousdeployment'</p> <p>The pod yaml</p> <pre><code> apiVersion: v1 kind: Pod metadata: name: continuousdeployment-ui spec: containers: - name: continuousdeployment-ui image: release.azurecr.io/release.ccf.ui:2758 volumeMounts: - name: config-volume mountPath: app/wwwroot/assets/config volumes: - name: config-volume configMap: name: continuousdeployment </code></pre> <p>Without the config map set i can see the config file when going to the IP address ./assets/config/config.json and i can view it all fine. when i apply the config map the only part of the json i can then see is:</p> <pre><code> { "apiUrl": </code></pre> <p>So any ideas?</p> <p>Update - Just amended the config.json to the following</p> <pre><code>{ "test":"1232", "apiUrl":"http://applictaion.cloudapp.net/" } </code></pre> <p>and in the browser i can see </p> <pre><code>{ "test":"1232", </code></pre> <p>configmap</p> <pre><code> { "kind": "ConfigMap", "apiVersion": "v1", "metadata": { "name": "continuousdeployment-ccf-ui-config", "namespace": "default", "selfLink": "/api/v1/namespaces/default/configmaps/continuousdeployment-ccf-ui-config", "uid": "94ee863c-42b3-11e9-8872-36a65af8d9e4", "resourceVersion": "235988", "creationTimestamp": "2019-03-09T21:37:47Z" }, "data": { "config.json": "{\n \"apiUrl\": \"http://application.cloudapp.net/\"\n}" } } </code></pre> <p>even tried this</p> <pre><code>{ "kind": "ConfigMap", "apiVersion": "v1", "metadata": { "name": "continuousdeployment-ccf-ui-config1", "namespace": "default", "selfLink": "/api/v1/namespaces/default/configmaps/continuousdeployment-ccf-ui-config1", "uid": "ee50ad25-42c0-11e9-8872-36a65af8d9e4", "resourceVersion": "243585", "creationTimestamp": "2019-03-09T23:13:21Z" }, "data": { "config.json": "{\r\n \"apiUrl\": \"http://application.cloudapp.net/\"\r\n}" } } </code></pre> <p>So if i remove all odd characters and just do the alphabet, when i view the config.json it gets to 'q'</p> <pre><code>{ "kind": "ConfigMap", "apiVersion": "v1", "metadata": { "name": "continuousdeployment-ccf-ui-config1", "namespace": "default", "selfLink": "/api/v1/namespaces/default/configmaps/continuousdeployment-ccf-ui-config1", "uid": "ee50ad25-42c0-11e9-8872-36a65af8d9e4", "resourceVersion": "244644", "creationTimestamp": "2019-03-09T23:13:21Z" }, "data": { "config.json": "{abcdefghijklmnopqrstuvwxyz}" } } </code></pre>
<p>Sorted it!</p> <pre><code>volumeMounts: - mountPath: /app/wwwroot/assets/config/config.json name: config-volume subPath: config.json </code></pre> <p>Had to put the following in the pod and now the json is visable and works</p>
<p>I am new to kubernetes and have installed KOPS and now I want to use traefik as a ingress controller and cant get through it, I have a domain "xyz.com" and nameserver on cloudflare. I tried to create a "CNAME" record with my domain with ELB of aws which I get after deploying all files but it didn't worked and I don't want to use route53. I actually can't get proper guidance regarding this. Have gone through the documentation but somewhere got an idea but not working. Can anyone tell me somewhere like step wise, I will be very grateful. </p>
<p>Given your comment, that is correct. You would set your DNS for all relevant domains to CNAME to the ELB generated for the Traefik Service.</p>
<p>Given a following scheme of services and their dependencies I would like to engineer a set of Helm charts.</p> <ul> <li><code>API Gateway</code> calls <code>Service A</code> and <code>Service C</code></li> <li><code>Service A</code> calls <code>Service B</code></li> <li><code>Service B</code> calls <code>Database</code></li> <li><code>Service C</code> calls <code>Service B</code> and <code>Service D</code></li> </ul> <p>At the moment I see two alternatives:</p> <ol> <li><p>Each of the 6 components in a diagram below is a single chart and each arrow in a diagram is a single dependency. <br /> <img src="https://i.stack.imgur.com/LeCHw.png" width="400" /></p></li> <li><p>There's an <code>Umbrella</code> chart that has a dependency on all other charts. The <code>Database</code> chart is a dependency of <code>Service B</code> chart.<br /> <img src="https://i.stack.imgur.com/cgxHn.png" width="320" /></p></li> </ol> <p><a href="https://helm.sh/docs/howto/charts_tips_and_tricks/#complex-charts-with-many-dependencies" rel="noreferrer">Helm documentation</a> suggest going with option 2. I am however more keen towards option 1 due to an ease of local development and CI/CD pipeline.</p> <p>Example scenario: developer is refactoring <code>Service C</code> and he wants to run the code he changed and test it.</p> <ul> <li>Option 1. Developer installs a <code>Service C</code> chart only.</li> <li>Option 2: Developer would have to either: <ul> <li>install an <code>Umbrella</code> chart which leads to waste of a CPU and memory resources because of running unneeded services like <code>Service A</code> or <code>API Gateway</code>, which doesn't scale well with the complexity of the system;</li> <li>install <code>Service C</code>, then <code>Service B</code> and then <code>Service D</code>, which also doesn't scale well with the complexity of the system because it requires to perform many manual actions and also require from developer to be faimiliar with the architecture of the system in order to know what charts needs to be installed.</li> </ul></li> </ul> <p>I would like to make an educated decision on which alternative to take. I am more keen towards option 1, but Helm docs and also few examples I was able to find on the Internet (<a href="https://github.com/microservices-demo/microservices-demo/tree/master/deploy/kubernetes/helm-chart" rel="noreferrer">link</a>) are also going with option 2, so I think I might be missing something.</p>
<p>I would recommend one chart per service, with the additional simplification of making the "service B" chart depend on its database. I would make these charts independent: none of the services depend on any other.</p> <p>The place where Helm dependencies work well is where you have a service that embeds/hides specific single other parts. The database behind B is an implementation detail, for example, and nothing outside B needs to know about it. So B can depend on <code>stable/postgres</code> or some such, and this works well in Helm.</p> <p>There's one specific mechanical problem that causes problems for the umbrella-chart approach. Say service D also depended on a database, and it was the same "kind" of database (both use PostgreSQL, say). Operationally you want these two databases to be separate. Helm will see the two paths <code>umbrella &gt; B &gt; database</code> and <code>umbrella &gt; D &gt; database</code>, and only install one copy of the database chart, so you'll wind up with the two services sharing a database. You probably don't want that.</p> <p>The other mechanical issue you'll encounter using Helm dependencies here is that most resources are named some variant of <code>{{ .Release.Name }}-{{ .Chart.Name }}</code>. In your option 1, say you do just install service C; you'd wind up with Deployments like <code>service-C-C</code>, <code>service-C-B</code>, <code>service-C-database</code>. If you then wanted to deploy service A alongside it, that would introduce its own <code>service-A-B</code> and <code>service-A-database</code>, which again isn't what you want.</p> <p>I'm not aware of a great high-level open-source solution to this problem. A Make-based solution is hacky, but can work:</p> <pre class="lang-make prettyprint-override"><code># -*- gnu-make -*- all: api-proxy.deployed %.deployed: helm upgrade --install --name $* -f values.yaml ./charts/$* touch $@ api-proxy.deployed: a.deployed c.deployed a.deployed: b.deployed c.deployed: b.deployed d.deployed </code></pre>
<p>We need to create basic (username/password) authentication for elasticsearch and kibana oss (Apache license) running into our kubernetes clusters. We have multi-cloud installations in AWS (EKS), Google cloud (GKE), on-premise installations and we plan to use Azure.</p> <p>I think about nginx reverse proxy with basic authentication running as sidecar container in each elasticsearch/kibana pod. This is will be a simple and known solution.</p> <p>The question is: What is be the right solution in k8s cluster? What we can take from an infinite number of solutions for easy maintenance? </p>
<p>Well if you are using <code>nginx ingress controller</code> you can add basic auth like this:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: kibana namespace: kibana annotations: kubernetes.io/ingress.class: "nginx" # type of authentication nginx.ingress.kubernetes.io/auth-type: basic # name of the secret that contains the user/password definitions nginx.ingress.kubernetes.io/auth-secret: my-secret-basic-auth # message to display with an appropriate context why the authentication is required nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - kibana-admin' ... ... </code></pre> <p>The <code>my-secret-basic-auth</code> have to be created with <code>htpasswd</code>:</p> <pre><code>$ htpasswd -c auth foo New password: &lt;bar&gt; New password: Re-type new password: Adding password for user foo </code></pre> <p>Then you need to create the secret:</p> <pre><code>$ kubectl create secret generic my-secret-basic-auth --from-file=auth secret "my-secret-basic-auth" created </code></pre> <p>That's simple and easy to maintain but you will be attach to <code>nginx ingress controller</code> forever.</p>
<p>I have scheduled an application to run as a <code>CronJob</code> in Kubernetes. When there is a code change, I'm also changing the image of the <code>CronJob</code>.</p> <p>I'm looking for an option where I can disable the currently running <code>CronJob</code> and deploy a new <code>CronJob</code> with the latest image version.</p> <p>How can I disable a <code>CronJob</code> in Kubernetes without deleting its <code>Deployment</code>?</p>
<p>If you want to suspend cronjob via patch, use:</p> <pre><code>kubectl patch cronjobs &lt;job-name&gt; -p '{&quot;spec&quot; : {&quot;suspend&quot; : true }}' </code></pre>
<p>I am new to Dev Ops. I am setting up a CD pipeline in the VSTS. I have used Deploy to Kubernetes task to deploy the application, which is working fine. </p> <p>After Deploy to Kubernetes task, I have added one more Deploy to Kubernetes task and I want to execute below command</p> <p><code>kubectl describe pods &lt;podname&gt;</code></p> <p>Above command describe about the pod.</p> <p>I can see there is no such command available in the Deploy to Kubernetes task (in VSTS pipeline) for describe. </p> <p>Only available commands are <code>get, apply, set, exec, login, logout, create, delete, expose, run and top</code>.</p> <p>By executing above commands, I want to make sure is each pods is running. </p> <p>How can I execute the describe command in the VSTS CD pipeline?</p> <p>Alternative option is, any other command, which will return same output as <code>describe pods &lt;podname&gt;</code> command. </p>
<p>you can use labels to find the pod you are interested in:</p> <pre><code>$ kg po --show-labels NAME READY STATUS RESTARTS AGE LABELS frontend-76dc7bfc6d-7zcb8 1/1 Running 0 9h app=Frontend,branch=develop,pod-template-hash=76dc7bfc6d identityserverapp-f9684fc77-z9wtb 1/1 Running 0 9h app=IdentityServerApp,branch=develop,pod-template-hash=f9684fc77 $ kg po --selector=app=Frontend NAME READY STATUS RESTARTS AGE frontend-76dc7bfc6d-7zcb8 1/1 Running 0 9h </code></pre> <p>ps. <code>kg</code> = alias for <code>kubectl get</code></p>
<p>I am new to istio. Istio intercepts all traffic between two services through istio-proxy/envoy. Is it possible to configure istio so that it ignores certain type of traffic</p> <ul> <li>when serviceA makes an https call directly to serviceB on a certain port</li> <li>UDP traffic</li> </ul> <p>Thanks</p>
<p>As per Istio <a href="https://github.com/istio/istio/blob/master/install/kubernetes/helm/istio/templates/sidecar-injector-configmap.yaml" rel="nofollow noreferrer">sidecar injection configuration</a> you can exclude ports from Envoy &amp; iptables rules using the <code>includeInboundPorts</code> and <code>excludeInboundPorts</code> annotations.</p> <p>Example:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: podinfo namespace: test labels: app: podinfo spec: selector: matchLabels: app: podinfo template: metadata: annotations: traffic.sidecar.istio.io/includeInboundPorts: "*" traffic.sidecar.istio.io/excludeInboundPorts: "9999,9229" labels: app: podinfo spec: containers: - name: podinfod image: quay.io/stefanprodan/podinfo:1.4.0 imagePullPolicy: IfNotPresent ports: - containerPort: 9898 name: http protocol: TCP - containerPort: 9999 # &lt;- excluded port protocol: UDP - containerPort: 9229 # &lt;- excluded port protocol: TCP command: - ./podinfo - --port=9898 - --level=info </code></pre>
<p>I have a kafka installation running within in kubernetes cluster. I have a pod running a spring boot application which is using the default bootstrap.servers (localhost:9092) configuration and not the one passed in (bootstrap.kafka.svc.cluster.local:9092). The pod then fails to start as kafka is not running on localhost.</p> <p>Here is my spring boot configuration</p> <pre><code>spring: kafka: consumer: group-id: spring-template auto-offset-reset: earliest bootstrap-servers: "bootstrap.kafka.svc.cluster.local:9092" producer: bootstrap-servers: "bootstrap.kafka.svc.cluster.local:9092" bootstrap-servers: "bootstrap.kafka.svc.cluster.local:9092" </code></pre> <p>When setting up the consumers on startup the group id and auto-offset-reset are being correctly passed in from the above configuration. However the bootstrap-servers configuration is not and the application is actually using localhost:9092 as per the log below</p> <pre><code>2019-03-11 07:34:36.826 INFO 1 --- [ restartedMain] o.a.k.clients.consumer.ConsumerConfig : ConsumerConfig values: auto.commit.interval.ms = 5000 auto.offset.reset = earliest bootstrap.servers = [localhost:9092] check.crcs = true client.id = connections.max.idle.ms = 540000 default.api.timeout.ms = 60000 enable.auto.commit = true exclude.internal.topics = true fetch.max.bytes = 52428800 fetch.max.wait.ms = 500 fetch.min.bytes = 1 group.id = spring-template heartbeat.interval.ms = 3000 interceptor.classes = [] internal.leave.group.on.close = true isolation.level = read_uncommitted key.deserializer = class org.apache.kafka.common.serialization.StringDeserializer max.partition.fetch.bytes = 1048576 max.poll.interval.ms = 300000 max.poll.records = 500 metadata.max.age.ms = 300000 metric.reporters = [] metrics.num.samples = 2 metrics.recording.level = INFO metrics.sample.window.ms = 30000 partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor] receive.buffer.bytes = 65536 reconnect.backoff.max.ms = 1000 reconnect.backoff.ms = 50 request.timeout.ms = 30000 retry.backoff.ms = 100 sasl.client.callback.handler.class = null sasl.jaas.config = null sasl.kerberos.kinit.cmd = /usr/bin/kinit sasl.kerberos.min.time.before.relogin = 60000 sasl.kerberos.service.name = null sasl.kerberos.ticket.renew.jitter = 0.05 sasl.kerberos.ticket.renew.window.factor = 0.8 sasl.login.callback.handler.class = null sasl.login.class = null sasl.login.refresh.buffer.seconds = 300 sasl.login.refresh.min.period.seconds = 60 sasl.login.refresh.window.factor = 0.8 sasl.login.refresh.window.jitter = 0.05 sasl.mechanism = GSSAPI security.protocol = PLAINTEXT send.buffer.bytes = 131072 session.timeout.ms = 10000 ssl.cipher.suites = null ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1] ssl.endpoint.identification.algorithm = https ssl.key.password = null ssl.keymanager.algorithm = SunX509 ssl.keystore.location = null ssl.keystore.password = null ssl.keystore.type = JKS ssl.protocol = TLS ssl.provider = null ssl.secure.random.implementation = null ssl.trustmanager.algorithm = PKIX ssl.truststore.location = null ssl.truststore.password = null ssl.truststore.type = JKS value.deserializer = class org.apache.kafka.common.serialization.StringDeserializer 2019-03-11 07:34:36.942 INFO 1 --- [ restartedMain] o.a.kafka.common.utils.AppInfoParser : Kafka version : 2.0.1 2019-03-11 07:34:36.945 INFO 1 --- [ restartedMain] o.a.kafka.common.utils.AppInfoParser : Kafka commitId : fa14705e51bd2ce5 2019-03-11 07:34:37.149 WARN 1 --- [ restartedMain] org.apache.kafka.clients.NetworkClient : [Consumer clientId=consumer-1, groupId=spring-template] Connection to node -1 could not be established. Broker may not be available. </code></pre> <p>I have kubernetes service called bootstrap, running in namespace kafka in the kubernetes cluster. Here is a snippet of the log file. Why is the spring boot application not picking up the configured bootstrap.servers configuration</p>
<p>The <code>bootstrap-servers</code> property expects a list of Kafka server addresses. By putting quotation marks around the value you signaled that the value is a string and therefore create a type conflict. </p> <p>To solve this issue you should either remove the quotation marks or put the value explicitly in a list form. e.g:</p> <pre><code>spring: kafka: consumer: bootstrap-servers: ["bootstrap.kafka.svc.cluster.local:9092"] </code></pre>
<p>I want to change timezone with command. I know applying <code>hostpath</code>.</p> <p>Could you know how to apply command ?</p> <pre><code>ln -snf /user/share/zoneinfor/$TZ /etc/localtime </code></pre> <p>it works well within container. But I don't know applying with command and arguments in yaml file.</p>
<p>You can change the <code>timezone</code> of your pod by using specific timezone config and hostPath volume to set specific timezone. Your yaml file will look something like:</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: busybox-sleep spec: containers: - name: busybox image: busybox args: - sleep - &quot;1000000&quot; volumeMounts: - name: tz-config mountPath: /etc/localtime volumes: - name: tz-config hostPath: path: /usr/share/zoneinfo/Europe/Prague type: File </code></pre> <p>If you want it across all pods or deployments, you need to add volume and volumeMounts to all your deployment file and change the <code>path</code> value in <code>hostPath</code> section to the timezone you want to set.</p>
<p>I authenticated to kubernetes cluster, how can I view my RBAC roles and groups attached to my current account?</p>
<h1>Found better tool</h1> <p>this tool looks way better than rakkess<br /> exactly what I was looking for</p> <p><a href="https://github.com/reactiveops/rbac-lookup" rel="nofollow noreferrer">https://github.com/reactiveops/rbac-lookup</a></p> <p>In the simplest use case, rbac-lookup will return any matching user, service account, or group along with the roles it has been given.</p> <pre><code>rbac-lookup rob SUBJECT SCOPE ROLE rob@example.com cluster-wide ClusterRole/view rob@example.com nginx-ingress ClusterRole/edit The wide output option includes the kind of subject along with the source role binding. </code></pre> <pre><code>rbac-lookup ro --output wide SUBJECT SCOPE ROLE SOURCE User/rob@example.com cluster-wide ClusterRole/view ClusterRoleBinding/rob-cluster-view User/rob@example.com nginx-ingress ClusterRole/edit RoleBinding/rob-edit User/ron@example.com web ClusterRole/edit RoleBinding/ron-edit ServiceAccount/rops infra ClusterRole/admin RoleBinding/rops-admin </code></pre>
<p>I am new to VSTS and Azure Kubernetes. I am building a VSTS CD pipeline. I have added a Deploy to Kubernetes task in my pipeline. I am executing the get command and trying to store the output in the output variables (which is available at the bottom of the Deploy to kubernetes task). I have set the variable name. </p> <p><a href="https://i.stack.imgur.com/kxqfw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kxqfw.png" alt="VSTS output variable"></a></p> <p>I am trying to fetch the value of the above output variable. I have used command line task to set a value to the variable as mentioned below </p> <p><code>echo '##vso[task.setvariable variable=myStatusVar;isSecret=false;]$(myvar)'</code></p> <p>where <code>myvar</code> is the variable, which is set in the Deploy to kubernetes task as output variable. </p> <p>After that in another command line task, I am trying to access the <code>myStatusVar</code> variable value, but when I execute the release pipeline, it shows the message:</p> <blockquote> <p>myvar command not found</p> </blockquote> <p>Can anyone let me know, how to use the output variable of the Deploy to kuberentes task of VSTS pipeline? </p>
<p>As stated in the comments your variable is 'exposed' as 'myvar.KubectlOutput'</p> <p>the way you are able to use it in scripts differs based on type of scripting you are doing:</p> <ul> <li>Batch script: %MYVAR_KUBECTLOUTPUT% </li> <li>PowerShell script: $env:MYVAR_KUBECTLOUTPUT</li> <li>Bash script: $MYVAR_KUBECTLOUTPUT</li> <li>Azure Devops 'designer view': $(myvar.KubectlOutput)</li> </ul> <p>For more details on this see the documentation on using variables in Azure DevOps: <a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&amp;tabs=yaml%2Cbatch" rel="noreferrer">https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&amp;tabs=yaml%2Cbatch</a></p>
<p>I deployed wordpress and mysql,everything works fine I just want to know how can I access my mysql from command line</p> <pre><code>My services wordpress LoadBalancer 10.102.29.45 &lt;pending&gt; 80:31262/TCP 39m wordpress-mysql ClusterIP None &lt;none&gt; 3306/TCP 42m </code></pre> <p>Describe pod</p> <pre><code>kubectl describe pod wordpress-mysql-5fc97c66f7-jx42l Name: wordpress-mysql-5fc97c66f7-jx42l Namespace: default Priority: 0 PriorityClassName: &lt;none&gt; Node: minikube/10.0.2.15 Start Time: Mon, 11 Mar 2019 08:49:19 +0100 Labels: app=wordpress pod-template-hash=5fc97c66f7 tier=mysql Annotations: &lt;none&gt; Status: Running IP: 172.17.0.15 Controlled By: ReplicaSet/wordpress-mysql-5fc97c66f7 Containers: mysql: Container ID: docker://dcfe9037ab14c3615aec4000f89f28992c52c40a03581215d921564e5b3bec58 Image: mysql:5.6 Image ID: docker-pullable://mysql@sha256:36cad5daaae69fbcc15dd33b9f25f35c41bbe7e06cb7df5e14d8b966fb26c1b4 Port: 3306/TCP Host Port: 0/TCP State: Running Started: Mon, 11 Mar 2019 08:50:33 +0100 Ready: True </code></pre> <p>Is there any analogy to docker? How to query mysql?</p> <p>If I try with exec</p> <pre><code>kubectl exec -it wordpress-mysql-5fc97c66f7-jx42l -- /bin/bash root@wordpress-mysql-5fc97c66f7-jx42l:/# mysql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) </code></pre>
<p>To fix the issue, you have to set up a password for your MySQL user.</p> <p>According to the official <a href="https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/#create-a-secret-for-mysql-password" rel="nofollow noreferrer">documentation</a>, you need to create a Secret object containing your password:</p> <pre><code>kubectl create secret generic mysql-pass --from-literal=password=YOUR_PASSWORD </code></pre> <p>And update your deployment spec with the following part:</p> <pre><code>env: - name: MYSQL_ROOT_PASSWORD valueFrom: secretKeyRef: name: mysql-pass key: password </code></pre>
<p>I am installing prometheus to monitor K8S but I met this error. Can you help me? Thank you so much!!</p> <pre><code>helm version Client: &amp;version.Version{SemVer:"v2.13.0", GitCommit:"79d07943b03aea2b76c12644b4b54733bc5958d6", GitTreeState:"clean"} Server: &amp;version.Version{SemVer:"v2.13.0", GitCommit:"79d07943b03aea2b76c12644b4b54733bc5958d6", GitTreeState:"clean"} helm install stable/prometheus-operator --name prometheus-operator --namespace monitoring Error: customresourcedefinitions.apiextensions.k8s.io "alertmanagers.monitoring.coreos.com" is forbidden: User "system:serviceaccount:kube-system:default" cannot delete resource "customresourcedefinitions" in API group "apiextensions.k8s.io" at the cluster scope </code></pre>
<p>This is a typical situation when Tiller (server side of Helm setup) is deployed without a service account having appropriate cluster role (cluster-admin).</p> <p>You need to fix your Helm setup first, to be able to proceed with prometheus-operator installation, as described <a href="https://helm.sh/docs/using_helm/#tiller-and-role-based-access-control" rel="nofollow noreferrer">here</a>, or by running the below commands directly one by one:</p> <ol> <li><code>kubectl create serviceaccount --namespace kube-system tiller</code></li> <li><code>kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller</code></li> <li><code>kubectl patch deploy --namespace kube-system tiller-deploy -p '{"spec":{"template":{"spec":{"serviceAccount":"tiller"}}}}'</code></li> </ol>
<p>I am trying to run <code>Sonarqube</code> service using the following <a href="https://github.com/devopskube/devopskube/tree/master/charts/sonarqube" rel="noreferrer">helm chart</a>.</p> <p>So the set-up is like it starts a MySQL and Sonarqube service in the minikube cluster and Sonarqube service talks to the MySQL service to dump the data.</p> <p>When I do <code>helm install</code> followed by <code>kubectl get pods</code> I see the <code>MySQL</code> pod status as <code>running</code>, but the <code>Sonarqube</code> pod status shows as <code>CreateContainerConfigError</code>. I reckon it has to do with the mounting volume thingy: <a href="https://github.com/devopskube/devopskube/blob/master/charts/sonarqube/templates/deployment.yaml#L58" rel="noreferrer">link</a>. Although I am not quite sure how to fix it (pretty new to Kubernetes environment and till learning :) )</p>
<p>This can be solved by various ways, I suggest better go for <code>kubectl describe pod podname</code> name, you now might see the cause of why the service that you've been trying is failing. In my case, I've found that some of my key-values were missing from the configmap while doing the deployment.</p>
<p>I'm using Gitlab Autodevops to deploy app on my kubernetes cluster. That app should always have only one instance running. Problem is, during the update process, Helm kills currently running pod before the new pod is ready. This causes downtime period, when old version is already killed and new one isn't ready yet. To make it worse, app need significant time to start (2+ minutes).</p> <p>I have tried to set <code>minAvailable: 1</code> in <code>PodDisruptionBudget</code>, but no help. Any idea how can i tell helm to wait for readiness of updated pod before killing old one? (Having 2 instances running simultaneously for several second is not such a problem for me)</p>
<p>You can release a new application version in few ways, it's necessary to choose the one that fit your needs. I would recommend one of the following:</p> <p><strong>Ramped - slow rollout</strong></p> <blockquote> <p>A ramped deployment updates pods in a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment" rel="nofollow noreferrer">rolling update</a> fashion, a secondary ReplicaSet is created with the new version of the application, then the number of replicas of the old version is decreased and the new version is increased until the correct number of replicas is reached.</p> </blockquote> <pre><code>spec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 2 # how many pods we can add at a time maxUnavailable: 0 # maxUnavailable define how many pods can be unavailable # during the rolling update </code></pre> <p>Full example and steps can be found <a href="https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master/ramped" rel="nofollow noreferrer">here</a>.</p> <p><strong>Blue/Green - best to avoid API versioning issues</strong></p> <blockquote> <p>A blue/green deployment differs from a ramped deployment because the “green” version of the application is deployed alongside the “blue” version. After testing that the new version meets the requirements, we update the Kubernetes Service object that plays the role of load balancer to send traffic to the new version by replacing the version label in the selector field.</p> </blockquote> <pre><code>apiVersion: v1 kind: Service metadata: name: my-app labels: app: my-app spec: type: NodePort ports: - name: http port: 8080 targetPort: 8080 # Note here that we match both the app and the version. # When switching traffic, we update the label “version” with # the appropriate value, ie: v2.0.0 selector: app: my-app version: v1.0.0 </code></pre> <p>Full example and steps can be found <a href="https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master/blue-green" rel="nofollow noreferrer">here</a>.</p> <p><strong>Canary - for testing</strong></p> <blockquote> <p>A canary deployment consists of routing a subset of users to a new functionality. In Kubernetes, a canary deployment can be done using two Deployments with common pod labels. One replica of the new version is released alongside the old version. Then after some time and if no error is detected, scale up the number of replicas of the new version and delete the old deployment.</p> <p>Using this ReplicaSet technique requires spinning-up as many pods as necessary to get the right percentage of traffic. That said, if you want to send 1% of traffic to version B, you need to have one pod running with version B and 99 pods running with version A. This can be pretty inconvenient to manage so if you are looking for a better managed traffic distribution, look at load balancers such as <a href="http://www.haproxy.org/" rel="nofollow noreferrer">HAProxy</a> or service meshes like <a href="https://linkerd.io/" rel="nofollow noreferrer">Linkerd</a>, which provide greater controls over traffic.</p> </blockquote> <p>Manifest for version A:</p> <pre><code>spec: replicas: 3 </code></pre> <p>Manifest for version B:</p> <pre><code>spec: replicas: 1 </code></pre> <p>Full example and steps can be found <a href="https://github.com/ContainerSolutions/k8s-deployment-strategies/tree/master/canary" rel="nofollow noreferrer">here</a>.</p> <p>You can also play with <a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/update/update-interactive/" rel="nofollow noreferrer">Interactive Tutorial - Updating Your App</a> on Kubernetes.</p> <p>I recommend reading <a href="https://docs.bitnami.com/kubernetes/how-to/deploy-application-kubernetes-helm/" rel="nofollow noreferrer">Deploy, Scale And Upgrade An Application On Kubernetes With Helm</a>.</p>
<p>Hi I am playing around with Kubernetes secrets. My deployment file is :</p> <pre><code>--- apiVersion: v1 kind: Secret metadata: name: my-secrets labels: app: my-app data: username: dXNlcm5hbWU= password: cGFzc3dvcmQ= </code></pre> <p>I am able to create secrets and I am mounting them in my deployments as below:</p> <pre><code>--- apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app: my-service ports: - protocol: TCP port: 80 targetPort: 8080 type: NodePort --- apiVersion: apps/v1 kind: Deployment metadata: name: spring-service labels: app: spring-service spec: replicas: 1 selector: matchLabels: app: spring-service template: metadata: labels: app: spring-service spec: containers: - name: spring-service image: my-image:tag imagePullPolicy: Always ports: - containerPort: 8080 volumeMounts: - name: my-secret-vol mountPath: "/app/secrets/my-secret" readOnly: true volumes: - name: my-secret-vol secret: secretName: my-secrets </code></pre> <p>My question is how can I access <code>username</code> and <code>password</code> I created in secret in spring-boot app?</p> <p>I have tried loading in with <code>${my-secrets.username}</code> and <code>${username}</code>, but it fails to find values.</p> <p>I also tried adding secrets as enviroment variables as below in deployment.yml:</p> <pre><code>env: - name: username valueFrom: secretKeyRef: name: my-secrets key: username - name: password valueFrom: secretKeyRef: name: my-secrets key: password </code></pre> <p>In this case, values are loaded from secrets and when I change values of secrets in minikube dashboard, it does not reflect the changes.</p> <p>Please help me to understand how this works.</p> <p>I am using <code>minikube</code> and <code>docker</code> as containers</p>
<p>You don't inject the secret into <code>properties.yml</code>. Instead, you use the content of the secret as <code>properties.yml</code>. The process is look like the following:</p> <ul> <li>Create a <code>properties.yml</code> with the sensitive data (e.g. password)</li> <li>Base64 encode this file (e.g. <code>base64 properties.yml</code>).</li> <li>Take the base64 encoded value and put that in the secret under the key <code>properties.yaml</code>.</li> </ul> <p>You should end up with a secret in the following format:</p> <pre><code>apiVersion: v1 kind: Secret metadata: name: my-secrets labels: app: my-app data: properties.yml: dXNlcm5hbWU= </code></pre> <p>Now when you mount this secret on your pod, Kubernetes will decrypt the secret and put the value under the relevant path and you can just mount it. </p> <p>The pattern is to have 2 configuration files - one with non-sensitive configurations that is stored with the code, and the second (which includes sensitive configurations) stored as a secret. I don't know if that possible to load multiple config files using Spring Boot.</p> <p>And one final comment - this process is cumbersome and error-prone. Each change to the configuration file requires decoding the original secret and repeating this manual process. Also, it's very hard to understand what changed - all you see is the entire content has changed. For that reason, we build <a href="https://github.com/Soluto/kamus" rel="nofollow noreferrer">Kamus</a>. It let you encrypt only the sensitive value instead of the entire file. Let me know if that could be relevant for you :)</p>
<p>We recently upgraded to nginx-ingress 0.22. Before this upgrade, my service was using the old namespace <code>ingress.kubernetes.io/affinity: cookie</code> and everything was working as I expected. However, upon the upgrade to 0.22, affinity stopped being applied to my service (I don't see <code>sticky</code> anywhere in the nginx.conf).</p> <p>I looked at the docs and changed the namespace to <code>nginx.ingress.kubernetes.io</code> as shown <a href="https://kubernetes.github.io/ingress-nginx/examples/affinity/cookie/" rel="nofollow noreferrer">in this example</a>, but it didn't help.</p> <p>Is there some debug log I can look at that will show the configuration parsing/building process? My guess is that some other setting is preventing this from working (I can't imagine the k8s team shipped a release with this feature completely broken), but I'm not sure what that could be.</p> <p>My ingress config as shown by the k8s dashboard follows:</p> <pre><code> "kind": "Ingress", "apiVersion": "extensions/v1beta1", "metadata": { "name": "example-ingress", "namespace": "master", "selfLink": "/apis/extensions/v1beta1/namespaces/master/ingresses/example-ingress", "uid": "01e81627-3b90-11e9-bb5a-f6bc944a4132", "resourceVersion": "23345275", "generation": 1, "creationTimestamp": "2019-02-28T19:35:30Z", "labels": { }, "annotations": { "ingress.kubernetes.io/backend-protocol": "HTTPS", "ingress.kubernetes.io/limit-rps": "100", "ingress.kubernetes.io/proxy-body-size": "100m", "ingress.kubernetes.io/proxy-read-timeout": "60", "ingress.kubernetes.io/proxy-send-timeout": "60", "ingress.kubernetes.io/secure-backends": "true", "ingress.kubernetes.io/secure-verify-ca-secret": "example-ingress-ssl", "kubernetes.io/ingress.class": "nginx", "nginx.ingress.kubernetes.io/affinity": "cookie", "nginx.ingress.kubernetes.io/backend-protocol": "HTTPS", "nginx.ingress.kubernetes.io/limit-rps": "100", "nginx.ingress.kubernetes.io/proxy-body-size": "100m", "nginx.ingress.kubernetes.io/proxy-buffer-size": "8k", "nginx.ingress.kubernetes.io/proxy-read-timeout": "60", "nginx.ingress.kubernetes.io/proxy-send-timeout": "60", "nginx.ingress.kubernetes.io/secure-verify-ca-secret": "example-ingress-ssl", "nginx.ingress.kubernetes.io/session-cookie-expires": "172800", "nginx.ingress.kubernetes.io/session-cookie-max-age": "172800", "nginx.ingress.kubernetes.io/session-cookie-name": "route", "nginx.org/websocket-services": "example" } }, "spec": { "tls": [ { "hosts": [ "*.example.net" ], "secretName": "example-ingress-ssl" } ], "rules": [ { "host": "*.example.net", "http": { "paths": [ { "path": "/", "backend": { "serviceName": "example", "servicePort": 443 } } ] } } ] }, "status": { "loadBalancer": { "ingress": [ {} ] } } } </code></pre>
<p>As I tested Sticky session affinity with Nginx Ingress version 0.22, I can assure that it works just fine. Then when I was looking for your configuration, I replaced wildcard host <code>host: "*.example.net"</code> with i.e <code>host: "stickyingress.example.net"</code> just to ignore wildcard, and it worked fine again. So after some search I found out that from this <a href="https://github.com/kubernetes/ingress-nginx/issues/3617" rel="nofollow noreferrer">issue</a></p> <blockquote> <p>Wildcard hostnames are not supported by the Ingress spec (only SSL wildcard certificates are) </p> </blockquote> <p>Even this issue was opened for NGINX Ingress controller version: 0.21.0</p>
<p>I'm trying to orchestrate a MongoDB cluster inside Kubernetes, working with StatefulSets and Headless Services. It's been a while I'm trying to figure out what's wrong in this but can't find anything I could use.</p> <p>While doing my research I found <a href="https://github.com/pkdone/gke-mongodb-shards-demo" rel="nofollow noreferrer">this repository</a> which I cloned and adapted to the use case. You can find one of the manifests (the one for the mongoS instance) <a href="https://pastebin.com/XsM02DvS" rel="nofollow noreferrer">right here</a>. </p> <p>I then run the <code>generate.sh</code> script shipped within the repository, but with everything related to <code>gcloud</code> or <code>persistentVolume</code> commented, leaving only the <code>statefulSet</code>/<code>Service</code> spawning processes. Everything seems to be working fine, but whenever the script reaches the block </p> <pre><code># Wait for the mongos to have started properly echo "Waiting for the first mongos to come up (`date`)..." echo " (IGNORE any reported not found &amp; connection errors)" echo -n " " until kubectl --v=0 exec mongos-router-0 -c mongos-container -- mongo --quiet --eval 'db.getMongo()'; do sleep 2 echo -n " " done echo "...first mongos is now running (`date`)" echo </code></pre> <p>It just gives this error message indifenitely:</p> <pre><code>2019-03-11T14:02:03.531+0000 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused : connect@src/mongo/shell/mongo.js:343:13 @(connect):1:21 exception: connect failed command terminated with exit code 1 </code></pre> <p>Thus I tried to run <code>mongo</code> from inside the pod directly, but the same error happened. Then I just tried to run <code>mongo</code> using different ports just inside the container, running <code>mongo --port 27018</code> (also tried 27019 and 27020), just to see which kind of errors it gives with non-exposed ports, and it seems that it gives the same error.</p> <p>How could I run mongo inside a container with a running mongos on port 27017? It seems that I have to run <code>mongod</code> before running the <code>mongo</code> shell, even if <code>mongos</code> already started. It's really mind-boggling and I feel like I'm missing something. I only have this error inside the mongos pods, while the mongo-configdb and mongod-maindb seems to be running smoothly (and running the mongo shell inside them doesn't give any errors. Moreover, when doing <code>rs.status()</code> inside one of those it works fine).</p> <p>You can find some <code>mongos</code> logs <a href="https://pastebin.com/6pHGaFac" rel="nofollow noreferrer">there</a>.</p> <p><strong>TL;DR</strong> How could I run mongo inside a container with a running mongos on port 27017?</p> <p><strong>N.B.:</strong> I'm using the image <strong>mongo:3.6</strong> from the official dockerhub repository.</p>
<p>I don't really understand why, but changing the running port from 27017 to 27020 worked fine. If someone passes by and can explain how, I'd be glad to hear his/her explanation as <code>netstat -tunelp</code> (as well a <code>ps aux</code>) while grepping port 27017 on both of my k8s nodes does not give any output related to port 27017...</p>
<p>I'm using G I want to create a custom user that have only access to specific namespace, I used this yaml:</p> <pre><code>--- apiVersion: v1 kind: ServiceAccount metadata: name: develop-user namespace: develop --- kind: Role apiVersion: rbac.authorization.k8s.io/v1beta1 metadata: name: develop-user-full-access namespace: develop rules: - apiGroups: rbac.authorization.k8s.io resources: - services verbs: ["get"] --- kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1beta1 metadata: name: develop-user-view namespace: develop subjects: - kind: ServiceAccount name: develop-user namespace: develop roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: develop-user-full-access </code></pre> <p>so I get a certificate and added to my kube config, after I switched context to this new service account and figured out that I still have access to everything :(<br> Why did it happen and how to fix?</p> <p>my kubeconfig (pastebin copy: <a href="https://pastebin.com/s5Nd6Dnn" rel="nofollow noreferrer">https://pastebin.com/s5Nd6Dnn</a>):</p> <pre><code>apiVersion: v1 clusters: - cluster: certificate-authority-data: %certificate-data% server: https://animeheaven.nyah name: anime-cluster-develop contexts: - context: cluster: anime-cluster-develop namespace: develop user: develop-user name: anime-develop current-context: anime-develop kind: Config preferences: {} users: - name: develop-user user: client-key-data: %certdata% token: %tokenkey% </code></pre>
<p><a href="https://medium.com/uptime-99/making-sense-of-kubernetes-rbac-and-iam-roles-on-gke-914131b01922" rel="nofollow noreferrer">https://medium.com/uptime-99/making-sense-of-kubernetes-rbac-and-iam-roles-on-gke-914131b01922</a><br> <a href="https://medium.com/@ManagedKube/kubernetes-rbac-port-forward-4c7eb3951e28" rel="nofollow noreferrer">https://medium.com/@ManagedKube/kubernetes-rbac-port-forward-4c7eb3951e28</a></p> <p>these two articles helped me finally! I almost felt into depression because of this stupid stuff, thanks to uptime-99 and ManagedKube I did it! yay!</p> <p>the key is to create kubernetes-viewer user in gcloud and then create a role for him here is a hint!</p> <pre><code>--- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: namespace: develop name: allow-developer-port-forward rules: - apiGroups: [""] resources: ["pods", "pods/portforward"] verbs: ["get", "list", "create"] --- kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: anime-developer-port-access namespace: develop subjects: - kind: User name: ANIMEDEVERLOP@gmail.com apiGroup: rbac.authorization.k8s.io roleRef: kind: Role name: allow-developer-port-forward apiGroup: "" </code></pre> <p>then </p> <blockquote> <p>kubectly apply -f accessconfig.yaml </p> </blockquote> <p>thats it!<br> have a nice day!</p>
<p>I followed <a href="https://docs.cert-manager.io/en/venafi/tutorials/quick-start/index.html" rel="nofollow noreferrer">https://docs.cert-manager.io/en/venafi/tutorials/quick-start/index.html</a> from start to end and everything seems to be working except that I'm not getting an external ip for my ingress.</p> <pre><code>NAME HOSTS ADDRESS PORTS AGE staging-site-ingress staging.site.io,staging.admin.site.io, 80, 443 1h </code></pre> <p>Altough I'm able to use the nginx ingress controller external ip and use dns to access the sites. When I'm going to the urls I'm being redirected to https, so I assume that's working fine.</p> <p>It redirects to https but still says "not secured", so he don't get a certificate issued. </p> <p>When I'm debugging I get the following information:</p> <p><strong>Ingress</strong>:</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal CreateCertificate 54m cert-manager Successfully created Certificate "tls-secret-staging" Normal UPDATE 35m (x3 over 1h) nginx-ingress-controller Ingress staging/staging-site-ingress Normal CreateCertificate 23m (x2 over 35m) cert-manager Successfully created Certificate "letsencrypt-staging-tls" </code></pre> <p><strong>Certificate:</strong></p> <pre><code>Status: Conditions: Last Transition Time: 2019-02-27T14:02:29Z Message: Certificate does not exist Reason: NotFound Status: False Type: Ready Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal OrderCreated 3m (x2 over 14m) cert-manager Created Order resource "letsencrypt-staging-tls-593754378" </code></pre> <p><strong>Secret:</strong></p> <pre><code>Name: letsencrypt-staging-tls Namespace: staging Labels: certmanager.k8s.io/certificate-name=staging-site-io Annotations: &lt;none&gt; Type: kubernetes.io/tls Data ==== ca.crt: 0 bytes tls.crt: 0 bytes tls.key: 1679 bytes </code></pre> <p><strong>Order:</strong></p> <pre><code>Status: Certificate: &lt;nil&gt; Finalize URL: Reason: State: URL: Events: &lt;none&gt; </code></pre> <p>So it seems something goes wrong in order and no challenges are created. </p> <p>Here are my ingress.yaml and issuer.yaml:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: staging-site-ingress annotations: kubernetes.io/ingress.class: "nginx" certmanager.k8s.io/issuer: "letsencrypt-staging" certmanager.k8s.io/acme-challenge-type: http01 spec: tls: - hosts: - staging.site.io - staging.admin.site.io - staging.api.site.io secretName: letsencrypt-staging-tls rules: - host: staging.site.io http: paths: - backend: serviceName: frontend-service servicePort: 80 path: / - host: staging.admin.site.io http: paths: - backend: serviceName: frontend-service servicePort: 80 path: / - host: staging.api.site.io http: paths: - backend: serviceName: gateway-service servicePort: 9000 path: / </code></pre> <pre><code>apiVersion: certmanager.k8s.io/v1alpha1 kind: Issuer metadata: name: letsencrypt-staging namespace: staging spec: acme: server: https://acme-staging-v02.api.letsencrypt.org/directory email: hello@site.io privateKeySecretRef: name: letsencrypt-staging-tls http01: {} </code></pre> <p>Anyone knows what I can do to fix this or what went wrong? Certmanager is installed correctly 100%, I'm just not sure about the ingress and what went wrong in the order.</p> <p>Thanks in advance!</p> <p>EDIT: I found this in the nginx-ingress-controller:</p> <pre><code>W0227 14:51:02.740081 8 controller.go:1078] Error getting SSL certificate "staging/letsencrypt-staging-tls": local SSL certificate staging/letsencrypt-staging-tls was not found. Using default certificate </code></pre> <p>It's getting spammed &amp; the CPU load is always at 0.003 and the cpu graph is full (the other services are almost nothing)</p>
<p>I stumbled over the same issue once, following exactly the same official tutorial. As @mikebridge mentioned, the issue is with Issuer/Secret's namespace mismatch.</p> <p>For me, the best was to switch from Issuer to <a href="https://docs.cert-manager.io/en/venafi/reference/clusterissuers.html?highlight=ClusterIssuer#clusterissuers" rel="nofollow noreferrer">ClusterIssuer</a>, which is not scoped to a single namespace.</p>
<p>I am trying to follow something similar to the Istio injection model where Istio is able to run a mutating admission webhook in order to auto inject their sidecar.</p> <p>We would like to do something similar, but with some config maps. We have a need to mount config maps to all new pods in a given namespace, always mounted at the same path. Is it possible to create a mutating admission webhook that will allow me to mount this config map at the known path while admitting new pods?</p> <p>docs to mutating webhooks: <a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/" rel="nofollow noreferrer">https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/</a></p>
<p>This should be entirely possible and is, in fact, an aligned use-case for a custom mutating admission webhook. Unfortunately, the official documentation on actually implementing them is somewhat sparse.</p> <p><a href="https://github.com/morvencao/kube-mutating-webhook-tutorial" rel="nofollow noreferrer">This is the most useful reference material</a> I found when I was working on <a href="https://github.com/kubernetes-sigs/mutating-trace-admission-controller" rel="nofollow noreferrer">this mutating admission webhook</a>.</p> <p>The general process is as follows:</p> <ol> <li>Generate and deploy certificates <a href="https://github.com/morvencao/kube-mutating-webhook-tutorial#deploy" rel="nofollow noreferrer">as demonstrated here</a></li> <li>Deploy <a href="https://github.com/kubernetes-sigs/mutating-trace-admission-controller/blob/master/deploy/base/mutatingwebhook.yaml" rel="nofollow noreferrer">MutatingWebhookConfiguration</a> to your cluster. This configuration allows us to tell the API server where to send the <code>AdmissionReview</code> objects. This is also where you should specify which operations on which API resources in which namespaces you want to target.</li> <li>Write the actual webhook server, which should accept <code>AdmissionReview</code> objects at the specified endpoint (<code>/mutate</code> is the convention) and return <code>AdmissionResponse</code> objects with the mutated object, <a href="https://github.com/kubernetes-sigs/mutating-trace-admission-controller/blob/589ff8723d1bc632c0ba2bb55313986db126d750/webhook.go#L85" rel="nofollow noreferrer">as is shown here</a> (note: in the linked example, I added an annotation to incoming pods that fit a certain criteria, while your application would add a field for the <code>ConfigMap</code>)</li> <li>Deploy the webhook server and expose it using normal methods (<code>Deployment</code> and <code>Service</code>, or whatever fits your use case). Make sure it's accessible at the location you specified in the configuration for the <code>MutatingWebhookConfiguration</code></li> </ol> <p>Hope this was enough information! Let me know if I left anything too vague / was unclear.</p>
<p>I have a Java-based server managed by the kubernetes cluster. It's a distributed environment where the number of the instance is set to 4 to handle millions of request per minute.</p> <p><em>The issue</em> that I am facing is kubernetes tries to balance the cluster and in the process kills the pod and take it to another node, but there are <strong>pending HTTP request</strong> GET and POST that gets lost.</p> <p>What is the solution by kubernetes or architectural solution that would let me retry if the request is stuck/ failed?</p> <p>UPDATE:</p> <p>I have two configurations for kubernetes service:</p> <ol> <li>LoadBalancer (is with AWS ELB): <em>for external facing</em></li> <li>ClusterIP: <em>for internal microservice based architecture</em></li> </ol>
<p>Kubernetes gives you the means to gracefully handle pod terminations via SIGTERM and preStop hooks. There are several articles on this, e.g. <a href="https://pracucci.com/graceful-shutdown-of-kubernetes-pods.html" rel="nofollow noreferrer">Graceful shutdown of pods with Kubernetes</a>. In your Java app, you should listen for SIGTERM and gracefully shutdown the server (most http frameworks have this "shutdown" functionality built in them).</p> <blockquote> <p>The issue that I am facing is kubernetes tries to balance the cluster and in the process kills the pod and take it to another node</p> </blockquote> <p>Now this sounds a little suspicious - in general K8s only evicts and reschedules pods on different nodes under specific circumstances, for example when a node is running out of resources to serve the pod. If your pods are frequently getting rescheduled, this is generally a sign that something else is happening, so you should probably determine the root cause (if you have resource limits set in your deployment spec make sure your service container isn't exceeding those - this is a common problem with JVM containers).</p> <p>Finally, HTTP retries are inherently unsafe for non-idempotent requests (POST/PUT), so you can't just retry on any failed request without knowing the logical implications. In any case, retries generally happen on the client side, not server, so it's not a flag you can set in K8s to enable them. </p>
<p>I have deployed my object detection model to Google Kubernetes Engine. My model is trained using faster_rcnn_resnet101_pets configuration. The inference time of my model is very high (~10 seconds total time for prediction and ) even though I am using a Nvidia Tesla K80 GPU in my cluster node. I am using gRPC for getting predicitons from the model. The script for making prediciton requests is :</p> <pre><code>import argparse import os import time import sys import tensorflow as tf from PIL import Image import numpy as np from grpc.beta import implementations sys.path.append("..") from object_detection.core.standard_fields import \ DetectionResultFields as dt_fields from object_detection.utils import label_map_util from argparse import RawTextHelpFormatter from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2_grpc tf.logging.set_verbosity(tf.logging.INFO) WIDTH = 1024 HEIGHT = 768 def load_image_into_numpy_array(input_image): image = Image.open(input_image) image = image.resize((WIDTH, HEIGHT), Image.ANTIALIAS) (im_width, im_height) = image.size image_arr = np.array(image.getdata()).reshape( (im_height, im_width, 3)).astype(np.uint8) image.close() return image_arr def load_input_tensor(input_image): image_np = load_image_into_numpy_array(input_image) image_np_expanded = np.expand_dims(image_np, axis=0).astype(np.uint8) tensor = tf.contrib.util.make_tensor_proto(image_np_expanded) return tensor def main(args): start_main = time.time() host, port = args.server.split(':') channel = implementations.insecure_channel(host, int(port))._channel stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) request = predict_pb2.PredictRequest() request.model_spec.name = args.model_name input_tensor = load_input_tensor(args.input_image) request.inputs['inputs'].CopyFrom(input_tensor) start = time.time() result = stub.Predict(request, 60.0) end = time.time() output_dict = {} output_dict[dt_fields.detection_classes] = np.squeeze( result.outputs[dt_fields.detection_classes].float_val).astype(np.uint8) output_dict[dt_fields.detection_boxes] = np.reshape( result.outputs[dt_fields.detection_boxes].float_val, (-1, 4)) output_dict[dt_fields.detection_scores] = np.squeeze( result.outputs[dt_fields.detection_scores].float_val) category_index = label_map_util.create_category_index_from_labelmap(args.label_map, use_display_name=True) classes = output_dict[dt_fields.detection_classes] scores = output_dict[dt_fields.detection_scores] classes.shape = (1, 300) scores.shape = (1, 300) print("prediction time : " + str(end-start)) objects = [] threshold = 0.5 # in order to get higher percentages you need to lower this number; usually at 0.01 you get 100% predicted objects for index, value in enumerate(classes[0]): object_dict = {} if scores[0, index] &gt; threshold: object_dict[(category_index.get(value)).get('name').encode('utf8')] = \ scores[0, index] objects.append(object_dict) print(objects) end_main = time.time() print("Overall Time : " + str(end_main-start_main)) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Object detection grpc client.", formatter_class=RawTextHelpFormatter) parser.add_argument('--server', type=str, default='localhost:9000', help='PredictionService host:port') parser.add_argument('--model_name', type=str, default="my-model", help='Name of the model') parser.add_argument('--input_image', type=str, default='./test_images/123.jpg', help='Path to input image') parser.add_argument('--output_directory', type=str, default='./', help='Path to output directory') parser.add_argument('--label_map', type=str, default="./data/object_detection.pbtxt", help='Path to label map file') args = parser.parse_args() main(args) </code></pre> <p>I have used kubectl port forwarding for testing purposes so the request port is set to localhost:9000. </p> <p>The output is :</p> <pre><code>prediction time : 6.690936326980591 [{b'goi_logo': 0.9999970197677612}] Overall Time : 10.25893259048462 </code></pre> <p>What can I do to make my inference faster? I have seen that the inference time is in the order of milliseconds so in comparison 10 seconds is a very long duration and unfit for production environments. I understand that port forwarding is slow. What is another method that I can use? I need to make this client available to the world as an API endpoint.</p>
<p>As previous answers stated, you should indeed try to do multiple requests because tf-serving needs some overhead the first time(s). You can prevent this by using a warm-up script.</p> <p>To add some extra options: </p> <ul> <li><p>from tf-serving v1.8 you can also use a http rest API service. Then you can call the service that you have created on your GKE from a google compute engine to reduce the connection lag. In my case it had a big speed-up because my local connection was mediocre at best. Next to http rest api being more workable to debug, you can also send much bigger requests. The grpc limit seems to be 1.5 mb while the http one is a lot higher.</p></li> <li><p>Are you sending b64 encoded images? Sending the images themselves is a lot slower than sending b64 encoded strings. The way I handled this is sending b64 encoded strings from the images and create some extra layers in front of my network that transform the string to jpeg images again and then process them through the model. Some code to help you on your way:</p></li> </ul> <blockquote> <pre><code>from keras.applications.inception_v3 import InceptionV3, preprocess_input from keras.models import Model import numpy as np import cv2 import tensorflow as tf from keras.layers import Input, Lambda from keras import backend as K base_model = InceptionV3( weights='imagenet', include_top=True) model = Model( inputs=base_model.input, outputs=base_model.get_layer('avg_pool').output) def prepare_image(image_str_tensor): #image = tf.squeeze(tf.cast(image_str_tensor, tf.string), axis=[0]) image_str_tensor = tf.cast(image_str_tensor, tf.string) image = tf.image.decode_jpeg(image_str_tensor, channels=3) #image = tf.divide(image, 255) #image = tf.expand_dims(image, 0) image = tf.image.convert_image_dtype(image, tf.float32) return image def prepare_image_batch(image_str_tensor): return tf.map_fn(prepare_image, image_str_tensor, dtype=tf.float32) # IF BYTE STR model.layers.pop(0) print(model.layers[0]) input_img = Input(dtype= tf.string, name ='string_input', shape = () ) outputs = Lambda(prepare_image_batch)(input_img) outputs = model(outputs) inception_model = Model(input_img, outputs) inception_model.compile(optimizer = "sgd", loss='categorical_crossentropy') weights = inception_model.get_weights() </code></pre> </blockquote> <ul> <li>Next to that, I would say use a bigger gpu. I have basic yolo (keras implementation) now running on a P100 with about 0.4s latency when called from a compute engine. We noticed that the darknet implementation (in c++) is a lot faster than the keras implementation tho.</li> </ul>
<p>I am using GKE. I've launched the following traefik deployment through kubectl:</p> <p><a href="https://github.com/containous/traefik/blob/master/examples/k8s/traefik-deployment.yaml" rel="nofollow noreferrer">https://github.com/containous/traefik/blob/master/examples/k8s/traefik-deployment.yaml</a></p> <p>The pod runs on the kube-system namespace. I'm not able to ssh into the pod. </p> <p><code>kubectl get po -n kube-system traefik-ingress-controller-5bf599f65d-fl9gx 1/1 Running 0 30m</code></p> <p><code>kubectl exec -it traefik-ingress-controller-5bf599f65d-fl9gx -n kube-system -- '\bin\bash' rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "exec: \"\\\\bin\\\\bash\": executable file not found in $PATH" command terminated with exit code 126</code></p> <p>Am I missing something? The same thing for '-- sh' too.</p>
<p>rather use forward slashed <code>/</code> (your example has a backslash) such as in</p> <pre><code>kubectl exec -it traefik-ingress-controller-5bf599f65d-fl9gx -n kube-system -- '/bin/bash' </code></pre> <p>If this does still not work, try a different shell such as</p> <pre><code>kubectl exec -it traefik-ingress-controller-5bf599f65d-fl9gx -n kube-system -- '/bin/sh' </code></pre>
<p>i've problem when i run a php deployment with kubernetes becouse don't load the modules or extensions libraries.</p> <p>My deployment file is this:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: php labels: app: php spec: selector: matchLabels: app: php replicas: 1 template: metadata: labels: app: php spec: containers: - name: php image: php:7-fpm env: - name: PHP_INI_SCAN_DIR value: :/usr/local/etc/php/conf.custom ports: - containerPort: 9000 lifecycle: postStart: exec: command: ["/bin/sh","-c","docker-php-ext-install pdo pdo_mysql mysqli &amp;&amp; docker-php-ext-enable pdo pdo_mysql mysqli"] volumeMounts: - name: php-conf mountPath: /usr/local/etc/php/conf.custom volumes: - name: php-conf configMap: name: php </code></pre> <p>And my ConfigMap is this:</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: php labels: app: php data: wordpress-custom.ini: |- upload_max_filesize = 100M post_max_size = 100M default.ini: |- extension=pdo_mysql.so extension=mysqli.so </code></pre> <p>Later i go into the Pod with command "exec -it" and i put again "docker-php-ext-enable mysqli" to check it, but i receive the message "warning: mysqli (mysqli.so) is already loaded!", but when i run the "phpinfo()" command, i see "upload_max_filesize = 100M" and "post_max_size = 100M" updated, but i can't see modules enabled.</p> <p>What i can do? very thank's</p>
<p>The problem is that your docker CMD is to run php-fpm </p> <p><a href="https://github.com/docker-library/php/blob/bb16de8a711d1ba1dc76adf4665b3b1c06a06922/7.3/stretch/fpm/Dockerfile#L266" rel="nofollow noreferrer">https://github.com/docker-library/php/blob/bb16de8a711d1ba1dc76adf4665b3b1c06a06922/7.3/stretch/fpm/Dockerfile#L266</a></p> <p>and after container started you cannot change loaded to memory php configuration. </p> <p>You need to restart php-fpm to apply changes, but restart kills container and you loose all changes. To add some libraries for php you should to create your own docker image and install all your libraries into the image instead of installing it in runtime.</p> <p>Check also this issue on github <a href="https://github.com/docker-library/php/issues/331" rel="nofollow noreferrer">https://github.com/docker-library/php/issues/331</a></p> <p>So answer is to create your own image and install all required extensions with docker RUN command</p> <pre><code>FROM php:7-fpm RUN apt-get install php-pdo php-mysql </code></pre> <p>After that you have to build this image</p> <pre><code>docker build -t php:7-fpm-mysql . </code></pre> <p>push it to some docker registry. For example hub.docker.com</p> <pre><code>docker push php:7-fpm-mysql </code></pre> <p>NOTE: php mysql extension is deprecated since PHP 5.5.*, use PDO instead</p>
<p>When I set the Cronjob Schedule as <code>*/1 * * * *</code>,it would work.</p> <p>When I set any number which is in <code>0-59</code> to the <code>crontab minute</code>,such as <code>30 * * * *</code>,it would work as well.</p> <p>However when I set the Cronjob Schedule as <code>30 11 * * *</code>,it even doesn`t create a job at 11:30.</p> <p>All the config is followed:</p> <pre><code> apiVersion: batch/v1beta1 kind: CronJob metadata: name: hello spec: schedule: &quot;33 11 * * *&quot; jobTemplate: spec: template: spec: containers: - name: hello-cronjob image: busybox command: [&quot;bash&quot;,&quot;-c&quot;,&quot;date;echo Hello from the Kubernetes cluste&quot;] restartPolicy: OnFailure </code></pre>
<p>This is probably because your cluster is running in a different timezone then the one used by you.</p> <p>You can check what timezone will be set in a <code>POD</code> using:</p> <p><code>kubectl run -i --tty busybox --image=busybox --restart=Never -- date</code>.</p> <p>As for your <code>yaml</code> it looks good, there is no need to change anything with the <code>spec.schedule</code> value.</p> <p>A small hint that might be helpful to you which is checking the logs from <code>Jobs</code>.</p> <p>When you create <code>CronJob</code> when it's scheduled it will spawn a <code>Job</code>, you can see them using <code>kubectl get jobs</code>.</p> <pre><code>$ kubectl get jobs NAME DESIRED SUCCESSFUL AGE hello-1552390680 1 1 7s </code></pre> <p>If you use the name of that job <code>hello-1552390680</code> and set it as a variable you can check the logs from that job.</p> <pre><code>$ pods=$(kubectl get pods --selector=job-name=hello-1552390680 --output=jsonpath={.items..metadata.name}) </code></pre> <p>You can later check logs:</p> <pre><code>$ kubectl logs $pods Tue Mar 12 11:38:04 UTC 2019 Hello from the Kubernetes cluster </code></pre>
<p>Being completly new to google cloud, and almost new to kubernetes, I struggled my whole weekend trying to deploy my app in GKE. My app consists of a react frontend, nodejs backend, postgresql database (connected to the backend with a cloudsql-proxy) and redis.</p> <p>I serve the frontend and backend with an Ingress, everything seems to be working and all, my pods are running. The ingress-nginx exposes the endpoint of my app, but when when I open it, instead of seeing my app, I see blank page with a 200 response. And when I do <strong>kubectl logs MY_POD</strong>, I can see that my react app is running.</p> <p>Ingress:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: superflix-ingress-service namespace: default annotations: kubernetes.io/ingress.class: nginx kubernetes.io/ingress.global-static-ip-name: "web-static-ip" nginx.ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/ssl-redirect: "false" spec: rules: - http: paths: - path: /* backend: serviceName: superflix-ui-node-service servicePort: 3000 - path: /graphql/* backend: serviceName: superflix-backend-node-service servicePort: 4000 </code></pre> <p>Here is my backend:</p> <pre><code>kind: Service apiVersion: v1 metadata: name: superflix-backend-node-service spec: type: NodePort selector: app: app ports: - port: 4000 targetPort: 4000 # protocol: TCP name: http --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: superflix-backend-deployment namespace: default spec: replicas: 2 template: metadata: labels: app: app spec: containers: - name: superflix-backend image: gcr.io/superflix-project/superflix-server:v6 ports: - containerPort: 4000 # The following environment variables will contain the database host, # user and password to connect to the PostgreSQL instance. env: - name: REDIS_HOST value: superflix-redis.default.svc.cluster.local - name: IN_PRODUCTION value: "true" - name: POSTGRES_DB_HOST value: "127.0.0.1" - name: POSTGRES_DB_PORT value: "5432" - name: REDIS_PASSWORD valueFrom: secretKeyRef: name: redis-env-secrets key: REDIS_PASS # [START cloudsql_secrets] - name: POSTGRES_DB_USER valueFrom: secretKeyRef: name: cloudsql-db-credentials key: username - name: POSTGRES_DB_PASSWORD valueFrom: secretKeyRef: name: cloudsql-db-credentials key: password # [END cloudsql_secrets] # [START proxy_container] - name: cloudsql-proxy image: gcr.io/cloudsql-docker/gce-proxy:1.11 command: ["/cloud_sql_proxy", "-instances=superflix-project:europe-west3:superflix-db=tcp:5432", "-credential_file=/secrets/cloudsql/credentials.json"] # [START cloudsql_security_context] securityContext: runAsUser: 2 # non-root user allowPrivilegeEscalation: false # [END cloudsql_security_context] volumeMounts: - name: cloudsql-instance-credentials mountPath: /secrets/cloudsql readOnly: true # [END proxy_container] # [START volumes] volumes: - name: cloudsql-instance-credentials secret: secretName: cloudsql-instance-credentials # [END volumes] </code></pre> <p>And here is my frontend:</p> <pre><code>kind: Service apiVersion: v1 metadata: name: superflix-ui-node-service spec: type: NodePort selector: app: app ports: - port: 3000 targetPort: 3000 # protocol: TCP name: http --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: superflix-ui-deployment namespace: default spec: replicas: 1 template: metadata: labels: app: app spec: containers: - name: superflix-ui image: gcr.io/superflix-project/superflix-ui:v4 ports: - containerPort: 3000 env: - name: IN_PRODUCTION value: 'true' - name: BACKEND_HOST value: superflix-backend-node-service </code></pre> <p>EDIT:</p> <p>When I look at the stackdriver logs of my nginx-ingress-controller I have warnings:</p> <blockquote> <p>Service "default/superflix-ui" does not have any active Endpoint. Service "default/superflix-backend" does not have any active Endpoint.</p> </blockquote>
<p>I actually found what was the issue. I changed the ingress service path from <strong>/*</strong> to <strong>/</strong>, and now it is working perfectly.</p>
<p>I want a Kubernetes StatefulSet with:</p> <ul> <li>Number of Replicas/Pods = Number of Nodes in Kubernetes Cluster</li> <li>One Pod on on every node</li> </ul> <p>Is there a simple example on how to solve this typical requirement?</p>
<p>DaemonSets are exactly what you're looking for. They're a tool which will run a single Pod on every node for your resource. If a new node is created - a new Pod is created on it.</p> <p>You can find further information onto how they're implemented at the following URL in the documentation:</p> <p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/</a></p>
<p>I have a MySQL database pod with 3 replicas.<br>Now I'm making some changes in one pod(pod data,not pod configuration), say I'm adding a table.<br>How will the change reflect on the other replicas of the pod?</p> <p>I'm using kubernetes v1.13 with 3 worker nodes.</p>
<p>PODs do not sync. Think of them as independend processes.</p> <p>If you want a clustered MySQL installation, the Kubernetes docs describe how to do this by using a StatefulSet: <a href="https://kubernetes.io/docs/tasks/run-application/run-replicated-stateful-application/#deploy-mysql" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/run-application/run-replicated-stateful-application/#deploy-mysql</a></p> <p>In essence you have to configure master/slave instances of MySQL yourself.</p>
<p>I understand the difference between ReplicaSet and ReplicationController, of former being Set based and the latter Equality based. What I want to know is why was a newer implementation (Read ReplicaSet) introduced when the older ReplicationController achieves the same functionality.</p>
<p><code>ReplicaSet</code> is usually not standalone, these are owned by <code>Deployment</code>. A single <code>Deployment</code> can have many <code>ReplicaSet</code>s in its life cycle as new <code>Version</code> deployment added one more <code>ReplicaSet</code>. </p> <p><code>Deployment</code> allows us to rollback to previous stable releases if required.</p>
<p>Is there a way to configure a liveness probe to stop running when a Pod has successfully completed?</p> <p>I'm using a liveness probe to ensure that batch Jobs (which are expected to run to completion over the course of a few minutes to weeks) are responsive and running properly. However, when a Pod completes successfully, there seems to be a delay between when the Pod stops serving the liveness probe (in this case, touch-ing a file) and when the Pod is deleted after completing successfully. During this delay, the liveness probe fails enough times to trigger Kubernetes to restart the Pod.</p> <p>Aside from increasing the liveness probe's failure threshold or period, or decreasing the Pod's termination grace period, I haven't come across any possible mitigations, and no robust solutions, for this issue. In fact, I haven't found any mention in the Kubernetes' docs of using a liveness probe in a batch Job.</p> <p>The events log from <code>kubectl describe pod &lt;pod&gt;</code> is below. Of particular interest to me, and what's guiding my thinking that the liveness probe is failing during the Pod's completion, is the message <code>Liveness probe failed: OCI runtime exec failed: exec failed: cannot exec a container that has stopped: unknown</code>.</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning Unhealthy 55m kubelet, pascal0 Liveness probe failed: OCI runtime exec failed: exec failed: cannot exec a container that has stopped: unknown Normal Created 55m (x8 over 21h) kubelet, pascal0 Created container Normal Pulled 55m (x7 over 18h) kubelet, pascal0 Container image "&lt;image&gt;" already present on machine Normal Started 55m (x8 over 21h) kubelet, pascal0 Started container </code></pre> <p>Some relevant Job configuration values are included below.</p> <pre><code>backoffLimit: 10 restartPolicy: OnFailure livenessProbe: exec: command: - test - $(stat -c %Y /tmp/healthy) -gt $(($(date +%s) - 10)) initialDelaySeconds: 30 periodSeconds: 60 timeoutSeconds: 1 successThreshold: 1 failureThreshold: 3 </code></pre>
<blockquote> <p>Aside from increasing the liveness probe's failure threshold or period, or decreasing the Pod's termination grace period, I haven't come across any possible mitigations, and no robust solutions, for this issue. </p> </blockquote> <p>There is nothing wrong with tweaking those parameters to meet your needs. <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods" rel="nofollow noreferrer">Default</a> pod graceful termination period is 30 seconds, so if your container needs more time to terminate, you should change the probe timings accordingly. Or I've probably missed the main point why it can be an issue in your case.</p> <blockquote> <p>In fact, I haven't found any mention in the Kubernetes' docs of using a liveness probe in a batch Job.</p> </blockquote> <p>Me neither. Apparently, it's not very popular approach and probably therefore is not tested well enough. </p> <p>Thinking about workarounds, I was about suggesting to use a <a href="https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks" rel="nofollow noreferrer"><strong>preStop</strong> hook</a>, but after reading the <a href="https://github.com/kubernetes/kubernetes/issues/55807" rel="nofollow noreferrer">whole story</a>, I found an alternative <a href="https://github.com/kubernetes/kubernetes/issues/55807#issuecomment-357841521" rel="nofollow noreferrer">suggestion</a> made by <a href="https://github.com/srikumarb" rel="nofollow noreferrer">srikumarb</a> in the issue <a href="https://github.com/kubernetes/kubernetes/issues/55807" rel="nofollow noreferrer">#55807</a>:</p> <blockquote> <p>I ended up using livenessProbe with a timestamp file to know the liveliness of the container from sidecar container. Hope that helps as a workaround for you also</p> </blockquote> <p>You may also think about configuring a <a href="https://medium.com/google-cloud/kubernetes-liveness-checks-4e73c631661f" rel="nofollow noreferrer">different kind</a> of the liveness probe, e.g checking the uptime (or whatever is not related to the filesystem) </p> <p>Alternatively, you can try to use <a href="https://kubernetes.io/docs/concepts/storage/volumes/#emptydir" rel="nofollow noreferrer">EmptyDir volume</a> as a placeholder for your probe file.</p>
<p>I have a kubernetes ingress manifest YAML, looking like next:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: certmanager.k8s.io/acme-http01-edit-in-place: "true" certmanager.k8s.io/cluster-issuer: letsencrypt name: staging namespace: dev spec: rules: - host: staging.domain.com http: paths: - backend: serviceName: task-11111 servicePort: 80 path: /task-11111/* - backend: serviceName: task-22222 servicePort: 80 path: /task-22222/* - backend: serviceName: task-33333 servicePort: 80 path: /task-33333/* tls: - hosts: - staging.domain.com secretName: staging-domain-com </code></pre> <p>What I'm trying to achieve is to add (if not present) or remove (if present) a backend block. What I have now:</p> <pre><code>yq -y '.spec.rules[].http.paths += [{ "backend": { "serviceName": "'${CI_COMMIT_REF_NAME}'", "servicePort": 80}, "path": "/'${CI_COMMIT_REF_NAME}'/*"}]' </code></pre> <p>(adds a new block with variable value, but doesn't bother if it already exists)</p> <pre><code>yq -y 'del(.. | .paths? // empty | .[] | select(.path |contains("'${CI_COMMIT_REF_NAME}'")) )' </code></pre> <p>(fails with <code>jq: error (at &lt;stdin&gt;:0): Invalid path expression with result {"backend":{"serviceName":...</code>)</p> <p>So rules may look like this after deletion (assume that <code>CI_COMMIT_REF_NAME</code> = <code>task-33333</code>):</p> <pre><code>spec: rules: - host: staging.domain.com http: paths: - backend: serviceName: task-11111 servicePort: 80 path: /task-11111/* - backend: serviceName: task-22222 servicePort: 80 path: /task-22222/* </code></pre> <p>or like this after adding (assume that <code>CI_COMMIT_REF_NAME</code> = <code>task-44444</code>):</p> <pre><code>spec: rules: - host: staging.domain.com http: paths: - backend: serviceName: task-11111 servicePort: 80 path: /task-11111/* - backend: serviceName: task-22222 servicePort: 80 path: /task-22222/* - backend: serviceName: task-33333 servicePort: 80 path: /task-33333/* - backend: serviceName: task-44444 servicePort: 80 path: /task-44444/* </code></pre> <p>Any help is greatly appreciated. </p>
<p>[The following has been revised to reflect the update to the question.]</p> <p>Assuming CI_COMMIT_REF_NAME is available to jq as $CI_COMMIT_REF_NAME, which can be done using jq with the command-line argument:</p> <pre><code>--arg CI_COMMIT_REF_NAME "$CI_COMMIT_REF_NAME" </code></pre> <p>an appropriate jq filter would be along the following lines:</p> <pre><code>.spec.rules[0].http.paths |= (map(select(.path | index($CI_COMMIT_REF_NAME) | not)) as $new | if ($new | length) == length then . + [{ "backend": { "serviceName": $CI_COMMIT_REF_NAME, "servicePort": 80}, "path": ($CI_COMMIT_REF_NAME + "/*") }] else $new end ) </code></pre> <p>You can test this with the following jq invocation:</p> <pre><code>jq --arg CI_COMMIT_REF_NAME task-4444 -f program.jq input.json </code></pre> <p>where of course <code>input.json</code> is the JSON version of your YAML.</p> <p>(I'd use <code>index</code> in preference to <code>contains</code> if at all possible.)</p>
<p>I am trying to follow the instructions at <a href="https://docs.docker.com/docker-for-windows/kubernetes/#use-docker-commands" rel="nofollow noreferrer">https://docs.docker.com/docker-for-windows/kubernetes/#use-docker-commands</a> for running a docker-compose.yml file against kubernetes on Docker for Windows.</p> <p>I am using the Edge version of Docker for Windows -- 18.03.0-ce-rc4 -- and I have kubernetes enabled.</p> <p>I am using the example docker-compose app at <a href="https://docs.docker.com/compose/gettingstarted/#step-3-define-services-in-a-compose-file" rel="nofollow noreferrer">https://docs.docker.com/compose/gettingstarted/#step-3-define-services-in-a-compose-file</a>, i.e.</p> <pre><code>version: '3.3' services: web: build: . ports: - '5000:5000' redis: image: redis </code></pre> <p>This example works fine with <code>docker-compose build</code> and <code>docker-compose up</code></p> <p>But following the documentation linked above for <code>docker stack</code>, I get the following:</p> <pre><code>PS C:\dev\projects\python\kubetest&gt; docker stack deploy --compose-file .\docker-compose.yml mystack Ignoring unsupported options: build Stack mystack was created Waiting for the stack to be stable and running... - Service redis has one container running PS C:\dev\projects\python\kubetest&gt; kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 &lt;none&gt; 443/TCP 5d redis ClusterIP None &lt;none&gt; 55555/TCP 8s </code></pre> <p>Note that it doesn't create the web service, along with that "ignoring unsupported options: build" error</p> <p>I also tried using the sample docker-compose.yml file in that documentation linked above, and it didn't work, either, with a totally different error.</p> <p>In short, by following the documentation, I'm unable to get anything deployed to kubernetes on Docker for Windows.</p>
<p>there is a project: </p> <blockquote> <p><a href="https://github.com/kubernetes/kompose" rel="nofollow noreferrer">https://github.com/kubernetes/kompose</a></p> </blockquote> <p>called <strong>Docker Kompose</strong> that helps users who already have docker-compose files to deploy their applications on Kubernetes as easy as possible by automatically converting their existing docker-compose file into many yaml files.</p>
<p>I'm facing docker version conflicts in my cluster. The master is having the version 18.03 but the worker nodes are having 17.03.2-ce. I'm using Jenkins multi pipeline to build the docker images where the latest docker container will be pulled in the slave and it is failing as the node base version is lesser than we expected. PFB</p> <p>Client: Docker Engine - Community Version: 18.09.3 API version: 1.27 (downgraded from 1.39) Go version: go1.10.8</p> <p>Server: Engine: Version: 17.03.2-ce API version: 1.27 (minimum version 1.12)</p> <p>Our build will work for versions higher than 17.05. So I though of updating my cluster by following the link (<a href="https://cloud.google.com/kubernetes-engine/docs/how-to/upgrading-a-cluster" rel="nofollow noreferrer">https://cloud.google.com/kubernetes-engine/docs/how-to/upgrading-a-cluster</a>), but I couldn't find anything specific to docker upgrade in the work nodes.</p> <p>Could you please help me to upgrade the docker version in the work nodes ?</p> <p>Note: Upgrade is required only in the worker nodes and not in the master (as it is having the latest- 18.03)</p>
<p>On GKE the version of docker is tightly coupled with the node image version, which is in turn based on the Kubernetes version of the nodes in your cluster. If you look at the <a href="https://cloud.google.com/kubernetes-engine/docs/release-notes" rel="nofollow noreferrer">GKE Release Notes</a> you can see which Docker versions come installed on which node image versions, and then figure out which node version you need to install to get the desired version of Docker. </p> <p>For example, looking at the <a href="https://cloud.google.com/kubernetes-engine/docs/release-notes#march-05-2019" rel="nofollow noreferrer">release note for March 5th, 2019</a>, <code>cos-69-10895-138-0-c124</code> comes with Docker <code>v18.09.0</code> and is used for Kubernetes nodes running <code>1.12+</code>. So if you upgrade your nodes to Kubernetes 1.12.x <em>and make sure you are using the <code>cos_containerd</code> node image</em> then you will get a Docker version higher that 18.03. </p>
<p>Is it possible to determine the neighbour container or pod IP address, e.g. given its name? More specifically, if I have two running containers/pods C1 (ip=1.2.3.4) and C2 (ip=5.6.7.8) and I execute:</p> <pre><code> ME$ kubectl exec -it C1 bash C1$ magic_command_to_get_ip C2 5.6.7.8 </code></pre> <p>Is there a magic_command_to_get_ip?</p> <p>I am new to Kubernetes and I used to resolve names to addresses in Docker using <code>getent hosts tasks.$SERVICE</code>, but apparently it does not work with KB. </p>
<p>Each pod has a service account mounted to it.</p> <p>You can check that with </p> <pre><code>kubectl decsribe pod pod_name </code></pre> <p><strong>Output:</strong></p> <pre><code>Mounts: /var/run/secrets/kubernetes.io/serviceaccount from xxxxx-token-xxx (ro) </code></pre> <p>The command suggested by Raunak should work if your service account has permission to execute that command.</p> <p>Please make sure the service account you are using has permission to run that command.</p> <p>The error stated in comments <strong>(Forbidden): pods "cassandra-0" is forbidden: User "system:serviceaccount:default:default"</strong> is beacuse of that.</p> <p>More about service accounts <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/" rel="nofollow noreferrer">docs</a></p>
<p>I've installed and configured AWS ALB Ingress Controller(<a href="https://github.com/kubernetes-sigs/aws-alb-ingress-controller" rel="noreferrer">https://github.com/kubernetes-sigs/aws-alb-ingress-controller</a>) and it's working properly over HTTP. However, it doesn't resolve over HTTPS.</p> <p>The Ingress resource is the following:</p> <pre><code>$ kubectl describe ingress api-gateway-ingress Name: api-gateway-ingress Namespace: orbix-mvp Address: 4ae1e4ba-orbixmvp-apigatew-c613-1873743362.eu-central-1.elb.amazonaws.com Default backend: default-http-backend:80 (&lt;none&gt;) TLS: api-gateway.orbixpay.com terminates api-gateway.orbixpay.com,4ae1e4ba-orbixmvp-apigatew-c613-1873743362.eu-central-1.elb.amazonaws.com Rules: Host Path Backends ---- ---- -------- * /* api-gateway:3000 (&lt;none&gt;) Annotations: kubernetes.io/ingress.class: alb alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-2016-08 alb.ingress.kubernetes.io/subnets: subnet-0c4cb5452b630939e, subnet-0e5d3c389bfbefee9 alb.ingress.kubernetes.io/success-codes: 302 kubectl.kubernetes.io/last-applied-configuration: {"apiVersion":"extensions/v1beta1","kind":"Ingress","metadata":{"annotations":{"alb.ingress.kubernetes.io/scheme":"internet-facing","alb.ingress.kubernetes.io/ssl-policy":"ELBSecurityPolicy-2016-08","alb.ingress.kubernetes.io/subnets":"subnet-0c4cb5452b630939e, subnet-0e5d3c389bfbefee9","alb.ingress.kubernetes.io/success-codes":"302","kubernetes.io/ingress.class":"alb"},"labels":{"app":"api-gateway"},"name":"api-gateway-ingress","namespace":"orbix-mvp"},"spec":{"rules":[{"host":"api-gateway.orbixpay.com","http":{"paths":[{"backend":{"serviceName":"api-gateway","servicePort":3000},"path":"/*"}]}}]}} Events: &lt;none&gt; </code></pre> <p>I've also added a self-signed SSL certificate as per the instructions over here:</p> <p><a href="https://kubernetes.github.io/ingress-nginx/user-guide/tls/" rel="noreferrer">https://kubernetes.github.io/ingress-nginx/user-guide/tls/</a></p> <p>On edit the Ingress looks like the following:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-2016-08 alb.ingress.kubernetes.io/subnets: subnet-0c4cb5452b630939e, subnet-0e5d3c389bfbefee9 alb.ingress.kubernetes.io/success-codes: "302" kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"extensions/v1beta1","kind":"Ingress","metadata":{"annotations":{"alb.ingress.kubernetes.io/scheme":"internet-facing","alb.ingress.kubernetes.io/ssl-policy":"ELBSecurityPolicy-2016-08","alb.ingress.kubernetes.io/subnets":"subnet-0c4cb5452b630939e, subnet-0e5d3c389bfbefee9","alb.ingress.kubernetes.io/success-codes":"302","kubernetes.io/ingress.class":"alb"},"labels":{"app":"api-gateway"},"name":"api-gateway-ingress","namespace":"orbix-mvp"},"spec":{"rules":[{"host":"api-gateway.orbixpay.com","http":{"paths":[{"backend":{"serviceName":"api-gateway","servicePort":3000},"path":"/*"}]}}]}} kubernetes.io/ingress.class: alb creationTimestamp: "2019-03-07T14:57:22Z" generation: 8 labels: app: api-gateway name: api-gateway-ingress namespace: orbix-mvp resourceVersion: "2230952" selfLink: /apis/extensions/v1beta1/namespaces/orbix-mvp/ingresses/api-gateway-ingress uid: 4fd70b63-40e9-11e9-bfe7-024a064218ac spec: rules: - http: paths: - backend: serviceName: api-gateway servicePort: 3000 path: /* tls: - hosts: - api-gateway.orbixpay.com - 4ae1e4ba-orbixmvp-apigatew-c613-1873743362.eu-central-1.elb.amazonaws.com secretName: api-gateway.orbixpay.com status: loadBalancer: ingress: - hostname: 4ae1e4ba-orbixmvp-apigatew-c613-1873743362.eu-central-1.elb.amazonaws.com </code></pre> <p>Thing is, the Ingress doesn't resolve over TLS - it just times out. As far as I'm aware this is the correct way to set it up, so I'm rather clueless as to why it's not working. Any help is appreciated.</p>
<p>I think you are mixing up 2 different things here: You want to use ALB Ingress Controller, but you're showing that you're using the configuration for the Nginx Controller. Those are actually 2 pretty different projects. They serve a common purpose but are actually completely different ways to solve it. Nginx is running on your cluster, while ALB Ingress Controller is actually just configuring an ALB which runs on it's own machine(s).</p> <p>The catch is, that ALB cannot use custom certificates. At least not directly from Kubernetes. They need to be put in <a href="https://aws.amazon.com/de/certificate-manager/" rel="noreferrer">ACM</a> first.</p> <p>If you have a certificate in ACM already, ALB Ingress Controller should match it, according to the <a href="https://kubernetes-sigs.github.io/aws-alb-ingress-controller/guide/ingress/annotation/#ssl" rel="noreferrer">documentation</a>.</p> <p>You can also specify which certificate to use for your load balancer like this</p> <pre><code>alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:eu-central-1:1231234564:certificate/4564abc12-d3c2-4455-8c39-45354cddaf03 </code></pre> <p>(replace with the ARN you get from ACM)</p> <p>Some more general tips for debugging this:</p> <ol> <li>Search for the load balancer in the AWS Management Console and check if your listeners have been applied as you expect it. If it looks like you would have configured it, something must be wrong with the logic here already.</li> <li>If they are not applied, probably ALB Ingress Controller got a problem parsing your ingress. Check the logs of the alb-ingress-controller pod in the kube-system namespace to get more details about that.</li> </ol>
<p>I have successfully implemented PodSecurityPolicies(PSP) in my local minikube and am having trouble porting it into GKE. My aim for now is simple --> <strong>Dont Allow pods with UID 0 or with privileged access.</strong></p> <p>My PSP is simple:</p> <pre><code>apiVersion: extensions/v1beta1 kind: PodSecurityPolicy metadata: name: default-psp spec: privileged: false runAsUser: rule: MustRunAsNonRoot </code></pre> <p>And Ive setup RBAC ClusterRoleBinding allowing ALL serviceaccounts to USE the PSP.</p> <pre><code>kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: restrict-root-clusterRole rules: - apiGroups: ['policy'] resources: ['podsecuritypolicies'] verbs: ['use'] resourceNames: - default-psp --- kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: restrict-root-clusterRoleBinding roleRef: kind: ClusterRole name: restrict-root-clusterRole apiGroup: rbac.authorization.k8s.io subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:serviceaccounts </code></pre> <p>Now I enable PSP in GKE using <code>gcloud beta container clusters update psp-demo --enable-pod-security-policy</code></p> <p>And then I notice that GKE create the following PSPs</p> <pre><code>$ k get psp NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMES gce.event-exporter false RunAsAny RunAsAny RunAsAny RunAsAny false hostPath,secret gce.fluentd-gcp false RunAsAny RunAsAny RunAsAny RunAsAny false configMap,hostPath,secret gce.persistent-volume-binder false RunAsAny RunAsAny RunAsAny RunAsAny false nfs,secret gce.privileged true * RunAsAny RunAsAny RunAsAny RunAsAny false * gce.unprivileged-addon false RunAsAny RunAsAny RunAsAny RunAsAny false emptyDir,configMap,secret </code></pre> <p>I then create my PSP and RBAC rules.</p> <pre><code>k get psp NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMES default-psp false RunAsAny MustRunAsNonRoot RunAsAny RunAsAny false * gce.event-exporter false RunAsAny RunAsAny RunAsAny RunAsAny false hostPath,secret gce.fluentd-gcp false RunAsAny RunAsAny RunAsAny RunAsAny false configMap,hostPath,secret gce.persistent-volume-binder false RunAsAny RunAsAny RunAsAny RunAsAny false nfs,secret gce.privileged true * RunAsAny RunAsAny RunAsAny RunAsAny false * gce.unprivileged-addon false RunAsAny RunAsAny RunAsAny RunAsAny false emptyDir,configMap,secret </code></pre> <p>I then spin up a root user pod</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: root-user-pod spec: containers: - name: root-user-pod image: nginx ports: - containerPort: 80 </code></pre> <p>And it goes into Running state and looking at the annotation, I see :</p> <pre><code>apiVersion: v1 kind: Pod metadata: annotations: kubernetes.io/limit-ranger: 'LimitRanger plugin set: cpu request for container root-user-pod' kubernetes.io/psp: gce.privileged </code></pre> <p>So clearly my default PSP is not being used.</p> <p>I tried to edit the <code>gce.privileged</code> PSP but GKE automatically reverts it back to default <code>privileged</code> status.</p> <p>Then what I did was to create a Pod in a particular namespace as a particular ServiceAccouunt. My new RBAC rules are :</p> <pre><code>apiVersion: v1 kind: ServiceAccount metadata: name: test-user namespace: test --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: namespace: test name: test-psp-role rules: - apiGroups: ['policy'] resources: ['podsecuritypolicies'] verbs: ['use'] resourceNames: - default-psp --- kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-psp-roleBinding namespace: test subjects: - kind: ServiceAccount name: test-user namespace: test roleRef: kind: Role name: test-psp-role apiGroup: rbac.authorization.k8s.io </code></pre> <p>And I add <code>serviceAccountName: test-user</code> to my Pod manifest and then deploy the pod in the <code>test</code> namespace and it too going into Running state.</p> <pre><code>k get po -n test NAME READY STATUS RESTARTS AGE root-user-pod 1/1 Running 0 7s </code></pre> <p>With the annotation :</p> <pre><code>apiVersion: v1 kind: Pod metadata: annotations: kubernetes.io/psp: gce.privileged creationTimestamp: "2019-03-12T15:48:11Z" name: root-user-pod namespace: test </code></pre> <p>So im not sure what to do next. How can I over ride the default PSPs that GKE creates ? </p>
<p>TL;DR - The privileged policy is required for running privileged system pods that provide critical cluster functionality. Your user account has access to use all PodSecurityPolicies.</p> <p>Use of a specific PodSecurityPolicy can be authorized in 2 different ways:</p> <ol> <li>The <strong>pod's</strong> service account has the <code>use</code> permission on the specific PodSecurityPolicy.</li> <li>The <strong>creating user</strong> has the <code>use</code> permission on the specific PodSecurityPolicy.</li> </ol> <p>You can test if your user account has access to use the policy with:</p> <pre><code>kubectl auth can-i use podsecuritypolicy/${PSP_NAME} </code></pre> <p>You can test whether the pod's service account has access to a PSP with:</p> <pre><code>kubectl --as=system:serviceaccount:${NAMESPACE:-default}:${SERVICE_ACCOUNT:-default} auth can-i use podsecuritypolicy/${PSP_NAME} </code></pre> <p>If you create the pod through a deployment, replicaset, or some other indirect mechanism, then it is the controller that creates the pod, not the user. In those cases the controller should not have access to any privileged pod security policies, and you should see the behavior you want.</p> <p>Alternatively, make sure the users creating unprivileged pods do not have access to the cluster-admin role binding.</p> <p>There are known issues with this approach, and the Kubernetes community is working on resolving these before PodSecurityPolicy is promoted from beta to general availability.</p>
<p>I am leaning Kubernetes,have applied secrets to my previously running deployments. Now, I have problem that I can not run my site</p> <pre><code>kubectl get ep -o wide NAME ENDPOINTS AGE hello-node 172.17.0.8:8080 2d21h kubernetes 192.168.99.101:8443 3d tomcat-deployment 172.17.0.10:8080,172.17.0.6:8080,172.17.0.7:8080 + 1 more... 2d16h wordpress 24h wordpress-mysql 172.17.0.15:3306 24h </code></pre> <p>Describe output</p> <pre><code>Name: wordpress Namespace: default CreationTimestamp: Tue, 12 Mar 2019 09:10:24 +0100 Labels: app=wordpress Annotations: deployment.kubernetes.io/revision: 1 kubectl.kubernetes.io/last-applied-configuration: {"apiVersion":"apps/v1beta2","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"wordpress"},"name":"wordpress","namespace":... Selector: app=wordpress,tier=frontend Replicas: 1 desired | 1 updated | 1 total | 0 available | 1 unavailable StrategyType: Recreate MinReadySeconds: 0 Pod Template: Labels: app=wordpress tier=frontend Containers: wordpress: Image: wordpress:4.8-apache Port: 80/TCP Host Port: 0/TCP Environment: WORDPRESS_DB_HOST: wordpress-mysql WORDPRESS_DB_PASSWORD: &lt;set to the key 'password' in secret 'mysql-pass'&gt; Optional: false Mounts: /var/www/html from wordpress-persistent-storage (rw) Volumes: wordpress-persistent-storage: Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace) ClaimName: wp-pv-claim ReadOnly: false Conditions: Type Status Reason ---- ------ ------ Progressing True NewReplicaSetAvailable Available False MinimumReplicasUnavailable OldReplicaSets: &lt;none&gt; NewReplicaSet: wordpress-dccb8668f (1/1 replicas created) Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal ScalingReplicaSet 7m37s deployment-controller Scaled up replica set wordpress-dccb8668f to 1 </code></pre> <p>I deleted previous deployment and have created the new one because some problems occur while running secrets cli. I do not understand this, why is end point missing? It also shows that my replica is unavailable,how to fix this? I created deployment with</p> <pre><code>apply -f ./deployment.yaml </code></pre> <p>Pods are running</p> <pre><code>wordpress-dccb8668f-4j6wg 1/1 Running 29 137m wordpress-mysql-7d4fc77fdc-fmhdh 1/1 Running 0 141m </code></pre> <p>get svc -o wide</p> <pre><code>wordpress LoadBalancer 10.102.29.45 &lt;pending&gt; 80:31262/TCP 26h app=wordpress,tier=frontend wordpress-mysql ClusterIP None &lt;none&gt; 3306/TCP 26h app=wordpress,tier=mysql </code></pre> <p>EDIT I changed deployment.yaml as suggested by S.Schenkel</p> <pre><code>apiVersion: v1 kind: Service metadata: name: wordpress labels: app: wordpress spec: ports: - port: 80 selector: app: wordpress tier: frontend type: NodePort </code></pre> <p>I still have the same problem.</p> <pre><code>minikube service wordpress --url http://192.168.99.101:31262 miki@miki:~$ curl http://192.168.99.101:31262 curl: (7) Failed to connect to 192.168.99.101 port 31262: Connection refused miki@miki:~$ </code></pre> <p>If someone wants to reproduce the example</p> <blockquote> <p><a href="https://github.com/LevelUpEducation/kubernetes-demo/tree/master/Advanced%20Kubernetes%20Usage/Secrets" rel="nofollow noreferrer">https://github.com/LevelUpEducation/kubernetes-demo/tree/master/Advanced%20Kubernetes%20Usage/Secrets</a></p> </blockquote> <pre><code>NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR hello-node LoadBalancer 10.104.141.138 &lt;pending&gt; 8080:31321/TCP 3d3h app=hello-node kubernetes ClusterIP 10.96.0.1 &lt;none&gt; 443/TCP 3d6h &lt;none&gt; tomcat-deployment LoadBalancer 10.107.218.19 &lt;pending&gt; 8080:32688/TCP 2d22h app=tomcat wordpress NodePort 10.102.29.45 &lt;none&gt; 80:31262/TCP 30h app=wordpress,tier=frontend wordpress-mysql ClusterIP None &lt;none&gt; 3306/TCP 30h app=wordpress,tier=mysql </code></pre> <p>Pods</p> <pre><code>wordpress-dccb8668f-gk2hn 0/1 CrashLoopBackOff 27 126m 172.17.0.8 minikube &lt;none&gt; &lt;none&gt; wordpress-mysql-7d4fc77fdc-fmhdh 1/1 Running 1 6h23m 172.17.0.19 minikube &lt;none&gt; &lt;none&gt; </code></pre> <p>CrashLoopBackOff means what?</p>
<p>I've just reproduced your case within the minikube and was able to reach the wordpress service</p> <p>Here is step-by-step instruction:</p> <ol> <li>Create a secret for MySQL deployment </li> </ol> <p><code>kubectl create secret generic mysql-pass --from-literal=password=password</code></p> <ol start="2"> <li>Deploy <a href="https://github.com/LevelUpEducation/kubernetes-demo/blob/master/Advanced%20Kubernetes%20Usage/Secrets/mysql-deployment.yaml" rel="nofollow noreferrer">MySQL</a> first. </li> <li>Deploy <a href="https://github.com/LevelUpEducation/kubernetes-demo/blob/master/Advanced%20Kubernetes%20Usage/Secrets/wordpress-deployment.yaml" rel="nofollow noreferrer">wordpress</a> </li> <li>Edit wordpress service type from <code>type: LoadBalancer</code> to <code>type: NodePort</code></li> </ol> <p><code>kubectl edit svc wordpress</code></p> <ol start="4"> <li>Make sure that all pods are running</li> </ol> <p><code>kubectl get pods -o wide</code></p> <ol start="5"> <li>If no issue with pods, try to curl the service</li> </ol> <p><code>curl -v $(minikube service --url wordpress)</code></p> <p>You should have something like this</p> <pre><code>sukhoversha@minikube:~$ curl -v $(minikube service --url wordpress) * Rebuilt URL to: http://192.168.99.100:32144/ * Trying 192.168.99.100... * Connected to 192.168.99.100 (192.168.99.100) port 32144 (#0) &gt; GET / HTTP/1.1 &gt; Host: 192.168.99.100:32144 &gt; User-Agent: curl/7.47.0 &gt; Accept: */* &gt; &lt; HTTP/1.1 302 Found &lt; Date: Tue, 12 Mar 2019 15:26:23 GMT &lt; Server: Apache/2.4.10 (Debian) &lt; X-Powered-By: PHP/5.6.32 &lt; Expires: Wed, 11 Jan 1984 05:00:00 GMT &lt; Cache-Control: no-cache, must-revalidate, max-age=0 &lt; Location: http://192.168.99.100:32144/wp-admin/install.php &lt; Content-Length: 0 &lt; Content-Type: text/html; charset=UTF-8 &lt; * Connection #0 to host 192.168.99.100 left intact </code></pre>
<p>I've searched online and most links seem to mention manifests without actually explaining what they are. What are Manifests?</p>
<p>It's basically a Kubernetes "API object description". A config file can include one or more of these. (i.e. Deployment, ConfigMap, Secret, DaemonSet, etc)</p> <p>As per <a href="https://kubernetes.io/docs/reference/glossary/?all=true#term-manifest" rel="noreferrer">this</a>:</p> <blockquote> <p>Specification of a Kubernetes API object in JSON or YAML format.</p> <p>A manifest specifies the desired state of an object that Kubernetes will maintain when you apply the manifest. Each configuration file can contain multiple manifests.</p> </blockquote> <p>And a previous version of the documentation:</p> <blockquote> <p>Configuration files - Written in YAML or JSON, these files describe the desired state of your application in terms of Kubernetes API objects. A file can include one or more API object descriptions (manifests).</p> </blockquote>
<p>I am currently working on a project where I need to set a bigger number (approx. 20) of environment variables.</p> <p>Now these variable should be shared with multiple containers inside of a pod. I am using a Configmap to define the values. Now my problem is this. I have to set every Environment variable seperately and also have to do this for every container which just is pretty ugly and alot of unnecessary code. Basically it's looking something like this</p> <pre><code>kind: Pod apiVersion: v1 ... containers: - name: container1 image: my-image:latest env: - name: VAR1 valueFrom: configMapKeyRef: name: my-config key: my-var1 ... - name: container2 image: some-other-image:stable env: - name: VAR1 valueFrom: configMapKeyRef: name: my-config key: my-var1 ... </code></pre> <p>What I want is to automatically add all the values from my configMap as and environment variable to the container. My first approach is to mount a configMap as volume and then run a shell script on startup. Similar to this</p> <p><strong>configMap</strong></p> <pre><code>kind: ConfigMap apiVersion: v1 ... data: envCat.sh: | #!/bin/sh export $(grep -v '^#' /etc/pod-config/envVars | xargs) cat envVars MY_VAR1="HELLO WORLD!!" MY_VAR2="I AM HERE" </code></pre> <p><strong>Pod</strong></p> <pre><code>kind: Pod apiVersion: v1 ... spec: volumes: - name: config-volume: configMap: name: my-config containers: - name: container1 image: my-image:latest volumeMounts: - name: config-volume mountPath: /etc/pod-config command: - /etc/pod-config/envCat.sh </code></pre> <p>Unfortunately the export command works just fine when I run it manually in the container but running the shell script or running /bin/sh /etc/pod-config/envCat.sh is not working.</p> <p>Any suggestions to achieve what I want to do?</p>
<p>You should be using envFrom to load all key:value pairs as environment variables inside the container </p>
<p>How does creating, developing on and operating K8s cluster differ -</p> <p>when using <a href="https://gardener.cloud" rel="nofollow noreferrer">Gardener</a>.</p> <p>OR</p> <p>directly creating it in GCP / AWS?</p> <p>I provisioned K8s cluster via Gardner. I now see compute instance created by Gardener (no GKE cluster).</p> <p>Is that the sole difference, at least in the context of a K8s cluster being provisioned?</p>
<blockquote> <p>How does creating, developing on and operating K8s cluster differ -</p> <p>when using Gardener.</p> <p>OR</p> <p>directly creating it in GCP / AWS?</p> </blockquote> <p>They are just different ways of managing your cluster/clusters, in essence, they accomplish something very similar with some differences here an there.</p> <ol> <li><p>Gardener: You have a 'garden' K8s to manage cluster on other cloud providers such as AWS, GCP, Azure, OpenStack. (Running on their server infrastructures like EC2 or GCE)</p> </li> <li><p>GCP / AWS. Here you can create your cluster with other tools like <a href="https://github.com/kubernetes/kops" rel="nofollow noreferrer">kops</a> or <a href="https://kubernetes.io/docs/reference/setup-tools/kubeadm/kubeadm/" rel="nofollow noreferrer">kubeadm</a>. The cluster is created in underlying servers in GCE or EC2 (with autoscaling groups, etc)</p> </li> <li><p>GKE / EKS / AKS. These are managed services specific to each of the cloud providers like Google, Amazon, and Microsoft. If you create a cluster with one of these you will only be able to manage it through the cloud providers specific API/Services. Their underlying infrastructure also happens to be EC2, GCE, Azure, depending on the cloud provider)</p> </li> </ol> <p>One advantage of Gardener appears to be able to create and manage clusters across multiple clouds from a single point.</p>
<p>I've create a private repo on docker hub and trying to pull that image into my kubernetes cluster. I can see the documentations suggest to do this</p> <p><code> kubectl create secret generic regcred \ --from-file=.dockerconfigjson=&lt;path/to/.docker/config.json&gt; \ --type=kubernetes.io/dockerconfigjson </code></p> <p>I am already logged in, and i change path to ~/.docker/config.json but it keeps giving me </p> <p><code>error: error reading ~./docker/config.json: no such file or directory</code> </p> <p>despite the fact if i type <code>cat ~/.docker/config.json</code> it displays the content, meaning there is a file.</p> <p>So in other words how to properly authenticate and be able to push private images into kube cluster?</p>
<blockquote> <pre><code>error: error reading ~./docker/config.json: no such file or directory ^^^^ ? </code></pre> </blockquote> <p><code>~./docker/config.json</code> does not seem valid:<br> <code>~/.docker/config.json</code> would</p> <p>To remove any doubt, try the full path instead of <code>~</code>:</p> <pre><code>kubectl create secret generic regcred \ --from-file=.dockerconfigjson=/home/auser/.docker/config.json \ --type=kubernetes.io/dockerconfigjson </code></pre>
<p>I have a simple replication controller yaml file which looks like this:</p> <pre><code>apiVersion: v1 kind: ReplicationController metadata: name: nginx spec: replicas: 3 selector: app: nginx template: spec: containers: - image: library/nginx:3.2 imagePullPolicy: IfNotPresent name: nginx ports: - containerPort: 80 metadata: labels: app: nginx </code></pre> <p>And after running this replication controller, I will get 3 different pods whose names are "nginx-xxx", where "xxx" represents a random string of letters and digits.</p> <p>What I want is to specify names for the pods created by the replication controller, so that the pods' name can be "nginx-01", "nginx-02", "nginx-03". And further more, for say if pod "nginx-02" is down for some reason, and replication controller will automatically create another nginx pod, and I want this new nginx pod's name to remain as "nginx-02".</p> <p>I wonder if this is possible? Thanks in advance.</p>
<p>You should be using statefulset instead of replication controllers. Moreover, replication controllers are replaced with ReplicaSets. </p> <p>StatefulSet Pods have a unique identity that is comprised of an ordinal. For a StatefulSet with N replicas, each Pod in the StatefulSet will be assigned an integer ordinal, from 0 up through N-1, that is unique over the Set. Each Pod in a StatefulSet derives its hostname from the name of the StatefulSet and the ordinal of the Pod.</p> <p>StatefulSets matches your requirements and hence use it in your deployment.</p> <p>Try the deployment files below:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: nginx labels: app: nginx spec: ports: - port: 80 name: web clusterIP: None selector: app: nginx --- apiVersion: apps/v1 kind: StatefulSet metadata: name: web spec: selector: matchLabels: app: nginx # has to match .spec.template.metadata.labels serviceName: "nginx" replicas: 3 # by default is 1 template: metadata: labels: app: nginx # has to match .spec.selector.matchLabels spec: terminationGracePeriodSeconds: 10 containers: - name: nginx image: k8s.gcr.io/nginx-slim:0.8 ports: - containerPort: 80 name: web volumeMounts: - name: www mountPath: /usr/share/nginx/html volumes: - name: www emptyDir: </code></pre>
<p>Im trying to create prometheus with operator in fresh new k8s cluster I use the following files , </p> <ol> <li>First step I’m creating a namespace monitoring </li> <li>apply this file , which works ok</li> </ol> <pre><code> apiVersion: apps/v1beta2 kind: Deployment metadata: labels: k8s-app: prometheus-operator name: prometheus-operator namespace: monitoring spec: replicas: 2 selector: matchLabels: k8s-app: prometheus-operator template: metadata: labels: k8s-app: prometheus-operator spec: priorityClassName: "operator-critical" tolerations: - key: "WorkGroup" operator: "Equal" value: "operator" effect: "NoSchedule" - key: "WorkGroup" operator: "Equal" value: "operator" effect: "NoExecute" containers: - args: - --kubelet-service=kube-system/kubelet - --logtostderr=true - --config-reloader-image=quay.io/coreos/configmap-reload:v0.0.1 - --prometheus-config-reloader=quay.io/coreos/prometheus-config-reloader:v0.29.0 image: quay.io/coreos/prometheus-operator:v0.29.0 name: prometheus-operator ports: - containerPort: 8080 name: http securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true nodeSelector: serviceAccountName: prometheus-operator </code></pre> <p>Now I want to apply this file (CRD)</p> <pre><code>apiVersion: monitoring.coreos.com/v1 kind: Prometheus metadata: name: prometheus namespace: monitoring labels: prometheus: prometheus spec: replica: 1 priorityClassName: "operator-critical" serviceAccountName: prometheus nodeSelector: worker.garden.sapcloud.io/group: operator serviceMonitorNamespaceSelector: {} serviceMonitorSelector: matchLabels: role: observeable tolerations: - key: "WorkGroup" operator: "Equal" value: "operator" effect: "NoSchedule" - key: "WorkGroup" operator: "Equal" value: "operator" effect: "NoExecute" </code></pre> <p>And Im getting error :</p> <p><code>error: unable to recognize "1500-prometheus-crd.yaml": no matches for kind "Prometheus" in version "monitoring.coreos.com/v1"</code></p> <p>I found this <a href="https://github.com/coreos/prometheus-operator/issues/1866" rel="nofollow noreferrer">https://github.com/coreos/prometheus-operator/issues/1866</a> , but I try to do it as mentioned, I.e. Wait a few second and deploy again but it doesn’t help. Any idea ? </p> <p>Also tried to delete the ns and create it again with the configs and I got the same issue. please advice</p>
<p>You need to install the <a href="https://github.com/coreos/prometheus-operator/tree/master/example/prometheus-operator-crd" rel="nofollow noreferrer">custom resources</a> as available objects in Kubernetes before you can create instances of them. </p>
<p>I am trying to log into a kubernetes pod using the kubectl exec command. I am successful but it logs me in as the root user. I have created some other users too as part of the system build. </p> <p>Command being used is "kubectl exec -it /bin/bash". I guess this means that run /bin/bash on the pod which results into a shell entry into the container.</p> <p>Can someone please guide me on the following -</p> <ol> <li>How to logon using a non-root user?</li> <li>Is there a way to disable root user login?</li> <li>How can I bind our organization's ldap into the container?</li> </ol> <p>Please let me know if more information is needed from my end to answer this?</p> <p>Thanks,</p> <p>Anurag</p>
<p>You can use <code>su - &lt;USERNAME&gt;</code> to login as a non-root user.</p> <p>Run <code>cat /etc/passwd</code> to get a list of all available users then identify a user with a valid shell compiler e.g</p> <p><code>/bin/bash</code> or <code>/bin/sh</code></p> <p>Users with <code>/bin/nologin</code> and <code>/bin/false</code> as the set compiler are used by system processes and as such you can't log in as them.</p>
<p>I tried to create an EKS Kubernetes cluster, for example using this: <a href="https://github.com/terraform-providers/terraform-provider-aws/tree/master/examples/eks-getting-started" rel="nofollow noreferrer">https://github.com/terraform-providers/terraform-provider-aws/tree/master/examples/eks-getting-started</a></p> <p>What I get is all pods are pending:</p> <blockquote> <p>No nodes available to schedule pods</p> </blockquote> <p>in <code>kubectl po describe</code> and I get an empty list when I type <code>kubectl get nodes</code>.</p> <p>Changing AMI images or AWS region doesn't help. </p> <p>What's wrong?</p>
<p>I was still having issue with the code where the worker nodes register only if eks was set to public subnets only.</p> <p><code>module "eks" { subnets = ["${module.vpc.public_subnets}"] }</code></p> <p>I did not want my workers to be in public subnets. I changed </p> <pre><code>module "eks" { subnets = ["${module.vpc.private_subnets}"] } module "vpc" { single_nat_gateway = false } </code></pre> <p>kubectl get nodes</p> <pre><code>NAME STATUS ROLES AGE VERSION ip-10-0-1-247.us-east-2.compute.internal Ready &lt;none&gt; 17m v1.11.5 ip-10-0-1-75.us-east-2.compute.internal Ready &lt;none&gt; 17m v1.11.5 ip-10-0-2-225.us-east-2.compute.internal Ready &lt;none&gt; 17m v1.11.5 ip-10-0-3-210.us-east-2.compute.internal Ready &lt;none&gt; 17m v1.11.5 </code></pre>
<p>We are planning to setup Highly Available Jenkins setup in container platform using kubernetes. We are looking at setting up one Active master and another master in standby mode. Jenkins data volume is going to be stored in a global storage that is shared between the two master containers.</p> <p>In case the active master is not available then requests should fail over to other master. And the slaves should be communicating only with active master.</p> <p>How do we accomplish Jenkins HA setup in active/passive mode in kubernetes. please provide your suggestions.</p> <p>We would like to achieve as shown in the diagram from below link</p> <p><a href="https://endocode.com/img/blog/jenkins-ha-setup_concept.png" rel="nofollow noreferrer">https://endocode.com/img/blog/jenkins-ha-setup_concept.png</a></p>
<p>This contradicts with how one should IMHO run applications in Kubernetes. Active/passive is a concept for the past century.</p> <p>Instead, configure a health check for the Jenkins Deployment. If that fails, Kubernetes will automatically kill the task and start a replacement (which will be available only a few seconds after detecting the active one being unhealthy).</p>
<p>I'm using minikube with <code>hyperkit</code> driver, and I need to access a port opened on the host machine FROM a pod inside the minikube cluster.</p> <p>There are 2 ways I can accomplish this:</p> <h2>Port forwarding</h2> <p>Port forward of my local port to the <code>minikube ip</code>:</p> <pre><code>ssh -i $(minikube ssh-key) docker@$(minikube ip) -R 8080:localhost:8080 </code></pre> <p>And then from the pod I can <code>curl 172.17.0.1:8080</code></p> <blockquote> <p>source: <a href="https://medium.com/tarkalabs/proxying-services-into-minikube-8355db0065fd" rel="nofollow noreferrer">https://medium.com/tarkalabs/proxying-services-into-minikube-8355db0065fd</a></p> </blockquote> <h2>Local machine's IP</h2> <p>From my host machine, I get the minikube's bridge IP: <code>ifconfig bridge100</code> </p> <pre><code>bridge100: flags=8863&lt;UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST&gt; mtu 1500 options=3&lt;RXCSUM,TXCSUM&gt; ether 8e:85:90:2d:d5:64 inet 192.168.64.1 netmask 0xffffff00 broadcast 192.168.64.255 </code></pre> <p>And then from the pod I can <code>curl 192.168.64.1:8080</code></p> <p>However, I'm not sure both methods are the right way. Is there a way to statically reference the host machine to be able to access open ports. What's the solution here?</p>
<p>There are too many layers of indirection involved here and you’ll have to inject the physical host’s IP address into the container as an environment variable or ConfigMap setting. An ExternalName type Service could also work here.</p> <p>The essential problem here is that each layer can find out about the layer immediately beyond it, but no further. You have a host running a VM running a Kubernetes Pod. The Pod can use the <a href="https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/" rel="nofollow noreferrer">downward API</a> to find its Node’s IP address, but in your case that will be the VM and not the host around it.</p> <p>(As a parallel question: you have an ordinary home router that’s 192.168.1.1, and your local system is 192.168.1.2. You’re running some server on the router. Meanwhile, you have a VM running on your local system, which sees the host as 172.17.0.1 and believes it is 172.17.0.2. How does the VM reach the service on the router, if it doesn’t know about the 192.168.1.0/24 network in its local network environment?)</p>
<p>I have a scenario where I need to push application logs running on EKS Cluster to separate cloudwatch log streams. I have followed the below link, which pushes all logs to cloudwatch using fluentd. But the issue is, it pushes logs to a single log stream only.</p> <blockquote> <p><a href="https://github.com/aws-samples/aws-workshop-for-kubernetes" rel="nofollow noreferrer">https://github.com/aws-samples/aws-workshop-for-kubernetes</a></p> </blockquote> <p>It also pushes all the logs under <code>/var/lib/docker/container/*.log</code>. How Can I filter this to can only application specific logs?</p>
<p><a href="https://collectord.io" rel="nofollow noreferrer">Collectord</a> now supports AWS CloudWatch Logs (and S3/Athena/Glue). It gives you flexibility to choose to what LogGroup and LogStream you want to forward the data (if the default does work for you).</p> <ul> <li><a href="https://collectord.io/docs/cloudwatch/kubernetes/installation/" rel="nofollow noreferrer">Installation instructions for CloudWatch</a></li> <li><a href="https://collectord.io/docs/cloudwatch/kubernetes/annotations/#override-loggroup-and-logstream" rel="nofollow noreferrer">How you can specify LogGroup and LogStream with annotations</a></li> </ul> <p>Highly recommend to read <a href="https://collectord.io/blog/2019-03-13-aws-centralized-logging-for-kubernetes/" rel="nofollow noreferrer">Setting up comprehensive centralized logging with AWS Services for Kubernetes</a></p>
<p>As a part of debug i need to track down events like pod creation and removal. in my kubernetes set up I am using logging level 5.</p> <p>Kube api server, scheduler, controller, etcd are running on master node and the minion nodes is running kubelet and docker. </p> <p>I am using <code>journalctl</code> to get K8s logs on master node as well on worker node. On worker node i can see logs from Docker and Kubelet. These logs contain events as i would expect as i create and destroy pods.</p> <p>However on Master node i dont see any relevant logs which may indicate a pod creation or removal request handling. </p> <p><strong>what other logs or method i can use to get such logs from Kubernetes master components (API server, controller, scheduler, etcd)?</strong></p> <p>i have checked the logs from API server, controller, scheduler, etcd pods; they dont seem to have such information.</p> <p>thanks</p>
<p><strong>System component logs:</strong></p> <p>There are two types of system components: </p> <ul> <li><p>those that run in a container </p></li> <li><p>and those that do not run in a container. </p></li> </ul> <p>For example:</p> <p>The Kubernetes scheduler and kube-proxy run in a container</p> <p>The kubelet and container runtime, for example Docker, do not run in containers.</p> <p>On machines with systemd, the kubelet and container runtime write to journald. If systemd is not present, they write to .log files in the /var/log directory. System components inside containers always write to the /var/log directory, bypassing the default logging mechanism. They use the klog logging library.</p> <p><strong>Master components logs:</strong></p> <p>Get them from those containers running on master nodes.</p> <pre><code>$ $ docker ps | grep apiserver d6af65a248f1 af20925d51a3 "kube-apiserver --ad…" 2 weeks ago Up 2 weeks k8s_kube-apiserver_kube-apiserver-minikube_kube-system_177a3eb80503eddadcdf8ec0423d04b9_0 5f0e6b33a29f k8s.gcr.io/pause-amd64:3.1 "/pause" 2 weeks ago Up 2 weeks k8s_POD_kube-apiserver-minikube_kube-system_177a3eb80503eddadcdf8ec0423d04b9_0 $ $ $ docker logs -f d6a </code></pre> <p>But all of this approach to logging is just for testing , you should stream all the logs , ( app logs , container logs , cluster level logs , everything) to a centeral logging system such as ELK or EFK.</p>
<p>I am just wondering if anyone has figured out a declarative way to have helm charts installed/configured as part of a cluster initiation and that could be checked into source control. Using Kuberenetes I have very much gotten used to the "everything as code" type of workflow and I realize that installing and configuring helm is based mostly on imperative workflows via the CLI.</p> <p>The reason I am asking is because currently we have our cluster in development and will be recreating it in production. Most of our configuration has been done declaratively via the deployment.yaml file. However we have spent a significant amount of time installing and configuring certain helm charts (e.g. prometheus, grafana etc.)</p>
<p>There a tools like <a href="https://github.com/roboll/helmfile" rel="nofollow noreferrer">helmfile</a> or <a href="https://github.com/Praqma/helmsman" rel="nofollow noreferrer">helmsman</a> which allow you to declare to be installed Helm releases as code. </p> <p>Here is an example from a <code>helmfile.yaml</code> doing so:</p> <pre><code>releases: # Published chart example - name: promnorbacxubuntu # name of this release namespace: prometheus # target namespace chart: stable/prometheus # the chart being installed to create this release, referenced by `repository/chart` syntax set: # values (--set) - name: rbac.create value: false </code></pre> <p>Running <code>helmfile charts</code> will then ensure that all listed releases are installed</p>
<p>I was trying <code>elasticsearch</code> deployment on Kubernetes (EKS) cluster with persistence volume (EBS), refering to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html" rel="nofollow noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html</a></p> <pre><code>apiVersion: extensions/v1beta1 kind: Deployment metadata: name: elasticsearch spec: replicas: 1 template: metadata: labels: run: elasticsearch spec: initContainers: - name: init-sysctl image: busybox imagePullPolicy: IfNotPresent command: ["sysctl", "-w", "vm.max_map_count=262144"] securityContext: privileged: true containers: - name: elasticsearch image: elasticsearch:6.6.1 imagePullPolicy: IfNotPresent securityContext: privileged: true capabilities: add: - IPC_LOCK ports: - containerPort: 9300 protocol: TCP resources: limits: cpu: 1 env: - name: CLUSTER_NAME value: elasticsearch - name: ES_JAVA_OPTS value: "-Xms256m -Xmx512m" volumeMounts: - name: elasticsearch-storage mountPath: /usr/share/elasticsearch/data volumes: - name: elasticsearch-storage persistentVolumeClaim: claimName: elasticsearch </code></pre> <p>But pod failed with </p> <pre><code>OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release. [2019-03-13T18:03:08,459][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [unknown] uncaught exception in thread [main] org.elasticsearch.bootstrap.StartupException: java.lang.IllegalStateException: Failed to create node environment at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:163) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:150) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:124) ~[elasticsearch-cli-6.6.1.jar:6.6.1] at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-cli-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:116) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:93) ~[elasticsearch-6.6.1.jar:6.6.1] Caused by: java.lang.IllegalStateException: Failed to create node environment at org.elasticsearch.node.Node.&lt;init&gt;(Node.java:298) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.node.Node.&lt;init&gt;(Node.java:265) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Bootstrap$5.&lt;init&gt;(Bootstrap.java:212) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:212) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:333) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:159) ~[elasticsearch-6.6.1.jar:6.6.1] ... 6 more Caused by: java.nio.file.AccessDeniedException: /usr/share/elasticsearch/data/nodes at sun.nio.fs.UnixException.translateToIOException(UnixException.java:90) ~[?:?] at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111) ~[?:?] at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116) ~[?:?] at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:385) ~[?:?] at java.nio.file.Files.createDirectory(Files.java:689) ~[?:?] at java.nio.file.Files.createAndCheckIsDirectory(Files.java:796) ~[?:?] at java.nio.file.Files.createDirectories(Files.java:782) ~[?:?] at org.elasticsearch.env.NodeEnvironment.lambda$new$0(NodeEnvironment.java:270) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.env.NodeEnvironment$NodeLock.&lt;init&gt;(NodeEnvironment.java:203) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.env.NodeEnvironment.&lt;init&gt;(NodeEnvironment.java:267) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.node.Node.&lt;init&gt;(Node.java:295) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.node.Node.&lt;init&gt;(Node.java:265) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Bootstrap$5.&lt;init&gt;(Bootstrap.java:212) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:212) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:333) ~[elasticsearch-6.6.1.jar:6.6.1] at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:159) ~[elasticsearch-6.6.1.jar:6.6.1] ... 6 more </code></pre> <p>From this <a href="https://discuss.elastic.co/t/elastic-elasticsearch-docker-not-assigning-permissions-to-data-directory-on-run/65812/2" rel="nofollow noreferrer">discussion</a>, it looks like permission issue on <code>/usr/share/elasticsearch/data</code> dir. </p> <p>following <code>initContainers</code> helped to get me around this issue. </p> <pre><code>initContainers: - name: init-sysctl image: busybox imagePullPolicy: IfNotPresent #command: ["sysctl", "-w", "vm.max_map_count=262144"] command: ["/bin/sh","-c"] args: ["sysctl -w vm.max_map_count=262144; chown -R 1000:1000 /usr/share/elasticsearch/data"] securityContext: privileged: true volumeMounts: - name: elasticsearch-storage mountPath: /usr/share/elasticsearch/data </code></pre> <p>Whats is correct way to fix this issue ?</p>
<p>The solution you are using is a workaround , but you can do it a bit kubernetes way is explained here:</p> <p><a href="https://stackoverflow.com/questions/46351051/permission-denied-when-chown-on-elasticsearch-data-directory-in-kubernetes-state">Permission denied when chown on elasticsearch data directory in kubernetes statefulset</a></p> <p>So in your case it should be like:</p> <pre><code>.... spec: ... securityContext: fsGroup: 1000 </code></pre>
<p>I have a service (CusterIP) like following which is exposing ports of backend POD.</p> <pre><code>apiVersion: v1 kind: Service metadata: name: fsimulator namespace: myns spec: type: ClusterIP selector: application: oms ports: - name: s-port port: 9780 - name: b-port port: 8780 </code></pre> <p>Front end POD should be able to connect to Backend POD using service. Should we replace hostname with service name to connect from Frontend POD to Backend POD ?</p> <p>I have to supply the service name and port through environment variables to Frontend POD container. The enviroment variables are set using configMap.</p> <p>Is it enough to give service name fsimulator as hostname to connect to ? How to give service if is created inside namespace ? </p> <p>Thanks </p>
<p>Check out <a href="https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services" rel="nofollow noreferrer">this documentation</a>. The internal service PORT / IP pairs for active services are indeed passed into the containers <em>by default</em>.</p> <p>As the documentation also says, it is possible (recommended) to use a DNS cluster add-on for service discovery. Accessing <code>service.namespace</code> from outside / inside a service will resolve to the correct service route (or just <code>service</code> from inside the namespace). This is usually the right path to take.</p> <p>Built-in service discovery is a huge perk of using Kubernetes, use the available tools if at all possible!</p>
<p>Using Airflow to run the KubernetesPodOperator on AWS EKS getting kubernetes.client.rest.ApiException: (400), states that Pod in version \"v1\" cannot be handled as a Pod: v1.Pod.Spec. Is aws-eks not supporting this type of pod creation?</p> <p>Here is the full log</p> <pre><code>[2019-03-13 01:13:47,991] {models.py:1593} INFO - Executing &lt;Task(KubernetesPodOperator): failing-task&gt; on 2019-03- 13T01:12:33.980710+00:00 [2019-03-13 01:13:47,991] {base_task_runner.py:118} INFO - Running: ['bash', '-c', 'airflow run testkuberete2 failing-task 2019-03- 13T01:12:33.980710+00:00 --job_id 20 --raw -sd DAGS_FOLDER/test- kubepodopptest5.py --cfg_path /tmp/tmpmwb4uzk0'] [2019-03-13 01:13:48,415] {base_task_runner.py:101} INFO - Job 20: Subtask failing-task [2019-03-13 01:13:48,415] {settings.py:174} INFO - settings.configure_orm(): Using pool settings. pool_size=5, pool_recycle=3600, pid=408 [2019-03-13 01:13:48,864] {base_task_runner.py:101} INFO - Job 20: Subtask failing-task [2019-03-13 01:13:48,863] {__init__.py:51} INFO - Using executor CeleryExecutor [2019-03-13 01:13:49,115] {base_task_runner.py:101} INFO - Job 20: Subtask failing-task [2019-03-13 01:13:49,114] {models.py:273} INFO - Filling up the DagBag from /usr/local/airflow/dags/test- kubepodopptest5.py [2019-03-13 01:13:49,473] {base_task_runner.py:101} INFO - Job 20: Subtask failing-task [2019-03-13 01:13:49,473] {cli.py:520} INFO - Running &lt;TaskInstance: testkuberete2.failing-task 2019-03- 13T01:12:33.980710+00:00 [running]&gt; on host airflow-worker-1.airflow- worker.rguonew.svc.cluster.local </code></pre> <p>I wrote some custom log to inspect what got send to the EKS:</p> <pre><code>[2019-03-13 01:13:49,782] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,781] {api_client.py:117} ERROR - header_params {Accept application/json} [2019-03-13 01:13:49,782] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,782] {api_client.py:117} ERROR - header_params {Content-Type application/json} [2019-03-13 01:13:49,782] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,782] {api_client.py:117} ERROR - header_params {User-Agent Swagger-Codegen/8.0.1/python} [2019-03-13 01:13:49,782] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,782] {api_client.py:128} ERROR - resource_path {namespace rguonew} [2019-03-13 01:13:49,782] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,782] {api_client.py:151} ERROR - body {{'apiVersion': 'v1', 'kind': 'Pod', 'metadata': {'name': 'fail-422f98fc', 'labels': {}, 'annotations': {}}, 'spec': {'containers': [{'name': 'base', 'image': 'python:3.6.6-stretch', 'command': 'echo', 'imagePullPolicy': 'IfNotPresent', 'args': '10'}], 'restartPolicy': 'Never', 'nodeSelector': {}, 'volumes': [], 'serviceAccountName': 'default', 'affinity': {}}}} [2019-03-13 01:13:49,782] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,782] {api_client.py:155} ERROR - url {https://xxxxxxxxxxxx.xxxx.us-east- 1.eks.amazonaws.com/api/v1/namespaces/rguonew/pods} [2019-03-13 01:13:49,838] {logging_mixin.py:95} INFO - [2019-03-13 01:13:49,823] {pod_launcher.py:58} ERROR - Exception when attempting to create Namespaced Pod. </code></pre> <blockquote> <p>Traceback</p> </blockquote> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python3.6/site- packages/airflow/contrib/kubernetes/pod_launcher.py", line 55, in run_pod_async resp = self._client.create_namespaced_pod(body=req, namespace=pod.namespace) File "/usr/local/lib/python3.6/site- packages/kubernetes/client/apis/core_v1_api.py", line 6115, in create_namespaced_pod (data) = self.create_namespaced_pod_with_http_info(namespace, body, **kwargs) File "/usr/local/lib/python3.6/site- packages/kubernetes/client/apis/core_v1_api.py", line 6206, in create_namespaced_pod_with_http_info collection_formats=collection_formats) File "/usr/local/lib/python3.6/site- packages/kubernetes/client/api_client.py", line 329, in call_api _return_http_data_only, collection_formats, _preload_content, _request_timeout) File "/usr/local/lib/python3.6/site-packages/kubernetes/client/ap i_client.py", line 163, in __call_api _request_timeout=_request_timeout) File "/usr/local/lib/python3.6/site- packages/kubernetes/client/api_client.py", line 372, in request body=body) File "/usr/local/lib/python3.6/site- packages/kubernetes/client/rest.py", line 266, in POST body=body) File "/usr/local/lib/python3.6/site- packages/kubernetes/client/rest.py", line 222, in request raise ApiException(http_resp=r) kubernetes.client.rest.ApiException: (400) Reason: Bad Request </code></pre> <p><strong>The Response:</strong></p> <pre><code>HTTP response headers: HTTPHeaderDict({'Audit-Id': '96f8ffee-3e65-47a7- bb3c-fe519281ee45', 'Content-Type': 'application/json', 'Date': 'Wed, 13 Mar 2019 01:13:49 GMT', 'Content-Length': '491'}) HTTP response body: {"kind":"Status","apiVersion":"v1","metadata": {},"status":"Failure","message":"Pod in version \"v1\" cannot be handled as a Pod: v1.Pod.Spec: v1.PodSpec.Containers: []v1.Container: v1.Container.Command: []string: decode slice: expect [ or n, but found \", error found in #10 byte of ...|ommand\": \"echo\", \"im|..., bigger context ...|se\", \"image\": \"python:3.6.6-stretch\", \"command\": \"echo\", \"imagePullPolicy\": \"IfNotPresent\", \"args\": |...","reason":"BadRequest","code":400} [2019-03-13 01:13:49,838] {logging_mixin.py:95} INFO - </code></pre>
<p>Ah, great to find another using Airflow on EKS!! </p> <p>I am also running a similar Airflow workload and can confirm that KubernetesPodOperator is supported with AWS EKS. </p> <p>Looking at the response, I think perhaps the API call to create the pod either got mangled or your python code included incorrect argument types when instantiating the KubernetesPodOperator.</p> <p>I decoded your pod definition (correct me if wrong):</p> <pre><code>--- apiVersion: v1 kind: Pod metadata: name: fail-422f98fc labels: {} annotations: {} spec: containers: - name: base image: python:3.6.6-stretch command: echo imagePullPolicy: IfNotPresent args: '10' restartPolicy: Never nodeSelector: {} volumes: [] serviceAccountName: default affinity: {} </code></pre> <p>Your should wrap your "command" and "args" in square brackets as below:</p> <pre><code>--- apiVersion: v1 kind: Pod metadata: name: fail-422f98fc labels: {} annotations: {} spec: containers: - name: base image: python:3.6.6-stretch command: ['echo'] imagePullPolicy: IfNotPresent args: ['10'] restartPolicy: Never nodeSelector: {} volumes: [] serviceAccountName: default affinity: {} </code></pre> <p>Hope this helps!</p>
<p>If I has an admission webhook that denies all deleting requests of secrets. So when i delete a project, what happen to the secrets in that namespace, will they be deleted anyway?</p>
<p><a href="https://docs.openshift.com/container-platform/3.11/architecture/additional_concepts/dynamic_admission_controllers.html" rel="nofollow noreferrer">This figure</a> shows where admission controller works.</p> <p>Note that:</p> <ol> <li>By default, the only way to delete k8s resources (ex: secret) is to access k8s api.</li> <li>Admission controller applies to each api call that passes A/A check.</li> </ol> <p>So, secrets will not be deleted. </p>
<p>At <a href="https://docs.cert-manager.io/en/latest/tutorials/acme/quick-start/index.html#" rel="nofollow noreferrer">step 3</a> I got the IP address as follow. And I customized my DNS according to this <a href="https://medium.com/@ayyazzafar/how-to-install-letsencrypt-ssl-certificate-using-cert-manager-on-google-kubernetes-engine-gke-4553889688bc" rel="nofollow noreferrer">article</a></p> <pre class="lang-sh prettyprint-override"><code>$ kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.51.240.1 &lt;none&gt; 443/TCP 10d quickstart-nginx-ingress-controller LoadBalancer 10.51.251.156 35.247.160.2 80:30686/TCP,443:32595/TCP 87s quickstart-nginx-ingress-default-backend ClusterIP 10.51.253.66 &lt;none&gt; 80/TCP 86s </code></pre> <blockquote> <p>The external IP that is allocated to the ingress-controller is the IP to which all incoming traffic should be routed. To enable this, add it to a DNS zone you control, for example as example.your-domain.com.</p> <p>This quickstart assumes you know how to assign a DNS entry to an IP address and will do so.</p> </blockquote> <p><code>DNS zone</code> <a href="https://i.stack.imgur.com/nHzXv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nHzXv.png" alt="enter image description here" /></a></p> <p><code>domains.google.com</code> <a href="https://i.stack.imgur.com/9Xt7I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Xt7I.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/PDpOR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PDpOR.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/SEZxV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SEZxV.png" alt="enter image description here" /></a></p> <p>I can <code>$ curl -kivL -H 'Host: singh.hbot.dev' 'http://singh.hbot.dev'</code> Here is the output of <code>kuard</code></p> <pre class="lang-sh prettyprint-override"><code>* Rebuilt URL to: http://singh.hbot.dev/ * Trying 35.247.160.2... * TCP_NODELAY set * Connected to singh.hbot.dev (35.247.160.2) port 80 (#0) &gt; GET / HTTP/1.1 &gt; Host: singh.hbot.dev &gt; User-Agent: curl/7.54.0 &gt; Accept: */* &gt; &lt; HTTP/1.1 308 Permanent Redirect HTTP/1.1 308 Permanent Redirect &lt; Server: nginx/1.15.8 Server: nginx/1.15.8 &lt; Date: Thu, 14 Mar 2019 08:59:24 GMT Date: Thu, 14 Mar 2019 08:59:24 GMT &lt; Content-Type: text/html Content-Type: text/html &lt; Content-Length: 171 Content-Length: 171 &lt; Connection: keep-alive Connection: keep-alive &lt; Location: https://singh.hbot.dev/ Location: https://singh.hbot.dev/ &lt; * Ignoring the response-body * Connection #0 to host singh.hbot.dev left intact * Issue another request to this URL: 'https://singh.hbot.dev/' * Trying 35.247.160.2... * TCP_NODELAY set * Connected to singh.hbot.dev (35.247.160.2) port 443 (#1) * ALPN, offering h2 * ALPN, offering http/1.1 * Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH * successfully set certificate verify locations: * CAfile: /etc/ssl/cert.pem CApath: none * TLSv1.2 (OUT), TLS handshake, Client hello (1): * TLSv1.2 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Client hello (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS change cipher, Client hello (1): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384 * ALPN, server accepted to use h2 * Server certificate: * subject: O=Acme Co; CN=Kubernetes Ingress Controller Fake Certificate * start date: Mar 14 08:22:58 2019 GMT * expire date: Mar 13 08:22:58 2020 GMT * issuer: O=Acme Co; CN=Kubernetes Ingress Controller Fake Certificate * SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway. * Using HTTP2, server supports multi-use * Connection state changed (HTTP/2 confirmed) * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * Using Stream ID: 1 (easy handle 0x7fdf3000e200) &gt; GET / HTTP/2 &gt; Host: singh.hbot.dev &gt; User-Agent: curl/7.54.0 &gt; Accept: */* &gt; * Connection state changed (MAX_CONCURRENT_STREAMS updated)! &lt; HTTP/2 200 HTTP/2 200 &lt; server: nginx/1.15.8 server: nginx/1.15.8 &lt; date: Thu, 14 Mar 2019 08:59:24 GMT date: Thu, 14 Mar 2019 08:59:24 GMT &lt; content-type: text/html content-type: text/html &lt; content-length: 1689 content-length: 1689 &lt; vary: Accept-Encoding vary: Accept-Encoding &lt; strict-transport-security: max-age=15724800; includeSubDomains strict-transport-security: max-age=15724800; includeSubDomains &lt; &lt;!doctype html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;title&gt;KUAR Demo&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;/static/css/bootstrap.min.css&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;/static/css/styles.css&quot;&gt; &lt;script&gt; var pageContext = {&quot;hostname&quot;:&quot;kuard-79b5d46779-5slz8&quot;,&quot;addrs&quot;:[&quot;10.48.2.20&quot;],&quot;version&quot;:&quot;v0.8.1-1&quot;,&quot;versionColor&quot;:&quot;hsl(18,100%,50%)&quot;,&quot;requestDump&quot;:&quot;GET / HTTP/1.1\r\nHost: singh.hbot.dev\r\nAccept: */*\r\nUser-Agent: curl/7.54.0\r\nX-Forwarded-For: 10.148.0.49\r\nX-Forwarded-Host: singh.hbot.dev\r\nX-Forwarded-Port: 443\r\nX-Forwarded-Proto: https\r\nX-Original-Uri: /\r\nX-Real-Ip: 10.148.0.49\r\nX-Request-Id: ba73c8e44498c36480ea0d4164279561\r\nX-Scheme: https&quot;,&quot;requestProto&quot;:&quot;HTTP/1.1&quot;,&quot;requestAddr&quot;:&quot;10.48.2.18:41748&quot;} &lt;/script&gt; &lt;/head&gt; &lt;svg style=&quot;position: absolute; width: 0; height: 0; overflow: hidden;&quot; version=&quot;1.1&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt; &lt;defs&gt; &lt;symbol id=&quot;icon-power&quot; viewBox=&quot;0 0 32 32&quot;&gt; &lt;title&gt;power&lt;/title&gt; &lt;path class=&quot;path1&quot; d=&quot;M12 0l-12 16h12l-8 16 28-20h-16l12-12z&quot;&gt;&lt;/path&gt; &lt;/symbol&gt; &lt;symbol id=&quot;icon-notification&quot; viewBox=&quot;0 0 32 32&quot;&gt; &lt;title&gt;notification&lt;/title&gt; &lt;path class=&quot;path1&quot; d=&quot;M16 3c-3.472 0-6.737 1.352-9.192 3.808s-3.808 5.72-3.808 9.192c0 3.472 1.352 6.737 3.808 9.192s5.72 3.808 9.192 3.808c3.472 0 6.737-1.352 9.192-3.808s3.808-5.72 3.808-9.192c0-3.472-1.352-6.737-3.808-9.192s-5.72-3.808-9.192-3.808zM16 0v0c8.837 0 16 7.163 16 16s-7.163 16-16 16c-8.837 0-16-7.163-16-16s7.163-16 16-16zM14 22h4v4h-4zM14 6h4v12h-4z&quot;&gt;&lt;/path&gt; &lt;/symbol&gt; &lt;/defs&gt; &lt;/svg&gt; &lt;body&gt; &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; &lt;script src=&quot;/built/bundle.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; * Connection #1 to host singh.hbot.dev left intact </code></pre> <p>Proceed on next steps</p> <pre class="lang-sh prettyprint-override"><code>$ kubectl apply -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.7/deploy/manifests/00-crds.yaml customresourcedefinition.apiextensions.k8s.io/certificates.certmanager.k8s.io created customresourcedefinition.apiextensions.k8s.io/challenges.certmanager.k8s.io created customresourcedefinition.apiextensions.k8s.io/clusterissuers.certmanager.k8s.io created customresourcedefinition.apiextensions.k8s.io/issuers.certmanager.k8s.io created customresourcedefinition.apiextensions.k8s.io/orders.certmanager.k8s.io created $ $ kubectl apply \ &gt; -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.7/deploy/manifests/00-crds.yaml customresourcedefinition.apiextensions.k8s.io/certificates.certmanager.k8s.io configured customresourcedefinition.apiextensions.k8s.io/challenges.certmanager.k8s.io configured customresourcedefinition.apiextensions.k8s.io/clusterissuers.certmanager.k8s.io configured customresourcedefinition.apiextensions.k8s.io/issuers.certmanager.k8s.io configured customresourcedefinition.apiextensions.k8s.io/orders.certmanager.k8s.io configured $ $ kubectl label namespace cert-manager certmanager.k8s.io/disable-validation=&quot;true&quot; namespace/cert-manager labeled $ $ helm repo add jetstack https://charts.jetstack.io &quot;jetstack&quot; has been added to your repositories $ helm repo update Hang tight while we grab the latest from your chart repositories... ...Skip local chart repository ...Successfully got an update from the &quot;jetstack&quot; chart repository ...Successfully got an update from the &quot;stable&quot; chart repository Update Complete. ⎈ Happy Helming!⎈ </code></pre> <p><code>install cert-manager</code></p> <pre class="lang-sh prettyprint-override"><code>$ helm install --name cert-manager --namespace cert-manager jetstack/cert-manager NAME: cert-manager LAST DEPLOYED: Thu Mar 14 16:06:48 2019 NAMESPACE: cert-manager STATUS: DEPLOYED RESOURCES: ==&gt; v1/ClusterRole NAME AGE cert-manager-edit 3s cert-manager-view 3s cert-manager-webhook:webhook-requester 3s ==&gt; v1/Pod(related) NAME READY STATUS RESTARTS AGE cert-manager-6f68b58796-w44tn 0/1 ContainerCreating 0 3s cert-manager-cainjector-67b4696847-l2lhb 0/1 ContainerCreating 0 3s cert-manager-webhook-6f58884b96-gh52r 0/1 ContainerCreating 0 3s ==&gt; v1/Service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE cert-manager-webhook ClusterIP 10.51.250.12 &lt;none&gt; 443/TCP 3s ==&gt; v1/ServiceAccount NAME SECRETS AGE cert-manager 1 3s cert-manager-cainjector 1 3s cert-manager-webhook 1 3s ==&gt; v1alpha1/Certificate NAME AGE cert-manager-webhook-ca 3s cert-manager-webhook-webhook-tls 3s ==&gt; v1alpha1/Issuer NAME AGE cert-manager-webhook-ca 2s cert-manager-webhook-selfsign 3s ==&gt; v1beta1/APIService NAME AGE v1beta1.admission.certmanager.k8s.io 3s ==&gt; v1beta1/ClusterRole NAME AGE cert-manager 3s cert-manager-cainjector 3s ==&gt; v1beta1/ClusterRoleBinding NAME AGE cert-manager 3s cert-manager-cainjector 3s cert-manager-webhook:auth-delegator 3s ==&gt; v1beta1/Deployment NAME READY UP-TO-DATE AVAILABLE AGE cert-manager 0/1 1 0 3s cert-manager-cainjector 0/1 1 0 3s cert-manager-webhook 0/1 1 0 3s ==&gt; v1beta1/RoleBinding NAME AGE cert-manager-webhook:webhook-authentication-reader 3s ==&gt; v1beta1/ValidatingWebhookConfiguration NAME AGE cert-manager-webhook 2s NOTES: cert-manager has been deployed successfully! In order to begin issuing certificates, you will need to set up a ClusterIssuer or Issuer resource (for example, by creating a 'letsencrypt-staging' issuer). More information on the different types of issuers and how to configure them can be found in our documentation: https://docs.cert-manager.io/en/latest/reference/issuers.html For information on how to configure cert-manager to automatically provision Certificates for Ingress resources, take a look at the `ingress-shim` documentation: https://docs.cert-manager.io/en/latest/reference/ingress-shim.html </code></pre> <p>Apply modified <code>staging-issuer.yaml and production-issuer.yaml</code>.</p> <pre class="lang-sh prettyprint-override"><code>$ kubectl apply -f staging-issuer.yaml issuer.certmanager.k8s.io/letsencrypt-staging created $ kubectl apply -f production-issuer.yaml issuer.certmanager.k8s.io/letsencrypt-prod created </code></pre> <p>Edit my <code>ingress.yaml</code> and apply it with</p> <pre class="lang-sh prettyprint-override"><code> kubernetes.io/ingress.class: &quot;nginx&quot; certmanager.k8s.io/issuer: &quot;letsencrypt-staging&quot; certmanager.k8s.io/acme-challenge-type: http01 </code></pre> <p>I found the <code>certificate</code>, but when I <code>describe</code> it <code>Events</code> is <code>none</code>!</p> <pre class="lang-sh prettyprint-override"><code>$ kubectl get certificate NAME quickstart-example-tls $ kubectl describe certificate quickstart-example-tls Name: quickstart-example-tls Namespace: default Labels: &lt;none&gt; Annotations: &lt;none&gt; API Version: certmanager.k8s.io/v1alpha1 Kind: Certificate Metadata: Creation Timestamp: 2019-03-14T09:17:11Z Generation: 1 Owner References: API Version: extensions/v1beta1 Block Owner Deletion: true Controller: true Kind: Ingress Name: kuard UID: f30e819b-4639-11e9-a2d5-42010a9400fd Resource Version: 2243137 Self Link: /apis/certmanager.k8s.io/v1alpha1/namespaces/default/certificates/quickstart-example-tls UID: f311c99d-4639-11e9-a2d5-42010a9400fd Spec: Acme: Config: Domains: singh.hbot.dev Http 01: Ingress Class: nginx Dns Names: singh.hbot.dev Issuer Ref: Kind: Issuer Name: letsencrypt-staging Secret Name: quickstart-example-tls Status: Conditions: Last Transition Time: 2019-03-14T09:17:11Z Message: Certificate is up to date and has not expired Reason: Ready Status: True Type: Ready Not After: 2019-06-12T08:16:05Z Events: &lt;none&gt; </code></pre> <p>Then I check <code>secret</code>. The docs says</p> <blockquote> <p>Once complete, cert-manager will have created a secret with the details of the certificate based on the secret used in the ingress resource. You can use the describe command as well to see some details:</p> </blockquote> <p>Although I don't have <code>ca.crt</code>. I decided to moved on.</p> <pre class="lang-sh prettyprint-override"><code>$ kubectl get secret NAME TYPE DATA AGE default-token-vnngd kubernetes.io/service-account-token 3 10d letsencrypt-prod Opaque 1 3d1h letsencrypt-staging Opaque 1 3d1h quickstart-example-tls kubernetes.io/tls 3 3d1h quickstart-nginx-ingress-token-c4tjk kubernetes.io/service-account-token 3 58m singh-dev-staging-tls kubernetes.io/tls 3 21h singh-secret kubernetes.io/tls 3 22h $ kubectl describe secret quickstart-example-tls Name: quickstart-example-tls Namespace: default Labels: certmanager.k8s.io/certificate-name=quickstart-example-tls Annotations: certmanager.k8s.io/alt-names: singh.hbot.dev certmanager.k8s.io/common-name: singh.hbot.dev certmanager.k8s.io/ip-sans: certmanager.k8s.io/issuer-kind: Issuer certmanager.k8s.io/issuer-name: letsencrypt-staging Type: kubernetes.io/tls Data ==== tls.key: 1675 bytes ca.crt: 0 bytes tls.crt: 3545 bytes </code></pre> <p>Change <code>ingress.yaml</code> to be <code>production</code> and <code>apply</code>.</p> <pre class="lang-sh prettyprint-override"><code>sixteen:cert-mgr hellohbot$ kubectl apply -f ingress.yaml ingress.extensions/kuard created </code></pre> <p>Remove <code>secret</code></p> <pre class="lang-sh prettyprint-override"><code>sixteen:cert-mgr hellohbot$ kubectl delete secret quickstart-example-tls secret &quot;quickstart-example-tls&quot; deleted </code></pre> <pre class="lang-sh prettyprint-override"><code>sixteen:cert-mgr hellohbot$ kubectl get certificate NAME quickstart-example-tls sixteen:cert-mgr hellohbot$ kubectl describe certificate quickstart-example-tls Name: quickstart-example-tls Namespace: default Labels: &lt;none&gt; Annotations: &lt;none&gt; API Version: certmanager.k8s.io/v1alpha1 Kind: Certificate Metadata: Creation Timestamp: 2019-03-14T09:32:45Z Generation: 1 Owner References: API Version: extensions/v1beta1 Block Owner Deletion: true Controller: true Kind: Ingress Name: kuard UID: 1fab9656-463c-11e9-a2d5-42010a9400fd Resource Version: 2246373 Self Link: /apis/certmanager.k8s.io/v1alpha1/namespaces/default/certificates/quickstart-example-tls UID: 1facf771-463c-11e9-a2d5-42010a9400fd Spec: Acme: Config: Domains: singh.hbot.dev Http 01: Ingress Class: nginx Dns Names: singh.hbot.dev Issuer Ref: Kind: Issuer Name: letsencrypt-staging Secret Name: quickstart-example-tls Status: Conditions: Last Transition Time: 2019-03-14T09:34:06Z Message: Certificate is up to date and has not expired Reason: Ready Status: True Type: Ready Not After: 2019-06-12T08:34:04Z Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Generated 33s cert-manager Generated new private key Normal GenerateSelfSigned 33s cert-manager Generated temporary self signed certificate Normal OrderCreated 33s cert-manager Created Order resource &quot;quickstart-example-tls-1671619353&quot; Normal OrderComplete 6s cert-manager Order &quot;quickstart-example-tls-1671619353&quot; completed successfully Normal CertIssued 6s cert-manager Certificate issued successfully </code></pre> <p>Check <code>order</code></p> <pre class="lang-sh prettyprint-override"><code>$ kubectl describe order quickstart-example-tls-1671619353 Name: quickstart-example-tls-1671619353 Namespace: default Labels: acme.cert-manager.io/certificate-name=quickstart-example-tls Annotations: &lt;none&gt; API Version: certmanager.k8s.io/v1alpha1 Kind: Order Metadata: Creation Timestamp: 2019-03-14T09:33:39Z Generation: 1 Owner References: API Version: certmanager.k8s.io/v1alpha1 Block Owner Deletion: true Controller: true Kind: Certificate Name: quickstart-example-tls UID: 1facf771-463c-11e9-a2d5-42010a9400fd Resource Version: 2246369 Self Link: /apis/certmanager.k8s.io/v1alpha1/namespaces/default/orders/quickstart-example-tls-1671619353 UID: 3fd25e87-463c-11e9-a2d5-42010a9400fd Spec: Config: Domains: singh.hbot.dev Http 01: Ingress Class: nginx Csr: MIIC...RQ8= Dns Names: singh.hbot.dev Issuer Ref: Kind: Issuer Name: letsencrypt-staging Status: Certificate: LS0t...LQo= Challenges: Authz URL: https://acme-staging-v02.api.letsencrypt.org/acme/authz/CkYZY5sWsaEq0uI2l1D2yyQwAjA1kl0_1uFsVY7UDqk Config: Http 01: Ingress Class: nginx Dns Name: singh.hbot.dev Issuer Ref: Kind: Issuer Name: letsencrypt-staging Key: tRxDXBXr_CYcEX1KzU9puQKg1pVZdmEXi7jGWyPAvTs.-kMH8oyhdhqKbua2D8gLPi8FxbeW7rYKBB6w1gMRw2w Token: tRxDXBXr_CYcEX1KzU9puQKg1pVZdmEXi7jGWyPAvTs Type: http-01 URL: https://acme-staging-v02.api.letsencrypt.org/acme/challenge/CkYZY5sWsaEq0uI2l1D2yyQwAjA1kl0_1uFsVY7UDqk/270336074 Wildcard: false Finalize URL: https://acme-staging-v02.api.letsencrypt.org/acme/finalize/8521062/26692657 State: valid URL: https://acme-staging-v02.api.letsencrypt.org/acme/order/8521062/26692657 Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Created 4m27s cert-manager Created Challenge resource &quot;quickstart-example-tls-1671619353-0&quot; for domain &quot;singh.hbot.dev&quot; Normal OrderValid 4m cert-manager Order completed successfully </code></pre> <p><strong>Solution:</strong> Thanks to <code>Harsh Manvar</code></p> <p>Confirm my <code>issuer</code> url from the running <code>issuer</code></p> <pre class="lang-sh prettyprint-override"><code>$ kubectl get issuer letsencrypt-prod -o yaml apiVersion: certmanager.k8s.io/v1alpha1 kind: Issuer metadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {&quot;apiVersion&quot;:&quot;certmanager.k8s.io/v1alpha1&quot;,&quot;kind&quot;:&quot;Issuer&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{},&quot;name&quot;:&quot;letsencrypt-prod&quot;,&quot;namespace&quot;:&quot;default&quot;},&quot;spec&quot;:{&quot;acme&quot;:{&quot;email&quot;:&quot;contact@hbot.io&quot;,&quot;http01&quot;:{},&quot;privateKeySecretRef&quot;:{&quot;name&quot;:&quot;letsencrypt-prod&quot;},&quot;server&quot;:&quot;https://acme-v02.api.letsencrypt.org/directory&quot;}}} creationTimestamp: &quot;2019-03-14T09:12:11Z&quot; generation: 1 name: letsencrypt-prod namespace: default resourceVersion: &quot;2242148&quot; selfLink: /apis/certmanager.k8s.io/v1alpha1/namespaces/default/issuers/letsencrypt-prod uid: 405fa7af-4639-11e9-a2d5-42010a9400fd spec: acme: email: contact@hbot.io http01: {} privateKeySecretRef: name: letsencrypt-prod server: https://acme-v02.api.letsencrypt.org/directory status: acme: uri: https://acme-v02.api.letsencrypt.org/acme/acct/53068205 conditions: - lastTransitionTime: &quot;2019-03-14T09:12:12Z&quot; message: The ACME account was registered with the ACME server reason: ACMEAccountRegistered status: &quot;True&quot; type: Ready </code></pre> <p>Check my <code>ingress</code></p> <pre class="lang-sh prettyprint-override"><code>$ kubectl get ingress --all-namespaces NAMESPACE NAME HOSTS ADDRESS PORTS AGE default kuard singh.hbot.dev 35.198.217.71 80, 443 43m $ kubectl describe ingress Name: kuard Namespace: default Address: 35.198.217.71 Default backend: default-http-backend:80 (10.48.0.7:8080) TLS: quickstart-example-tls terminates singh.hbot.dev Rules: Host Path Backends ---- ---- -------- singh.hbot.dev / kuard:80 (&lt;none&gt;) Annotations: certmanager.k8s.io/acme-challenge-type: http01 certmanager.k8s.io/issuer: letsencrypt-prod kubectl.kubernetes.io/last-applied-configuration: {&quot;apiVersion&quot;:&quot;extensions/v1beta1&quot;,&quot;kind&quot;:&quot;Ingress&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{&quot;certmanager.k8s.io/acme-challenge-type&quot;:&quot;http01&quot;,&quot;certmanager.k8s.io/issuer&quot;:&quot;letsencrypt-prod&quot;,&quot;kubernetes.io/ingress.class&quot;:&quot;nginx&quot;},&quot;name&quot;:&quot;kuard&quot;,&quot;namespace&quot;:&quot;default&quot;},&quot;spec&quot;:{&quot;rules&quot;:[{&quot;host&quot;:&quot;singh.hbot.dev&quot;,&quot;http&quot;:{&quot;paths&quot;:[{&quot;backend&quot;:{&quot;serviceName&quot;:&quot;kuard&quot;,&quot;servicePort&quot;:80},&quot;path&quot;:&quot;/&quot;}]}}],&quot;tls&quot;:[{&quot;hosts&quot;:[&quot;singh.hbot.dev&quot;],&quot;secretName&quot;:&quot;quickstart-example-tls&quot;}]}} kubernetes.io/ingress.class: nginx Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal CREATE 43m nginx-ingress-controller Ingress default/kuard Normal CreateCertificate 43m cert-manager Successfully created Certificate &quot;quickstart-example-tls&quot; Normal UPDATE 10m (x2 over 43m) nginx-ingress-controller Ingress default/kuard Normal UpdateCertificate 10m cert-manager Successfully updated Certificate &quot;quickstart-example-tls&quot; </code></pre> <p>Change <code>issuer</code> to <code>prod</code></p> <pre class="lang-sh prettyprint-override"><code>sixteen:cert-mgr hellohbot$ kubectl apply -f ingress.yaml ingress.extensions/kuard configured </code></pre> <p>Remove old <code>secret</code> to trigger the process.</p> <pre class="lang-sh prettyprint-override"><code>sixteen:cert-mgr hellohbot$ kubectl get secret NAME TYPE DATA AGE default-token-vnngd kubernetes.io/service-account-token 3 10d letsencrypt-prod Opaque 1 3d2h letsencrypt-staging Opaque 1 3d2h quickstart-example-tls kubernetes.io/tls 3 33m quickstart-nginx-ingress-token-c4tjk kubernetes.io/service-account-token 3 103m singh-dev-staging-tls kubernetes.io/tls 3 21h singh-secret kubernetes.io/tls 3 23h sixteen:cert-mgr hellohbot$ kubectl delete secret quickstart-example-tls secret &quot;quickstart-example-tls&quot; deleted </code></pre> <p>Check the new <code>certificate</code></p> <pre class="lang-sh prettyprint-override"><code>sixteen:cert-mgr hellohbot$ kubectl get certificate NAME quickstart-example-tls sixteen:cert-mgr hellohbot$ kubectl describe certificate Name: quickstart-example-tls Namespace: default Labels: &lt;none&gt; Annotations: &lt;none&gt; API Version: certmanager.k8s.io/v1alpha1 Kind: Certificate Metadata: Creation Timestamp: 2019-03-14T09:32:45Z Generation: 1 Owner References: API Version: extensions/v1beta1 Block Owner Deletion: true Controller: true Kind: Ingress Name: kuard UID: 1fab9656-463c-11e9-a2d5-42010a9400fd Resource Version: 2252545 Self Link: /apis/certmanager.k8s.io/v1alpha1/namespaces/default/certificates/quickstart-example-tls UID: 1facf771-463c-11e9-a2d5-42010a9400fd Spec: Acme: Config: Domains: singh.hbot.dev Http 01: Ingress Class: nginx Dns Names: singh.hbot.dev Issuer Ref: Kind: Issuer Name: letsencrypt-prod Secret Name: quickstart-example-tls Status: Conditions: Last Transition Time: 2019-03-14T10:06:53Z Message: Certificate issuance in progress. Temporary certificate issued. Reason: TemporaryCertificate Status: False Type: Ready Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal OrderCreated 33m cert-manager Created Order resource &quot;quickstart-example-tls-1671619353&quot; Normal OrderComplete 33m cert-manager Order &quot;quickstart-example-tls-1671619353&quot; completed successfully Normal CertIssued 33m cert-manager Certificate issued successfully Normal Generated 19s (x2 over 33m) cert-manager Generated new private key Normal GenerateSelfSigned 19s (x2 over 33m) cert-manager Generated temporary self signed certificate Normal Cleanup 19s cert-manager Deleting old Order resource &quot;quickstart-example-tls-1671619353&quot; Normal OrderCreated 19s cert-manager Created Order resource &quot;quickstart-example-tls-2367785339&quot; </code></pre>
<p>in ingress you are using issuer as <code>letsencrypt-staging</code> change it to production and also change <code>tls-secrets</code> it will work</p> <p>Production url for let's encrypt issuer : <a href="https://acme-v02.api.letsencrypt.org/directory" rel="nofollow noreferrer">https://acme-v02.api.letsencrypt.org/directory</a></p> <p>in the issuer you have used the staging url of let's encypt staging server change it to production URL and again try to get tls.cert and key it will run with https://</p> <p>staging certificate some time not work with https and browser give error it is for testing purpose.</p> <p>cert-manager and nginx ingress and other things are looking perfect as it should have to be. </p>
<p>I am running my application on Kubernetes that was provided to me as a black box docker image that runs with a bunch of env vars, volume mounts and (a little more unconventionally) using host port. I discovered - with a lot of pain and sweat - as expected, I can't have more than one pod in my deployment if I ever wish to see the host port function again. </p> <p>Two things are clear to me: 1. I need to add more pod replicas &amp; 2. I can't use an ingress controller (need to have a separate external IP).</p> <p><strong>Other points of information are:</strong></p> <ul> <li>I am using an external IP (quick solution is a LB service)</li> <li>When I enable host port on Kubernetes, everything works like a charm</li> <li>I am using a single tls certificate that is stored in the PVC that will be shared between my pods.</li> <li>When I disable host port, increase number of replicas and pretend it should work, the pods start running successfully, but the application can't be reached the way I reach it normally, as if it never hears what comes from the user through the loadbalancer (hence I thought setting up a NAT might have something to do with a solution??)</li> </ul> <p><strong>Things I tried:</strong></p> <ul> <li>Use NodePort to expose the containerPort, and add replicas (&amp; maybe then set up an ingress for loadbalancing). Problems with this: The port I am trying to map to the host is 80, and it's out range. I need to allow TCP and UDP through, which will require to create 2 separate services each with a different nodePort. </li> <li>Expose any possible port I can think of that might be used through a Loadbalancer service. Problem with this is that the user cannot reach the app for some reason.</li> </ul> <p>My yaml files look something like the following:</p> <p><strong>deployment.yaml</strong></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: namespace: x name: x labels: app: x spec: replicas: 1 selector: matchLabels: app: x template: metadata: labels: app: x spec: # hostNetwork: true containers: - name: x image: x env: ... volumeMounts: ... ports: - containerPort: 80 volumes: ... imagePullSecrets: - name: x </code></pre> <p><strong>service.yaml</strong></p> <pre><code>apiVersion: v1 kind: Service metadata: labels: app: x namespace: x name: x spec: type: LoadBalancer loadBalancerIP: x ports: - name: out port: 8081 targetPort: 8081 protocol: TCP - name: node port: 80 targetPort: 80 protocol: TCP selector: app: x --- apiVersion: v1 kind: Service metadata: labels: app: x namespace: x name: x spec: type: LoadBalancer loadBalancerIP: x ports: - name: out port: 8081 targetPort: 8081 protocol: UDP - name: node port: 80 targetPort: 80 protocol: UDP selector: app: x </code></pre> <p><strong>Problem</strong> is, what is the best practice / solution to replace host port netwroking safely?</p>
<p>After a bit of sweat and tears I figured this out. I found two alternatives to using host networking, both of which give us more freedom to use the host ports in other pods.</p> <p><strong>1. Map containerPort to hostPort</strong></p> <p>This method is slightly better than the host networking, because it only claims very specific ports on the host.</p> <p><em>Advantages:</em> multiple pods can now use host ports AS LONG AS they are using different host ports. Another advantage is that you can use ports pretty much in any range, eg below 1000 and so forth.</p> <p><em>Disadvantages:</em> multiple pods in a single Deployment or Statefulset still cannot co-exist with this configuration as they will be using the same host port. So the "node port not available" error will persist.</p> <p><em>deployment.yaml</em></p> <pre><code> ... - containerPort": 9000 hostPort": 9000 ... </code></pre> <p><strong>2. Use nodePort in your service, map to containerPort</strong></p> <p>This was what essentially did it for me. NodePorts allowed to be used in your service configurations range from 30000 to 32767. So there was no way for me to map 8081 and 443 to their corresponding nodePort. So I mapped my 443 containerPort to 30443 node port in my LoadBalancer service, and 8081 containerPort to 30881 node port. I then did a bit of changes in my code (passed these new node ports as env var) for the times where my application needs to know what host port is being used.</p> <p><em>Advantages:</em> you can scale up your deployment as much as you would like! You also would not occupy the well known ports in case they are needed later.</p> <p><em>Disadvantages:</em> the range (30000 - 32767) is limited. Also no two services can share these nodePorts, so you will only be able to use either the TCP or UDP service. Also you will have to make some changes in your app to work with higher number ports.</p> <p><em>service.yaml</em></p> <pre><code> ... - name: out targetPort: 8081 port: 30881 nodePort: 30881 protocol: TCP - name: https nodePort: 443 port: 30443 targetPort: 30443 protocol: TCP ... </code></pre> <p>So basically whatever resource that uses the nodePort will be the one, of which, you can only have one, if you are using a specific host port. So if you choose to go with the pod hostPort, you can only have one pod with that port, and if you choose to use the service nodePort, you can only have one service with that port on your node.</p>