prompt
stringlengths
65
38.7k
response
stringlengths
41
29.1k
<p>I have some CDC data in Kafka. Now I am trying to sink from Kafka to Elasticsearch. Here is what I have done so far:</p> <h2>Step 1 - Deploy Elasticsearch in Kubernetes (succeed)</h2> <p>I deployed Elasticsearch in Kubernetes by following this tutorial using Elastic Operator:</p> <ol> <li>Deploy ECK in your Kubernetes cluster: <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-eck.html" rel="nofollow noreferrer">https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-eck.html</a></li> <li>Deploy an Elasticsearch cluster: <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html" rel="nofollow noreferrer">https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html</a></li> </ol> <pre><code>apiVersion: elasticsearch.k8s.elastic.co/v1 kind: Elasticsearch metadata: name: hm-elasticsearch namespace: elastic spec: version: 7.14.0 nodeSets: - name: default count: 1 config: node.store.allow_mmap: false </code></pre> <p>Based on the tutorial, I can succeed calling by providing username <code>elastic</code> and password <code>passw0rd</code> in the header by</p> <pre><code>curl -u &quot;elastic:passw0rd&quot; -k &quot;https://hm-elasticsearch-es-http.elastic:9200&quot; </code></pre> <p>which returns</p> <pre><code>{ &quot;name&quot;: &quot;hm-elasticsearch-es-default-0&quot;, &quot;cluster_name&quot;: &quot;hm-elasticsearch&quot;, &quot;cluster_uuid&quot;: &quot;TWgIk0YGR_GVr7IJZcW62g&quot;, &quot;version&quot;: { &quot;number&quot;: &quot;7.14.0&quot;, &quot;build_flavor&quot;: &quot;default&quot;, &quot;build_type&quot;: &quot;docker&quot;, &quot;build_hash&quot;: &quot;dd5a0a2acaa2045ff9624f3729fc8a6f40835aa1&quot;, &quot;build_date&quot;: &quot;2021-07-29T20:49:32.864135063Z&quot;, &quot;build_snapshot&quot;: false, &quot;lucene_version&quot;: &quot;8.9.0&quot;, &quot;minimum_wire_compatibility_version&quot;: &quot;6.8.0&quot;, &quot;minimum_index_compatibility_version&quot;: &quot;6.0.0-beta1&quot; }, &quot;tagline&quot;: &quot;You Know, for Search&quot; } </code></pre> <h2>Step 2 - Add ElasticsearchSinkConnector (failed to connect Elasticsearch)</h2> <p>Now I am trying to adding ElasticsearchSinkConnector, however, I am having issue to set it up.</p> <p>I saw <a href="https://stackoverflow.com/questions/58381240/how-to-kafka-connect-elasticsearch-with-ssl">How to Kafka Connect Elasticsearch with SSL?</a>. Elastic Cloud just needs just to pass the username and password. So I thought it would be similar to mine.</p> <p>Also, based on <a href="https://github.com/debezium/debezium-examples/blob/main/unwrap-smt/es-sink.json" rel="nofollow noreferrer">this ElasticsearchSinkConnector config</a>, I wrote my config, and then try to verify by</p> <pre><code>curl --location --request PUT 'http://hm-connect-cluster-connect-api.kafka:8083/connector-plugins/io.confluent.connect.elasticsearch.ElasticsearchSinkConnector/config/validate' \ --header 'Content-Type: application/json' \ --data-raw '{ &quot;name&quot;: &quot;elasticsearch-sink&quot;, &quot;connector.class&quot;: &quot;io.confluent.connect.elasticsearch.ElasticsearchSinkConnector&quot;, &quot;tasks.max&quot;: &quot;1&quot;, &quot;topics&quot;: &quot;opa_db_server.public.roles&quot;, &quot;connection.url&quot;: &quot;https://hm-elasticsearch-es-http.elastic:9200&quot;, &quot;connection.username&quot;: &quot;elastic&quot;, &quot;connection.password&quot;: &quot;passw0rd&quot;, &quot;transforms&quot;: &quot;unwrap,key&quot;, &quot;transforms.unwrap.type&quot;: &quot;io.debezium.transforms.ExtractNewRecordState&quot;, &quot;transforms.unwrap.drop.tombstones&quot;: &quot;false&quot;, &quot;transforms.key.type&quot;: &quot;org.apache.kafka.connect.transforms.ExtractField$Key&quot;, &quot;transforms.key.field&quot;: &quot;role_id&quot;, &quot;key.ignore&quot;: &quot;false&quot;, &quot;behavior.on.null.values&quot;: &quot;delete&quot; }' </code></pre> <p>It returns the error</p> <pre><code>{ &quot;name&quot;: &quot;io.confluent.connect.elasticsearch.ElasticsearchSinkConnector&quot;, &quot;error_count&quot;: 3, &quot;groups&quot;: [ &quot;Common&quot;, &quot;Transforms&quot;, &quot;Predicates&quot;, &quot;Error Handling&quot;, &quot;Transforms: unwrap&quot;, &quot;Transforms: key&quot;, &quot;Connector&quot;, &quot;Data Conversion&quot;, &quot;Proxy&quot;, &quot;Security&quot;, &quot;Kerberos&quot;, &quot;Data Stream&quot; ], &quot;configs&quot;: [ // ... { &quot;definition&quot;: { &quot;name&quot;: &quot;connection.url&quot;, &quot;type&quot;: &quot;LIST&quot;, &quot;required&quot;: true, &quot;default_value&quot;: null, &quot;importance&quot;: &quot;HIGH&quot;, &quot;documentation&quot;: &quot;The comma-separated list of one or more Elasticsearch URLs, such as ``http://eshost1:9200,http://eshost2:9200`` or ``https://eshost3:9200``. HTTPS is used for all connections if any of the URLs starts with ``https:``. A URL without a protocol is treated as ``http``.&quot;, &quot;group&quot;: &quot;Connector&quot;, &quot;width&quot;: &quot;LONG&quot;, &quot;display_name&quot;: &quot;Connection URLs&quot;, &quot;dependents&quot;: [], &quot;order&quot;: 1 }, &quot;value&quot;: { &quot;name&quot;: &quot;connection.url&quot;, &quot;value&quot;: &quot;https://hm-elasticsearch-es-http.elastic:9200&quot;, &quot;recommended_values&quot;: [], &quot;errors&quot;: [ &quot;Could not connect to Elasticsearch. Error message: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target&quot; ], &quot;visible&quot;: true } }, { &quot;definition&quot;: { &quot;name&quot;: &quot;connection.username&quot;, &quot;type&quot;: &quot;STRING&quot;, &quot;required&quot;: false, &quot;default_value&quot;: null, &quot;importance&quot;: &quot;MEDIUM&quot;, &quot;documentation&quot;: &quot;The username used to authenticate with Elasticsearch. The default is the null, and authentication will only be performed if both the username and password are non-null.&quot;, &quot;group&quot;: &quot;Connector&quot;, &quot;width&quot;: &quot;SHORT&quot;, &quot;display_name&quot;: &quot;Connection Username&quot;, &quot;dependents&quot;: [], &quot;order&quot;: 2 }, &quot;value&quot;: { &quot;name&quot;: &quot;connection.username&quot;, &quot;value&quot;: &quot;elastic&quot;, &quot;recommended_values&quot;: [], &quot;errors&quot;: [ &quot;Could not authenticate the user. Check the 'connection.username' and 'connection.password'. Error message: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target&quot; ], &quot;visible&quot;: true } }, { &quot;definition&quot;: { &quot;name&quot;: &quot;connection.password&quot;, &quot;type&quot;: &quot;PASSWORD&quot;, &quot;required&quot;: false, &quot;default_value&quot;: null, &quot;importance&quot;: &quot;MEDIUM&quot;, &quot;documentation&quot;: &quot;The password used to authenticate with Elasticsearch. The default is the null, and authentication will only be performed if both the username and password are non-null.&quot;, &quot;group&quot;: &quot;Connector&quot;, &quot;width&quot;: &quot;SHORT&quot;, &quot;display_name&quot;: &quot;Connection Password&quot;, &quot;dependents&quot;: [], &quot;order&quot;: 3 }, &quot;value&quot;: { &quot;name&quot;: &quot;connection.password&quot;, &quot;value&quot;: &quot;[hidden]&quot;, &quot;recommended_values&quot;: [], &quot;errors&quot;: [ &quot;Could not authenticate the user. Check the 'connection.username' and 'connection.password'. Error message: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target&quot; ], &quot;visible&quot;: true } }, // ... ] } </code></pre> <p>The full verification response with all fields can be found <a href="https://gist.github.com/Hongbo-Miao/34e51bfe91dfd169259ab81ba3fd942a" rel="nofollow noreferrer">here</a> which has all info for the config field can be used.</p> <h1>UPDATE 1 (12/8/2021):</h1> <p>I found <a href="https://docs.confluent.io/kafka-connect-elasticsearch/current/security.html#step-4-configure-the-connector" rel="nofollow noreferrer">this document</a> which has more config regarding SSL</p> <pre><code>&quot;elastic.security.protocol&quot;: &quot;SSL&quot; &quot;elastic.https.ssl.keystore.location&quot;: &quot;/path/to/keystore.jks&quot; &quot;elastic.https.ssl.keystore.password&quot;: &quot;xxx&quot; &quot;elastic.https.ssl.key.password&quot;: &quot;xxx&quot; &quot;elastic.https.ssl.keystore.type&quot;: &quot;JKS&quot; &quot;elastic.https.ssl.truststore.location&quot;: &quot;/path/to/truststore.jks&quot; &quot;elastic.https.ssl.truststore.password&quot;: &quot;xxx&quot; &quot;elastic.https.ssl.truststore.type&quot;: &quot;JKS&quot; &quot;elastic.https.ssl.protocol&quot;: &quot;TLS&quot; </code></pre> <p>In my case, I only need provider username and password to succeed. But in above config, there is no place to provide username. So I am not sure how to really write it correctly.</p> <h1>UPDATE 2 (12/9/2021):</h1> <p>I have these pods running</p> <pre><code>&gt; kubectl get pods --namespace=elastic NAME READY STATUS RESTARTS AGE hm-kibana-kb-77d4d9b456-m6th9 1/1 Running 0 6d3h hm-elasticsearch-es-default-0 1/1 Running 0 35h </code></pre> <p>and these secrets</p> <pre><code>kubectl get secrets --namespace=elastic NAME TYPE DATA AGE hm-kibana-kibana-user Opaque 1 6d3h elastic-hm-kibana-kibana-user Opaque 3 6d3h hm-kibana-kb-http-ca-internal Opaque 2 6d3h hm-elasticsearch-es-http-ca-internal Opaque 2 6d3h hm-elasticsearch-es-http-certs-internal Opaque 3 6d3h hm-elasticsearch-es-http-certs-public Opaque 2 6d3h hm-kibana-kb-es-ca Opaque 2 6d3h hm-kibana-kb-http-certs-internal Opaque 3 6d3h hm-kibana-kb-http-certs-public Opaque 2 6d3h hm-elasticsearch-es-transport-ca-internal Opaque 2 6d3h hm-elasticsearch-es-transport-certs-public Opaque 1 6d3h hm-elasticsearch-es-remote-ca Opaque 1 6d3h hm-elasticsearch-es-elastic-user Opaque 1 6d3h hm-elasticsearch-es-internal-users Opaque 3 6d3h hm-elasticsearch-es-xpack-file-realm Opaque 3 6d3h hm-elasticsearch-es-default-es-config Opaque 1 6d3h hm-elasticsearch-es-default-es-transport-certs Opaque 3 6d3h hm-kibana-kb-config Opaque 2 6d3h </code></pre> <p>I am able to save <code>ca.crt</code>, <code>tls.crt</code>, <code>tls.key</code> locally by</p> <pre><code>kubectl get secret hm-elasticsearch-es-http-certs-public \ --namespace=elastic \ --output=go-template='{{index .data &quot;ca.crt&quot; | base64decode }}' \ &gt; ca.crt kubectl get secret hm-elasticsearch-es-http-certs-public \ --namespace=elastic \ --output=go-template='{{index .data &quot;tls.crt&quot; | base64decode }}' \ &gt; tls.crt kubectl get secret hm-elasticsearch-es-http-certs-internal \ --namespace=elastic \ --output=go-template='{{index .data &quot;tls.key&quot; | base64decode }}' \ &gt; tls.key </code></pre> <p>Before I have to use <code>-k</code> flag to disable the certificate verification to let the <code>curl</code> succeed. Now in Kubernetes, I can succeed without the flag:</p> <pre><code>curl --request GET \ --url https://hm-elasticsearch-es-http.elastic:9200 \ --cacert ca.crt \ --key tls.key \ --cert tls.crt \ --header 'Content-Type: application/json' \ -u &quot;elastic:passw0rd&quot; </code></pre> <p>Also, I succeed generating <code>keystore.jks</code> by</p> <pre><code>openssl pkcs12 -export \ -in tls.crt \ -inkey tls.key \ -CAfile ca.crt \ -caname root \ -out keystore.p12 \ -password pass:SFLzyT8DPkGGjDtn \ -name hm-elasticsearch-keystore keytool -importkeystore \ -srckeystore keystore.p12 \ -srcstoretype PKCS12 \ -srcstorepass SFLzyT8DPkGGjDtn \ -deststorepass MPx57vkACsRWKVap \ -destkeypass MPx57vkACsRWKVap \ -destkeystore keystore.jks \ -alias hm-elasticsearch-keystore </code></pre> <p>I am still not sure how <strong>truststore</strong> in UPDATE 1 is. But now I can fill this part regarding <strong>keystore</strong>:</p> <pre><code>&quot;elastic.https.ssl.keystore.location&quot;: &quot;/path/to/keystore.jks&quot; &quot;elastic.https.ssl.keystore.password&quot;: &quot;MPx57vkACsRWKVap&quot; &quot;elastic.https.ssl.key.password&quot;: &quot;MPx57vkACsRWKVap&quot; &quot;elastic.https.ssl.keystore.type&quot;: &quot;JKS&quot; </code></pre> <p>However, my <code>keystore.jks</code> is currently on my laptop locally. My Elasticsearch and ElasticsearchSinkConnector is running in the Kubernetes.</p> <p>Where does this <code>&quot;elastic.https.ssl.keystore.location&quot;: &quot;/path/to/keystore.jks&quot;</code> refer to?</p>
<p>First add more background. The way I deployed Kafka is using <a href="https://strimzi.io/quickstarts/" rel="noreferrer">Strimzi</a>:</p> <pre><code>kubectl create namespace kafka kubectl apply --filename=&quot;https://strimzi.io/install/latest?namespace=kafka&quot; --namespace=kafka kubectl apply --filename=https://strimzi.io/examples/latest/kafka/kafka-persistent-single.yaml --namespace=kafka </code></pre> <p>Following the UPDATE 2 in the question, once got <strong>keystore.jks</strong>, I created the secret by</p> <pre><code>kubectl create secret generic hm-elasticsearch-keystore \ --from-file=keystore.jks \ --namespace=kafka </code></pre> <p>I have files</p> <p><strong>kafkaconnect.yaml</strong></p> <pre><code>apiVersion: kafka.strimzi.io/v1beta2 kind: KafkaConnect metadata: name: hm-connect-cluster namespace: kafka annotations: # use-connector-resources configures this KafkaConnect # to use KafkaConnector resources to avoid # needing to call the Connect REST API directly strimzi.io/use-connector-resources: &quot;true&quot; spec: image: hongbomiao/hm-connect-debezium:latest replicas: 1 bootstrapServers: my-cluster-kafka-bootstrap:9093 tls: trustedCertificates: - secretName: my-cluster-cluster-ca-cert certificate: ca.crt config: config.storage.replication.factor: 1 offset.storage.replication.factor: 1 status.storage.replication.factor: 1 config.providers: file config.providers.file.class: org.apache.kafka.common.config.provider.FileConfigProvider externalConfiguration: volumes: - name: hm-elasticsearch-keystore-volume secret: secretName: hm-elasticsearch-keystore </code></pre> <p><strong>elasticsearch-sink-kafkaconnector.yaml</strong></p> <pre><code>apiVersion: kafka.strimzi.io/v1beta2 kind: KafkaConnector metadata: name: elasticsearch-sink-connector namespace: kafka labels: strimzi.io/cluster: hm-connect-cluster spec: class: io.confluent.connect.elasticsearch.ElasticsearchSinkConnector tasksMax: 1 # https://docs.confluent.io/kafka-connect-elasticsearch/current/configuration_options.html config: connector.class: &quot;io.confluent.connect.elasticsearch.ElasticsearchSinkConnector&quot; tasks.max: &quot;1&quot; topics: &quot;opa_db_server.public.roles&quot; connection.url: &quot;https://hm-elasticsearch-es-http.elastic:9200&quot; connection.username: &quot;elastic&quot; connection.password: &quot;passw0rd&quot; transforms: &quot;unwrap,key&quot; transforms.unwrap.type: &quot;io.debezium.transforms.ExtractNewRecordState&quot; transforms.unwrap.drop.tombstones: &quot;false&quot; transforms.key.type: &quot;org.apache.kafka.connect.transforms.ExtractField$Key&quot; transforms.key.field: &quot;role_id&quot; key.ignore: &quot;false&quot; behavior.on.null.values: &quot;delete&quot; elastic.security.protocol: &quot;SSL&quot; elastic.https.ssl.keystore.location: &quot;/opt/kafka/external-configuration/hm-elasticsearch-volume/keystore.jks&quot; elastic.https.ssl.keystore.password: &quot;MPx57vkACsRWKVap&quot; elastic.https.ssl.key.password: &quot;MPx57vkACsRWKVap&quot; elastic.https.ssl.keystore.type: &quot;JKS&quot; elastic.https.ssl.truststore.location: &quot;/opt/kafka/external-configuration/hm-elasticsearch-keystore-volume/keystore.jks&quot; elastic.https.ssl.truststore.password: &quot;MPx57vkACsRWKVap&quot; elastic.https.ssl.truststore.type: &quot;JKS&quot; elastic.https.ssl.protocol: &quot;TLS1.3&quot; </code></pre> <p>Note keystore and truststore share the same one.</p> <p>Then just need run</p> <pre><code>kubectl apply --filename=kafkaconnect.yaml kubectl apply --filename=elasticsearch-sink-kafkaconnector.yaml </code></pre> <p>Now it works!</p>
<p>I'm using the kubebuilder framework in my controller and I want to completely ignore events from a list of given system namespaces. I think predicates must be the best option for this, hence I have the following code</p> <pre><code>... WithEventFilter(predicate.Funcs{ GenericFunc: func(e event.GenericEvent) bool { namespace := e.Object.GetNamespace() if _, ok := systemNs[namespace]; ok { // ignore events from system namespaces return false } return true }, }). </code></pre> <p>However I still receive events from all namespaces instead of just the ones which I allow. Is this a correct and valid use case of predicates?</p>
<p>According to <a href="https://github.com/kubernetes-sigs/controller-runtime/blob/1e4d87c9f9e15e4a58bb81909dd787f30ede7693/pkg/handler/eventhandler.go#L52" rel="nofollow noreferrer">controller-runtime</a></p> <blockquote> <p>Generic is called in response to an event of an unknown type or a synthetic event triggered as a cron or external trigger request - e.g. reconcile Autoscaling, or a Webhook.</p> </blockquote> <p>Most of the time reconciliation gets triggered on <code>Create</code>, <code>Update</code>, or <code>Delete</code> so you need to filter on these events.</p> <pre class="lang-golang prettyprint-override"><code>WithEventFilter(predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { namespace := e.Object.GetNamespace() if _, ok := systemNs[namespace]; ok { // ignore events from system namespaces return false } return true }, UpdateFunc: func(e event.UpdateEvent) bool { namespace := e.ObjectNew.GetNamespace() if _, ok := systemNs[namespace]; ok { // ignore events from system namespaces return false } return true }, DeleteFunc: func(e event.DeleteEvent) bool { namespace := e.Object.GetNamespace() if _, ok := systemNs[namespace]; ok { // ignore events from system namespaces return false } return true }, }). </code></pre>
<p>We have application with huge configuration (this is just a part):</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: my-app data: application.yaml: |- config: app: MY-APP my-custom-map: KEY1: value1 KEY2: value2 KEY3: value3 KEY4: value4 something1: true something2: 123 something3: string123 something4: null subclass: anotherMap: &quot;[AAA:0.0.1,BBB:CCC]&quot;: &quot;DDD:EEEE&quot; subclass2: something4: AAAA anotherMap2: 0.0.3: 0.0.3 </code></pre> <p>I follow <a href="https://github.com/fabric8io/spring-cloud-kubernetes/tree/master/spring-cloud-kubernetes-examples/kubernetes-reload-example" rel="noreferrer">this</a> example to bind configmap with spring boot configuration but there is still some problem for example how to solve null in yaml which spring yaml postprocessor resolve as empty string: <a href="https://github.com/spring-projects/spring-framework/issues/19986" rel="noreferrer">issue</a></p> <p>second problem is how to handle this configmap. I know I can edit and then use apply but this can lead to some error. Is there some tool which I can use to edit this yaml and make some bash script for editing ? like: ./my-script.sh -function addMyCustomMapValue -args &quot;KEY5:value5&quot; . I tried to explore <a href="https://github.com/mikefarah/yq" rel="noreferrer">yq</a> but I think there is some limitation and it is hard to use for some use-case and then <a href="https://kustomize.io/" rel="noreferrer">kustomize</a> which I think is good for creating configmap but not for editing existing one.</p> <p>Is there already some good example for this use-case ?</p>
<p><strong>Option : 1</strong></p> <p>You can Use the Lens : <a href="https://k8slens.dev/kubernetes.html" rel="nofollow noreferrer">https://k8slens.dev/kubernetes.html</a></p> <p>It's UI for monitoring and Managing K8s clusters. Using this you can also edit the configmap.</p> <p><strong>Option : 2</strong></p> <p>You can manage all the Key value into single YAML file and create configmap from file :</p> <pre><code>kubectl create configmap some-config \ --from-file=some-key=some-config.yaml \ -n some-namespace \ -o yaml \ --dry-run | kubectl apply -f - </code></pre> <p><strong>Option : 3</strong></p> <p>Use <code>helm</code> and <code>values.yaml</code> template to create and your chart and apply it further.</p> <p><strong>Configmap</strong> using <strong>YAML</strong> helm</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: jksconfig data: config.json: |- {{ .Files.Get &quot;config.json&quot; | indent 4 }} </code></pre> <p><strong>Option : 4</strong></p> <p>If you are using the configmap as Environment or injecting it to file path you can use the Hashi corp vault also : <a href="https://www.vaultproject.io/" rel="nofollow noreferrer">https://www.vaultproject.io/</a></p> <p><strong>Option : 5</strong></p> <p>As you suggested you can create one <strong>Bash</strong> script which will export the existing running <strong>Configmap</strong> to a new <strong>YAML</strong> file one you are done with editing YAML manually. You can apply the changes to <strong>K8s</strong> cluster.</p> <pre><code>#bin/bash kubectl get configmap &lt;configmap-name&gt; -o yaml &gt; cofig.yaml </code></pre> <p>You can also check the : <a href="https://github.com/Gallore/yaml_cli" rel="nofollow noreferrer">https://github.com/Gallore/yaml_cli</a> might be helpful.</p>
<p>I am trying to use <code>kubernetes</code> for local deployment using <code>minikube</code>, I want to mount a share a directory between host machine and pods. For this, I am trying to mount directory to <code>minikube</code>. But I already had minikube running on which few deployments were running. I deleted them. But every time I restart minikube with mount I get following error</p> <pre><code>$ minikube start --mount-string=&quot;/var/log:/log&quot; --mount * minikube v1.14.2 on Ubuntu 18.04 * Using the docker driver based on existing profile * Starting control plane node minikube in cluster minikube * Restarting existing docker container for &quot;minikube&quot; ... X Exiting due to GUEST_MOUNT_CONFLICT: Sorry, docker does not allow mounts to be changed after container creation (previous mount: '', new mount: '/var/log:/log)' </code></pre> <p>Output for kubectl get all is</p> <pre><code>kubectl get all NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/kubernetes ClusterIP 10.96.0.1 &lt;none&gt; 443/TCP 2s </code></pre> <p>What am I doing wrong here. I need to mount <code>/var/log:/log</code> in my pods just like docker</p>
<p>You will have to delete the minikube container first using <code>minikube delete</code> , after that recreate the container with the new mount path <code>minikube start --mount-string=&quot;/var/log:/log&quot; --mount</code><br /> Check this Github <a href="https://github.com/kubernetes/minikube/issues/11084" rel="noreferrer">Issue</a> for more details</p>
<p>I have packed the software to a container. I need to put the container to cluster by Azure Container Service. The software have outputs of an directory <code>/src/data/</code>, I want to access the content of the whole directory. </p> <p>After searching, I have to solution.</p> <ol> <li>use Blob Storage on azure, but then after searching, I can't find the executable method.</li> <li>use Persistent Volume, but all the official documentation of azure and pages I found is about Persistent Volume itself, not about how to inspect it.</li> </ol> <p>I need to access and manage my output directory on Azure cluster. In other words, I need a savior. </p>
<p>As I've explained <a href="https://frank.sauerburger.io/2021/12/01/inspect-k8s-pvc.html" rel="noreferrer">here</a> and <a href="https://k8s.sauerburger.com/t/pvc-inspect" rel="noreferrer">here</a>, in general, if you can interact with the cluster using <code>kubectl</code>, you can create a pod/container, mount the PVC inside, and use the container's tools to, e.g., <code>ls</code> the contents. If you need more advanced editing tools, replace the container image <code>busybox</code> with a custom one.</p> <p><strong>Create the inspector pod</strong></p> <pre class="lang-yaml prettyprint-override"><code>cat &lt;&lt;EOF | kubectl apply -f - apiVersion: v1 kind: Pod metadata: name: pvc-inspector spec: containers: - image: busybox name: pvc-inspector command: [&quot;tail&quot;] args: [&quot;-f&quot;, &quot;/dev/null&quot;] volumeMounts: - mountPath: /pvc name: pvc-mount volumes: - name: pvc-mount persistentVolumeClaim: claimName: YOUR_CLAIM_NAME_HERE EOF </code></pre> <p><strong>Inspect the contents</strong></p> <pre><code>kubectl exec -it pvc-inspector -- sh $ ls /pvc </code></pre> <p><strong>Clean Up</strong></p> <pre><code>kubectl delete pod pvc-inspector </code></pre>
<p>I am setting <code>KUBECONFIG</code> variable, but kubectl is not using this variable and instead using the default config file.</p> <p>Setting variable as below -</p> <pre><code>$export KUBECONFIG=./my-k8s-token.config </code></pre> <p>next am running get pods as below -</p> <pre><code>$ kubectl.exe get pods -v 8 I1211 22:08:39.175597 1920 loader.go:359] Config loaded from file C:\Users\myuserhome/.kube/config I1211 22:08:39.186378 1920 round_trippers.go:416] GET https://kubernetes.docker.internal:6443/api/v1/namespaces/default/pods?limit=500 I1211 22:08:39.187586 1920 round_trippers.go:423] Request Headers: </code></pre> <p>As you can see above, kubectl is still using the default config file: <code>C:\Users\myuserhome/.kube/config</code>.</p> <p>How can i fix this. How can i make kubectl read the config file from KUBECONFIG variable.</p> <p>Note: If you are wondering why there is .exe extension for kubectl, the answer is I am using WSL2 with Ubuntu.</p>
<p>I could solve the issue by using <code>kubectl</code> which i installed using offical documentation - <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-using-native-package-management" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-using-native-package-management</a>.</p> <p>Now on using kubectl instead of kubectl.exe I am able to use KUBECONFIG env variable.</p>
<p>I am testing something out on my local minikube cluster on a Windows10 machine. I deployed my test deployment on my local minikube cluster and added a service to it to access over NodePort, but I cannot access it.</p> <pre><code>PS C:\Users\Admin&gt; kubectl get all -n web -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES pod/nginx-webserver-deploy-79b6588b5f-mllnf 1/1 Running 0 134m 172.17.0.5 minikube &lt;none&gt; &lt;none&gt; pod/nginx-webserver-deploy-79b6588b5f-rvtxt 1/1 Running 0 134m 172.17.0.7 minikube &lt;none&gt; &lt;none&gt; pod/nginx-webserver-deploy-79b6588b5f-xqzwz 1/1 Running 0 134m 172.17.0.6 minikube &lt;none&gt; &lt;none&gt; NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR service/nginx-webserver-service NodePort 10.96.115.194 &lt;none&gt; 80:30008/TCP 132m app=nginx-webserver,tier=frontend NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR deployment.apps/nginx-webserver-deploy 3/3 3 3 134m nginx-webserver nginx:1.20.2 app=nginx-webserver,tier=frontend NAME DESIRED CURRENT READY AGE CONTAINERS IMAGES SELECTOR replicaset.apps/nginx-webserver-deploy-79b6588b5f 3 3 3 134m nginx-webserver nginx:1.20.2 app=nginx-webserver,pod-template-hash=79b6588b5f,tier= frontend PS C:\Users\Admin&gt; kubectl describe svc nginx-webserver-service -n web Name: nginx-webserver-service Namespace: web Labels: &lt;none&gt; Annotations: &lt;none&gt; Selector: app=nginx-webserver,tier=frontend Type: NodePort IP Family Policy: SingleStack IP Families: IPv4 IP: 10.96.115.194 IPs: 10.96.115.194 Port: http 80/TCP TargetPort: 80/TCP NodePort: http 30008/TCP Endpoints: 172.17.0.5:80,172.17.0.6:80,172.17.0.7:80 Session Affinity: None External Traffic Policy: Cluster Events: &lt;none&gt; </code></pre> <p>But I am not able to connect using nodeport method:</p> <pre><code>PS C:\Users\Admin&gt; curl 10.96.115.194:30008 curl : Unable to connect to the remote server At line:1 char:1 + curl 10.96.115.194:30008 + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand </code></pre> <p>I tried disabling the Windows firewall fully but no luck.</p> <p>I must be missing something core but could not figure out yet.</p>
<p>I found the solution.</p> <p>Unlike on Linux, accessing NodePort using the specified port on the service definition yaml file is not a straightforward thing on Windows10.</p> <p>On Windows10, it has to be done as follows:</p> <pre><code>PS C:\Users\Admin&gt; minikube service nginx-webserver-service -n web |-----------|-------------------------|-------------|---------------------------| | NAMESPACE | NAME | TARGET PORT | URL | |-----------|-------------------------|-------------|---------------------------| | web | nginx-webserver-service | http/80 | http://192.168.49.2:30008 | |-----------|-------------------------|-------------|---------------------------| * Starting tunnel for service nginx-webserver-service. |-----------|-------------------------|-------------|------------------------| | NAMESPACE | NAME | TARGET PORT | URL | |-----------|-------------------------|-------------|------------------------| | web | nginx-webserver-service | | http://127.0.0.1:61410 | |-----------|-------------------------|-------------|------------------------| * Opening service web/nginx-webserver-service in default browser... ! Because you are using a Docker driver on windows, the terminal needs to be open to run it. * Stopping tunnel for service nginx-webserver-service. </code></pre> <p>This will open the exposed service on your default web-browser automatically.</p> <p>Otherwise, you can have it just generated the URL instead of opening automatically.</p> <pre><code>PS C:\Users\Admin&gt; minikube service nginx-webserver-service -n web --url * Restarting the docker service may improve performance. * Starting tunnel for service nginx-webserver-service. |-----------|-------------------------|-------------|------------------------| | NAMESPACE | NAME | TARGET PORT | URL | |-----------|-------------------------|-------------|------------------------| | web | nginx-webserver-service | | http://127.0.0.1:52665 | |-----------|-------------------------|-------------|------------------------| http://127.0.0.1:52665 ! Because you are using a Docker driver on windows, the terminal needs to be open to run it. * Stopping tunnel for service nginx-webserver-service. </code></pre>
<p>I'm very new to Ansible and I'm trying to install kubectl on an EC2 instance (Ubuntu 18.04) for a class.</p> <p>I have ran the playbook and it went well until it hit task 4 then threw the following error:</p> <blockquote> <p>fatal: [localhost]: FAILED! =&gt; {&quot;changed&quot;: false, &quot;msg&quot;: &quot;Failed to update apt cache: W:Updating from such a repository can't be done securely, and is therefore disabled by default., W:See apt-secure(8) manpage for repository creation and user configuration details., W:GPG error: <a href="https://packages.cloud.google.com/apt" rel="nofollow noreferrer">https://packages.cloud.google.com/apt</a> kubernetes-xenial InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY FEEA9169307EA071 NO_PUBKEY 8B57C5C2836F4BEB, E:The repository 'https://apt.kubernetes.io kubernetes-xenial InRelease' is not signed.&quot;}</p> </blockquote> <p>It now throws the same error on task 1 whenever I try to run it again. Can someone advise me on how to fix this?</p> <p>This is the playbook I have written, it's based on an exercise I completed for installing Docker using Ansible and the commands given to me for installing kubectl:</p> <pre><code>- name: A playbook to install kubectl on a VM hosts: localhost user: ubuntu become: yes tasks: - name: 1. Update APT Package Manager apt: update_cache: yes - name: 2. Install dependency packages apt: name={{ item }} with_items: - apt-transport-https - ca-certificates - curl - gnupg-agent - software-properties-common - name: 3. Get APT Key shell: cmd: curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - cmd: echo &quot;deb https://apt.kubernetes.io/ kubernetes-xenial main&quot; | sudo tee -a /etc/apt/sources.list.d/kubernetes.list - name: 4. Update Packages apt: update_cache: yes - name: 5. Install Kubectl apt: update_cache: yes name: kubectl </code></pre>
<p>Regarding the part</p> <pre><code>- name: 3. Get APT Key shell: cmd: curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - cmd: echo &quot;deb https://apt.kubernetes.io/ kubernetes-xenial main&quot; | sudo tee -a /etc/apt/sources.list.d/kubernetes.list </code></pre> <p>The <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html" rel="nofollow noreferrer"><code>shell</code></a>_module will only execute the second <code>cmd</code>. Ansible can only pass one of the parameters to the module, the last one.</p> <p>To <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/get_url_module.html" rel="nofollow noreferrer">download files from HTTPS to node</a> you may use the <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/get_url_module.html#examples" rel="nofollow noreferrer"><code>get_url</code></a>_module, followed by an <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/apt_key_module.html" rel="nofollow noreferrer"><code>apt_key</code></a>_module task to <a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/apt_key_module.html#examples" rel="nofollow noreferrer">add an apt key</a>.</p> <pre><code>- name: Download apt key get_url: url: https://packages.cloud.google.com/apt/doc/apt-key.gpg dest: /tmp # or /etc/pki/rpm-gpg depending on the infrastructure - name: Add a key from a file ansible.builtin.apt_key: file: /tmp/apt-key.gpg state: present </code></pre> <p>You could also add it by</p> <pre><code>- name: Add an Apt signing key, uses whichever key is at the URL ansible.builtin.apt_key: url: https://packages.cloud.google.com/apt/doc/apt-key.gpg state: present </code></pre> <p>or if you know the key ID already</p> <pre><code>- name: Add missing Apt signing key by ID from a keyserver ansible.builtin.apt_key: keyserver: keyserver.ubuntu.com id: &quot;{{ KEY_ID }}&quot; </code></pre>
<p>I am trying to delete (and recreate) the Argo namespace, but it won't fully delete because I tried launching an eventsource and eventbus there. Now these will not delete.</p> <p>I have tried to delete them via yaml and individually - no success yet.</p> <p>The frustrating result is that I cannot re-launch argo</p> <pre><code>customresourcedefinition.apiextensions.k8s.io/clusterworkflowtemplates.argoproj.io unchanged customresourcedefinition.apiextensions.k8s.io/cronworkflows.argoproj.io unchanged customresourcedefinition.apiextensions.k8s.io/workfloweventbindings.argoproj.io unchanged customresourcedefinition.apiextensions.k8s.io/workflows.argoproj.io unchanged customresourcedefinition.apiextensions.k8s.io/workflowtasksets.argoproj.io unchanged customresourcedefinition.apiextensions.k8s.io/workflowtemplates.argoproj.io unchanged clusterrole.rbac.authorization.k8s.io/argo-aggregate-to-admin unchanged clusterrole.rbac.authorization.k8s.io/argo-aggregate-to-edit unchanged clusterrole.rbac.authorization.k8s.io/argo-aggregate-to-view unchanged clusterrole.rbac.authorization.k8s.io/argo-cluster-role unchanged clusterrole.rbac.authorization.k8s.io/argo-server-cluster-role unchanged clusterrolebinding.rbac.authorization.k8s.io/argo-binding unchanged clusterrolebinding.rbac.authorization.k8s.io/argo-server-binding unchanged Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: serviceaccounts &quot;argo&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: serviceaccounts &quot;argo-server&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: roles.rbac.authorization.k8s.io &quot;argo-role&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: rolebindings.rbac.authorization.k8s.io &quot;argo-binding&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: configmaps &quot;workflow-controller-configmap&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: services &quot;argo-server&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: services &quot;workflow-controller-metrics&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: deployments.apps &quot;argo-server&quot; is forbidden: unable to create new content in namespace argo because it is being terminated Error from server (Forbidden): error when creating &quot;https://github.com/argoproj/argo-workflows/releases/download/v3.2.0/install.yaml&quot;: deployments.apps &quot;workflow-controller&quot; is forbidden: unable to create new content in namespace argo because it is being terminated </code></pre> <p>Here is what is going on in the argo namespace itself</p> <pre><code>{ &quot;apiVersion&quot;: &quot;v1&quot;, &quot;kind&quot;: &quot;Namespace&quot;, &quot;metadata&quot;: { &quot;creationTimestamp&quot;: &quot;2021-10-21T14:52:51Z&quot;, &quot;deletionTimestamp&quot;: &quot;2021-12-10T18:48:17Z&quot;, &quot;labels&quot;: { &quot;kubernetes.io/metadata.name&quot;: &quot;argo&quot; }, &quot;name&quot;: &quot;argo&quot;, &quot;resourceVersion&quot;: &quot;9222845&quot;, &quot;uid&quot;: &quot;2ce61352-74a5-40d1-b35e-fe1efa39c3af&quot; }, &quot;spec&quot;: { &quot;finalizers&quot;: [ &quot;kubernetes&quot; ] }, &quot;status&quot;: { &quot;conditions&quot;: [ { &quot;lastTransitionTime&quot;: &quot;2021-12-10T18:48:23Z&quot;, &quot;message&quot;: &quot;All resources successfully discovered&quot;, &quot;reason&quot;: &quot;ResourcesDiscovered&quot;, &quot;status&quot;: &quot;False&quot;, &quot;type&quot;: &quot;NamespaceDeletionDiscoveryFailure&quot; }, { &quot;lastTransitionTime&quot;: &quot;2021-12-10T18:48:23Z&quot;, &quot;message&quot;: &quot;All legacy kube types successfully parsed&quot;, &quot;reason&quot;: &quot;ParsedGroupVersions&quot;, &quot;status&quot;: &quot;False&quot;, &quot;type&quot;: &quot;NamespaceDeletionGroupVersionParsingFailure&quot; }, { &quot;lastTransitionTime&quot;: &quot;2021-12-10T18:48:23Z&quot;, &quot;message&quot;: &quot;All content successfully deleted, may be waiting on finalization&quot;, &quot;reason&quot;: &quot;ContentDeleted&quot;, &quot;status&quot;: &quot;False&quot;, &quot;type&quot;: &quot;NamespaceDeletionContentFailure&quot; }, { &quot;lastTransitionTime&quot;: &quot;2021-12-10T18:48:23Z&quot;, &quot;message&quot;: &quot;Some resources are remaining: eventbus.argoproj.io has 1 resource instances, eventsources.argoproj.io has 1 resource instances&quot;, &quot;reason&quot;: &quot;SomeResourcesRemain&quot;, &quot;status&quot;: &quot;True&quot;, &quot;type&quot;: &quot;NamespaceContentRemaining&quot; }, { &quot;lastTransitionTime&quot;: &quot;2021-12-10T18:48:23Z&quot;, &quot;message&quot;: &quot;Some content in the namespace has finalizers remaining: eventbus-controller in 1 resource instances, eventsource-controller in 1 resource instances&quot;, &quot;reason&quot;: &quot;SomeFinalizersRemain&quot;, &quot;status&quot;: &quot;True&quot;, &quot;type&quot;: &quot;NamespaceFinalizersRemaining&quot; } ], &quot;phase&quot;: &quot;Terminating&quot; } } </code></pre> <p>UPDATE: Even though one test of Kubernetes shows that the eventsource persists, another test shows that it does not</p> <p>This is the response to kubectl get eventsources argo</p> <pre><code>Error from server (NotFound): eventsources.argoproj.io &quot;argo&quot; not found </code></pre>
<p>For anyone who stumbles onto this question, it is a permissions issue. Make certain your service account has permissions to work in both namespaces (argo and argo-events).</p>
<p>I was trying to setup an elasticsearch cluster in AKS using helm chart but due to the log4j vulnerability, I wanted to set it up with option <code>-Dlog4j2.formatMsgNoLookups</code> set to <code>true</code>. I am getting unknown flag error when I pass the arguments in helm commands. Ref: <a href="https://artifacthub.io/packages/helm/elastic/elasticsearch/6.8.16" rel="noreferrer">https://artifacthub.io/packages/helm/elastic/elasticsearch/6.8.16</a></p> <pre><code>helm upgrade elasticsearch elasticsearch --set imageTag=6.8.16 esJavaOpts &quot;-Dlog4j2.formatMsgNoLookups=true&quot; Error: unknown shorthand flag: 'D' in -Dlog4j2.formatMsgNoLookups=true </code></pre> <p>I have also tried to add below in <code>values.yaml</code> file</p> <pre><code>esConfig: {} # elasticsearch.yml: | # key: # nestedkey: value log4j2.properties: | -Dlog4j2.formatMsgNoLookups = true </code></pre> <p>but the values are not adding to the <code>/usr/share/elasticsearch/config/jvm.options</code>, <code>/usr/share/elasticsearch/config/log4j2.properties</code> or in the environment variables.</p>
<p>First of all, here's a good source of knowledge about mitigating <a href="https://xeraa.net/blog/2021_mitigate-log4j2-log4shell-elasticsearch/" rel="nofollow noreferrer">Log4j2 security issue</a> if this is the reason you reached here.</p> <p>Here's how you can write your <code>values.yaml</code> for the Elasticsearch chart:</p> <pre><code>esConfig: log4j2.properties: | logger.discovery.name = org.elasticsearch.discovery logger.discovery.level = debug </code></pre> <p>A ConfigMap will be generated by Helm:</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: elasticsearch-master-config ... data: log4j2.properties: | logger.discovery.name = org.elasticsearch.discovery logger.discovery.level = debug </code></pre> <p>And the Log4j configuration will be mount to your Elasticsearch as:</p> <pre><code>... volumeMounts: ... - name: esconfig mountPath: /usr/share/elasticsearch/config/log4j2.properties subPath: log4j2.properties </code></pre> <p><strong>Update:</strong> How to set and add multiple configuration files.</p> <p>You can setup other ES configuration files in your <code>values.yaml</code>, all the files that you specified here will be part of the ConfigMap, each of the files will be mounted at <code>/usr/share/elasticsearch/config/</code> in the Elasticsearch container. Example:</p> <pre><code>esConfig: elasticsearch.yml: | node.master: true node.data: true log4j2.properties: | logger.discovery.name = org.elasticsearch.discovery logger.discovery.level = debug jvm.options: | # You can also place a comment here. -Xmx1g -Xms1g -Dlog4j2.formatMsgNoLookups=true roles.yml: | click_admins: run_as: [ 'clicks_watcher_1' ] cluster: [ 'monitor' ] indices: - names: [ 'events-*' ] privileges: [ 'read' ] field_security: grant: ['category', '@timestamp', 'message' ] query: '{&quot;match&quot;: {&quot;category&quot;: &quot;click&quot;}}' </code></pre> <p><strong>ALL of the configurations above are for illustration only to demonstrate how to add multiple configuration files in the values.yaml. Please substitute these configurations with your own settings.</strong></p>
<p>I have a Problem with the Kubernetes Dashboard. I use actually the Managed Kubernetes Service AKS and created a Kubernetes Cluster with following Setup:</p> <ul> <li>Kubernetes-Version 1.20.9</li> <li>1 Worker Node with Size Standard_DS2_v2</li> </ul> <p>It starts successfully with the automatic configuration of <strong>coredns</strong>, <strong>corednsautoscaler</strong>, <strong>omsagent-rs</strong>, <strong>tunnelfront</strong> and the <strong>metrics-sever</strong>.</p> <p>After that i applied three deployments for my services, which all are deployed successfully.</p> <p>Now, i want to get access to the Kubernetes Dashboard. I used the instruction which is described on <a href="https://artifacthub.io/packages/helm/k8s-dashboard/kubernetes-dashboard" rel="nofollow noreferrer">https://artifacthub.io/packages/helm/k8s-dashboard/kubernetes-dashboard</a>.</p> <p>After that I call <strong>kubectl proxy</strong> to access the dashboard via the url: <a href="http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/." rel="nofollow noreferrer">http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/.</a></p> <p>After i use my kubeconfig-File to Sign to Kubernetes Dashboard i get following output and nor cpu neither memory usage is displayed.</p> <p><a href="https://i.stack.imgur.com/coSnY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/coSnY.png" alt="enter image description here" /></a></p> <p>When i execute kubectl describe kubernetes-dashboard pod i get following: <a href="https://i.stack.imgur.com/FUus0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FUus0.png" alt="enter image description here" /></a></p> <p>And the logs from the pod say following:</p> <pre><code>Internal error occurred: No metric client provided. Skipping metrics. 2021/12/11 19:23:04 [2021-12-11T19:23:04Z] Outcoming response to 127.0.0.1:43392 with 200 status code 2021/12/11 19:23:04 Internal error occurred: No metric client provided. Skipping metrics. 2021/12/11 19:23:04 [2021-12-11T19:23:04Z] Outcoming response to 127.0.0.1:43392 with 200 status code 2021/12/11 19:23:04 Internal error occurred: No metric client provided. Skipping metrics. </code></pre>
<p><code>... I used the instruction which is described on https://artifacthub.io/packages/helm/k8s-dashboard/kubernetes-dashboard.</code></p> <p>The dashboard needs a way to &quot;cache&quot; a small window of metrics collected from the metrics server. The instruction provided there doesn't have this enabled. You can run the following to install/upgrade kubernetes-dashboard with metrics scraper enabled:</p> <pre><code>helm upgrade -i kubernetes-dashboard/kubernetes-dashboard --name my-release \ --set=service.externalPort=8080,resources.limits.cpu=200m,metricsScraper.enabled=true </code></pre>
<p>I find it &quot;a bit&quot; boring to create K8s manifests for services that I want to deploy. Typically, for an app, a set of manifests as follows is needed:</p> <ul> <li>deployment</li> <li>service</li> <li>ingress</li> <li>configMap</li> <li>secret</li> </ul> <p>I think there must be some tool that automates the generation of such templates, probably some CLI program that goes through a series of questions-and-answers to generate final manifests. I would imagine that it could also be a bit framework-specific, so it'd be able to generate configMaps based on .NET's <code>appsetting.json</code> or node's <code>.env</code> files.</p> <p>I tries to find something like that on Google, but possibly I'm using wrong keywords. Is there anything as I described?</p>
<h2>Solution 1</h2> <p>Kubernetes supports generating manifests for some resource types. Here is the full list: <a href="https://kubernetes.io/docs/reference/kubectl/conventions/#generators" rel="nofollow noreferrer">https://kubernetes.io/docs/reference/kubectl/conventions/#generators</a></p> <p>You can get the usage of each resource by;</p> <pre><code>kubectl create &lt;resource-name&gt; -h </code></pre> <p>Then you can use;</p> <pre><code>kubectl create --dry-run=client -o yaml &lt;resource-name&gt; [ARGS] </code></pre> <p>Such as for deployment;</p> <pre><code>kubectl create --dry-run=client -o yaml deployment NAME --image=image </code></pre> <p>eg:</p> <pre><code>$ kubectl create --dry-run=client -o yaml deploy nginx-deploy --image nginx apiVersion: apps/v1 kind: Deployment metadata: creationTimestamp: null labels: app: nginx-deploy name: nginx-deploy spec: replicas: 1 selector: matchLabels: app: nginx-deploy strategy: {} template: metadata: creationTimestamp: null labels: app: nginx-deploy spec: containers: - image: nginx name: nginx resources: {} status: {} </code></pre> <h2>Solution 2</h2> <p>If you need more sophisticated solution, you can have a look at Helm, Kustomize and Ansible Operator.</p> <p>Some further information for each:</p> <p>Helm:<br /> <a href="https://helm.sh/docs/intro/quickstart" rel="nofollow noreferrer">https://helm.sh/docs/intro/quickstart</a></p> <p>Kustomize:<br /> <a href="https://kustomize.io" rel="nofollow noreferrer">https://kustomize.io</a></p> <p>Ansible Operator:<br /> <a href="https://sdk.operatorframework.io/docs/building-operators/ansible/tutorial" rel="nofollow noreferrer">https://sdk.operatorframework.io/docs/building-operators/ansible/tutorial</a></p>
<p>When an application needs to call events API to get all events of its cluster, as a programmer I may define a role like this:</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: pod-reader rules: - apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group resources: [&quot;events&quot;] verbs: [&quot;list&quot;] </code></pre> <p>What makes me confusing is the <code>apiGroups</code> part, I can use &quot;events.k8s.io&quot;, or simply &quot;&quot;, or &quot;events.k8s.io&quot; and &quot;&quot; both...</p> <p>What is this apiGroups thing? I tried to read official documentation but all I found is this:</p> <pre><code>API groups make it easier to extend the Kubernetes API. The API group is specified in a REST path and in the apiVersion field of a serialized object. There are several API groups in Kubernetes: The core (also called legacy) group is found at REST path /api/v1. The core group is not specified as part of the apiVersion field, for example, apiVersion: v1. The named groups are at REST path /apis/$GROUP_NAME/$VERSION and use apiVersion: $GROUP_NAME/$VERSION (for example, apiVersion: batch/v1). You can find the full list of supported API groups in the Kubernetes API reference. </code></pre> <p>This doesn't help me understand it... Why there are named groups and core groups, why I can use &quot;&quot; and &quot;events.k8s.io&quot; together?</p> <p>If my resource is <code>events</code>, why do I need to explicitly tell K8s that there is an API group named &quot;events.k8s.io&quot; as if the <code>events</code> in &quot;events.k8s.io&quot; and <code>events</code> in resources are two different things... This question had been haunting me for days😭</p>
<blockquote> <p>Why there are named groups and core groups</p> </blockquote> <p>The reason is historical. Kubernetes first considered some resources part of a core group, meaning the core of Kubernetes is constituted by these resources (resources in the core group includes Pods, Events).</p> <p>The purposes of the named API groups (or namespaces) (such as <code>events.k8s.io</code>) is to group resources by thematic. You'll have <code>networking.k8s.io</code> for resources related to networking.<br /> The &quot;core&quot; resources were considered such an integral part of Kubernetes that they did not need a group (I'm simplifying).</p> <blockquote> <p>why I can use &quot;&quot; and &quot;events.k8s.io&quot; together?</p> </blockquote> <blockquote> <p>If my resource is events, why do I need to explicitly tell K8s that there is an API group named &quot;events.k8s.io&quot; as if the events in &quot;events.k8s.io&quot; and events in resources are two different things...</p> </blockquote> <p>The API is not exactly the same. In the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#event-v1-events-k8s-io" rel="nofollow noreferrer">API reference</a> you can see that in the <code>events.k8s.io</code> you can see some field staring with <code>deprecated</code> which are <code>deprecated field(s) assuring backward compatibility with core.v1 Event type</code>. So depending on which endpoint you use, the API semantic is not exactly the same (but Kubernetes has mechanisms to translate from one version to the other). Since some tools might rely on the core <code>v1</code> version and not yet have migrated to <code>events.k8s.io/v1</code>, both need to exists.</p> <p>There has been other &quot;group migration&quot; of that sort, notably from the <code>extensions</code> group to other group (<code>Ingress</code> migrated to <code>networking.k8s.io</code>, <code>Deployment</code> to <code>apps</code>)</p>
<p>I'm sporting a fresh <strong>Minikube</strong> install on an <strong>ArchLinux</strong> box, using <strong>Docker</strong> as the <strong>Minikube</strong> driver.</p> <p>I started the <strong>minikube</strong> &quot;cluster&quot; using the <code>minikube start</code> command. <code>docker container ls</code> tells us it's up and running:</p> <pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d86070af0c21 gcr.io/k8s-minikube/kicbase:v0.0.28 &quot;/usr/local/bin/entr…&quot; 50 minutes ago Up 50 minutes 127.0.0.1:49162-&gt;22/tcp, 127.0.0.1:49161-&gt;2376/tcp, 127.0.0.1:49160-&gt;5000/tcp, 127.0.0.1:49159-&gt;8443/tcp, 127.0.0.1:49158-&gt;32443/tcp minikube </code></pre> <p>I'm trying to run a simple <strong>nginx</strong> pod, using this command: <code>kubectl run my-nginx --image nginx</code></p> <p>Since I'm pulling a public image from a public repo, I would expect I don't need any authentication. But the <code>describe pod</code> sub-command shows:</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 47s default-scheduler Successfully assigned default/my-nginx to minikube Normal BackOff 31s kubelet Back-off pulling image &quot;nginx&quot; Warning Failed 31s kubelet Error: ImagePullBackOff Normal Pulling 19s (x2 over 46s) kubelet Pulling image &quot;nginx&quot; Warning Failed 4s (x2 over 31s) kubelet Failed to pull image &quot;nginx&quot;: rpc error: code = Unknown desc = Error response from daemon: Get &quot;https://registry-1.docker.io/v2/&quot;: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers) Warning Failed 4s (x2 over 31s) kubelet Error: ErrImagePull </code></pre> <p>When I try to <strong>curl</strong> the URL found in the error message from inside the <strong>minikube</strong> container, it shows that authentication is needed:</p> <pre><code>patres@arch:~$ minikube ssh docker@minikube:~$ curl https://registry-1.docker.io/v2/ {&quot;errors&quot;:[{&quot;code&quot;:&quot;UNAUTHORIZED&quot;,&quot;message&quot;:&quot;authentication required&quot;,&quot;detail&quot;:null}]} </code></pre> <p>When I try to pull that very image from host using <code>docker pull nginx</code> command, the image gets pulled, no auth required.</p> <p>I also tried to create a <strong>kubernetes</strong> secret this way, then launching the pod using YAML with that secret, but it was to no avail.</p> <pre><code>kubectl create secret docker-registry regcred --docker-server=https://registry-1.docker.io/v2/ --docker-username=myusername --docker-password=mypass --docker-email=my@email.com </code></pre> <p>Finally, it seems like the issue might not be unique to <strong>DockerHub</strong>, since if I follow the official <strong>minikubes</strong> <a href="https://minikube.sigs.k8s.io/docs/start/" rel="nofollow noreferrer">documentation</a> and launch the default <code>hello-minikube</code> deployment:</p> <pre><code>kubectl create deployment hello-minikube --image=k8s.gcr.io/echoserver:1.4 </code></pre> <p>I get the same <code>ImagePullBackOff</code> error:</p> <pre><code>$ kubectl get pod hello-minikube-6ddfcc9757-zdzz2 NAME READY STATUS RESTARTS AGE hello-minikube-6ddfcc9757-zdzz2 0/1 ImagePullBackOff 0 6m11s </code></pre>
<p>The problem got resolved by one of these actions (not sure by which exactly):</p> <ul> <li>terminating my VPN connection</li> <li>deleting the <strong>minikube</strong> container and image</li> <li>rebooting my computer</li> <li>starting anew with <code>minikube start</code></li> </ul>
<p>I am working with kubernetes for a long time and I have a question that I am not sure what the answer is.</p> <p>If I create a <code>PersistentVolume</code> and couple of <code>PersistentVolumeClaims</code> that uses that <code>PersistentVolume</code>. I mapped different <code>PersistentVolumeClaims</code> to different pods/containers.</p> <p>Is There a way that one pod could read data that the other pod/container written?</p>
<p><strong>TL;DR:</strong> By mistake - no. By a chain of mistakes - yes.</p> <p>First, PV <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes" rel="nofollow noreferrer">Access Mode</a> need to be set to <code>ReadWriteMany</code>.</p> <p>Then, a specific Volume Plugin have to be used. While Kuberentes supports a lot of different volumes, only few support <code>ReadWriteMany</code> Access Mode.<br /> Those volume types that do support <code>ReadWriteMany</code> can be found in <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes" rel="nofollow noreferrer">this table</a> (scroll down a bit).</p> <p>As far as a container is concerned, PersistentVolume is just a volume mounted in container's filesystem. If you mount it to multiple pods, they will be able to read and write to the same files.</p>
<p>I'm trying to setup my Jenkins instance in our On-premise Kubernetes cluster v1.18.6. Went thru multiple posts on the internet explaining the steps but using nodeport IP and not using the ingress.</p> <p>I'm looking for</p> <ol> <li>Domain under which I want to access Jenkins: <code>jenkins.BU.org.com/jenkins</code>.</li> <li>Master slaves communication using ingress controller. I believe Jenkins uses a custom protocol for communicating with its build agents, being Java RMI, and not HTTP based.</li> </ol> <p>What other extra changes I've to make from my end in addition to the steps mentioned in the below document.</p> <p>Very new to Kubernetes and its dynamics, so any help here would be great for my learning, thanks.</p> <p><a href="https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-kubernetes" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-kubernetes</a></p>
<p>So starting out from bare bones I assume following things:</p> <ul> <li>You have a configured Kubernetes cluster available to you</li> <li>You have the Ingress controller installed in your cluster</li> </ul> <p>First thing to make clear:</p> <blockquote> <p>Workloads which run within the Kubernetes cluster should communicate via Service resources and not Ingress resources.</p> </blockquote> <p>Second thing to keep in mind is:</p> <blockquote> <p>Use Ingress resource to make your workloads reachable from outside of your cluster</p> </blockquote> <p>And lastly since you are hoping to make your Jenkins instance accessible under <code>jenkins.BU.org.com/jenkins</code> then you will have to pick one of the following:</p> <ul> <li>Buy the <code>org.com</code> domain, since <code>jenkins.BU.org.com</code> is a subdomain of <code>org.com</code> domain</li> <li>Setup your own private networking ( out of scope of this question and my knowledge honestly )</li> </ul> <p>So to answer your question you will need to do following things to make your Jenkins instance accessible from outside of the cluster:</p> <ul> <li>Create your Jenkins master Pod with some port open, say 8080</li> <li>Create a Service resource which selects your Pod and forwards the port 80 to port 8080</li> <li>Create an Ingress resource which forwards your desired domain name to your Service onto port 80</li> <li>Create a LoadBalancer service to target your Ingress controller Pods</li> <li>Associate the LoadBalancer service with your actual load balancer ( depending on your environment )</li> <li>Associate your domain name to load balancer IPs for DNS resolution</li> </ul> <p>Another way to solve this would be:</p> <ul> <li>Create your Jenkins master Pod with some port open, say 8080</li> <li>Create a Service resource of type NodePort which selects your Pod and forwards the port 80 to port 8080. This will open a port on your Node, and then you should be able to access your Pod via the IP address of the node.</li> <li>Configure the DNS to resolve your desired domain name to the IP of your node.</li> </ul> <p>I would not recommend second approach, since it would imply making your node available to the internet directly.</p>
<p>We'd like to use <a href="https://github.com/tektoncd/experimental" rel="nofollow noreferrer">Tekton experimental features</a> such as the <a href="https://github.com/tektoncd/experimental/tree/main/pipelines-in-pipelines" rel="nofollow noreferrer">Pipelines In Pipelines feature</a>. We already <a href="https://github.com/tektoncd/experimental/tree/main/pipelines-in-pipelines#install" rel="nofollow noreferrer">installed the feature as described in the README</a> via <code>kubectl apply</code> but end up in an error like this:</p> <pre><code>Pipeline default/buildpacks-test-pipeline can't be Run; it contains Tasks that don't exist: Couldn't retrieve Task &quot;generic-gitlab-set-status&quot;: tasks.tekton.dev &quot;generic-gitlab-set-status&quot; not found </code></pre> <p>In <a href="https://github.com/tektoncd/experimental/issues/785" rel="nofollow noreferrer">this issue</a> it is stated, that we need to enable Tekton alpha features in our deployment. In the Tekton docs at <a href="https://tekton.dev/docs/pipelines/install/#customizing-the-pipelines-controller-behavior" rel="nofollow noreferrer">Customizing the Pipelines Controller behavior</a> all feature flags are described - including the <a href="https://tekton.dev/docs/pipelines/install/#alpha-features" rel="nofollow noreferrer">Alpha Features</a>. The docs state we should change the <code>enable-api-fields:</code> field from <code>stable</code> to <code>alpha</code> if we want to use those features.</p> <p>The recommended way of <a href="https://tekton.dev/docs/pipelines/install/#installing-tekton-pipelines-on-kubernetes" rel="nofollow noreferrer">installing Tekton Pipelines</a> is to use <code>kubectl apply</code> leveraging a remotely served yaml file:</p> <pre><code>kubectl apply --filename https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml </code></pre> <p>Inside we see the <code>ConfigMap</code> <code>feature-flags</code> (shortened):</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: feature-flags namespace: tekton-pipelines labels: app.kubernetes.io/instance: default app.kubernetes.io/part-of: tekton-pipelines data: ... # Setting this flag will determine which gated features are enabled. # Acceptable values are &quot;stable&quot; or &quot;alpha&quot;. enable-api-fields: &quot;stable&quot; ... </code></pre> <p><strong>Is there a way to change the <code>enable-api-fields</code> field to <code>alpha</code> somehow on-the-fly without the need to store</strong> (and in the long run maintain) <strong>the official Tekton pipeline yaml file?</strong></p>
<p>A simple combination of <code>curl</code> which downloads the file and pipes it into <code>sed</code>, which substitutes the <code>stable</code> to <code>alpha</code> works like a charm - especially since this flag is the only line including <code>stable</code> (except of the commentary line directly above). <code>sed</code> is a common tool to <a href="https://stackoverflow.com/a/70152914/4964553">set dynamic values with Kubernetes yaml file</a>.</p> <p>You may test-drive it adding a <code>grep</code> at the end to see the lines changed with:</p> <pre><code>curl https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml | sed &quot;s#stable#alpha#g&quot; | grep enable-api-fields </code></pre> <p>Now combining the command with a final <code>kubectl apply -f -</code> (instead of <code>grep</code>) will do what was asked for:</p> <pre><code>curl https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml | sed &quot;s#stable#alpha#g&quot; | kubectl apply -f - </code></pre> <p>Now the officially released Tekton pipelines yaml is configured to use alpha features on-the-fly - without the need to store and maintain the <code>ConfigMap</code> in a custom git repository for example.</p>
<p>I have a Kubernetes cluster (v. 1.22) and inside it I have Nginx ingress controller deployed. I have found I could <a href="https://kubernetes.github.io/ingress-nginx/how-it-works/#when-a-reload-is-required" rel="noreferrer">reload my ingress</a> in several situations: The next list describes the scenarios when a reload is required:</p> <blockquote> <ul> <li>New Ingress Resource Created.</li> <li>TLS section is added to existing Ingress.</li> <li>Change in Ingress annotations that impacts more than just upstream configuration. For instance load-balance annotation does not require a reload.</li> <li>A path is added/removed from an Ingress.</li> <li>An Ingress, Service, Secret is removed.</li> <li>Some missing referenced object from the Ingress is available, like a Service or Secret.</li> <li>A Secret is updated.</li> </ul> </blockquote> <p>My ingress now using only HTTP traffic and I want to add TLS section to existing Ingress.</p> <p><strong>So, my question is: What should I exactly do to reload my ingress?</strong></p> <p>I cannot find any information in docs or other places. Any suggestion is appreciated!</p>
<blockquote> <p><strong>What should I exactly do to reload my ingress?</strong></p> </blockquote> <p>You just need to update the ingress, in your case you just need to add the TLS section is to existing Ingress.</p> <p>Then (automatically) the ingress controller should find the differences (as <a href="https://stackoverflow.com/users/11344502/anemyte">anemyte</a> says in its answer) and update the ingress. From now on, you will be able to use TLS.</p> <p>In general, this should all happen automatically. In theory, this could also be done manually, although it is not recommended. It is described <a href="https://github.com/kubernetes/ingress-nginx/issues/2612" rel="noreferrer">in this topic</a>.</p> <hr /> <p><strong>EDIT:</strong></p> <p>I have reproduced this situation. First I have created simple ingress with following <code>ingress.yaml</code>:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ing-1 spec: ingressClassName: nginx rules: - host: www.example.com http: paths: - backend: service: name: app-1 port: number: 80 path: / pathType: Prefix </code></pre> <p>Then I have run <code>kubectl get ingress</code> and here is the output:</p> <pre><code>NAME CLASS HOSTS ADDRESS PORTS AGE ing-1 nginx www.example.com 35.X.X.X 80 3m </code></pre> <p>In this step I had working ingress without TLS (only working port 80). Then I have created <code>tls.yaml</code> for TLS (I have used self signed certs, you need to use your certs and domain):</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Secret metadata: name: tls data: tls.crt: | &lt;my cert&gt; tls.key: | &lt;my key&gt; type: kubernetes.io/tls </code></pre> <p>I have run in by <code>kubectl apply -f tls.yaml</code> and then I had changed <code>ingress.yaml</code> as below:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ing-1 spec: ingressClassName: nginx rules: - host: www.example.com http: paths: - backend: service: name: app-1 port: number: 80 path: / pathType: Prefix # This section is only required if TLS is to be enabled for the Ingress tls: - hosts: - www.example.com secretName: tls </code></pre> <p>I have added the TLS section. Then I have run <code>kubectl apply -f ingress.yaml</code> and after few second I could see this output when running <code>kubectl get ingress</code>:</p> <pre><code>NAME CLASS HOSTS ADDRESS PORTS AGE ing-1 nginx www.example.com 35.239.7.126 80, 443 18m </code></pre> <p>TLS is working. In the logs I can see this message:</p> <pre><code>Event(v1.ObjectReference{Kind:&quot;Ingress&quot;, Namespace:&quot;default&quot;, Name:&quot;ing-1&quot;, UID:&quot;84966fae-e135-47bb-8110-bf372de912c8&quot;, APIVersion:&quot;networking.k8s.io/v1&quot;, ResourceVersion:&quot;11306&quot;, FieldPath:&quot;&quot;}): type: 'Normal' reason: 'Sync' Scheduled for sync </code></pre> <p>Ingress reloaded automatically :)</p>
<p>I am following <a href="https://docs.aws.amazon.com/eks/latest/userguide/efs-csi.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/eks/latest/userguide/efs-csi.html</a> to link EFS to EKS. I have two namespace under my k8s clusters: <code>dev</code> and <code>stage</code>, and from I understand, I'd need to have two PersistentVolumeClaims that map to the shared PersistentVolume and StorageClass. So after I ran below 3 commands:</p> <pre><code>kubectl apply -f specs/pv.yaml kubectl apply -f specs/claim.yaml kubectl apply -f specs/storageclass.yaml </code></pre> <p>and from <code>kubectl get sc,pv,pvc1 -n dev</code>, I am able to see all 3 items just fine. However, as I tried to add to <code>stage</code> namespace - <code>kubectl apply -f specs/claim.yaml --namespace=stage</code>, I got below errors as <code>efs-claim</code> becomes stuck in a forever PENDING status:</p> <pre><code>Name: efs-claim Namespace: stage StorageClass: efs-sc Status: Pending Volume: Labels: &lt;none&gt; Annotations: volume.beta.kubernetes.io/storage-provisioner: efs.csi.aws.com Finalizers: [kubernetes.io/pvc-protection] Capacity: Access Modes: VolumeMode: Filesystem Used By: foo-api-stage-chart-12345-abcde foo-api-stage-chart-12345-abcde Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Provisioning 107s efs.csi.aws.com_ip-xxx External provisioner is provisioning volume for claim &quot;stage/efs-claim&quot; Warning ProvisioningFailed 107s efs.csi.aws.com_ip-xxx failed to provision volume with StorageClass &quot;efs-sc&quot;: rpc error: code = InvalidArgument desc = Missing provisioningMode parameter Normal ExternalProvisioning 4s (x8 over 107s) persistentvolume-controller waiting for a volume to be created, either by external provisioner &quot;efs.csi.aws.com&quot; or manually created by system administrator </code></pre> <p>What is causing</p> <blockquote> <p>efs.csi.aws.com_ip-xxx failed to provision volume with StorageClass &quot;efs-sc&quot;: rpc error: code = InvalidArgument desc = Missing provisioningMode parameter</p> </blockquote> <p>I did not have to provide such parameter on <code>dev</code> namespace so why it is required for a different namespace like <code>stage</code>?</p>
<p>To resolve the error that you are seeing, re-apply your StorageClass with:</p> <pre><code>... parameters: provisioningMode: efs-ap fileSystemId: &lt;ID of the file system created on EFS&gt; ... </code></pre> <p>If multiple pods going to read/write to the file system, re-apply PersistentVolume with:</p> <pre><code>... spec: ... accessModes: - ReadWriteMany ... </code></pre> <p>Should the problem persist do post your StorageClass, PersistentVolumeClaim and PersistentVolume spec in your question.</p>
<p>There is a kubernetes cluster with 100 nodes, I have to clean the specific images manually, I know the kubelet garbage collect may help, but it isn't applied in my case. After browsing the internet , I found a solution - docker in docker, to solve my problem.</p> <p>I just wanna remove the image in each node one time, is there any way to run a job in each node one time?</p> <p>I checked the kubernetes labels and podaffinity, but still no ideas, any body could help?</p> <p>Also, I tried to use daemonset to solve the problem, but turns out that it can only remove the image for a part of nodes instead of all nodes, I don't what might be the problem...</p> <p>here is the daemonset example:</p> <pre class="lang-yaml prettyprint-override"><code>kind: DaemonSet apiVersion: apps/v1 metadata: name: test-ds labels: k8s-app: test spec: selector: matchLabels: k8s-app: test template: metadata: labels: k8s-app: test spec: containers: - name: test env: - name: DELETE_IMAGE_NAME value: &quot;nginx&quot; image: busybox command: ['sh', '-c', 'curl --unix-socket /var/run/docker.sock -X DELETE http://localhost/v1.39/images/$(DELETE_IMAGE_NAME)'] securityContext: privileged: true volumeMounts: - mountPath: /var/run/docker.sock name: docker-sock-volume ports: - containerPort: 80 volumes: - name: docker-sock-volume hostPath: # location on host path: /var/run/docker.sock </code></pre>
<p>If you want to run you job on single specific Node you can us the <strong>Nodeselector</strong> in POD spec</p> <pre><code>apiVersion: batch/v1beta1 kind: CronJob metadata: name: test spec: schedule: &quot;*/1 * * * *&quot; jobTemplate: spec: template: spec: containers: - name: test image: busybox args: - /bin/sh - -c - date; echo Hello from the Kubernetes cluster restartPolicy: OnFailure nodeSelector: name: node3 </code></pre> <p>daemon set ideally should resolve your issues, as it creates the PODs on each available Node in the cluster.</p> <p>You can read more about the <strong>affinity</strong> at here : <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/</a></p> <blockquote> <p><strong>nodeSelector</strong> provides a very simple way to constrain pods to nodes with particular labels. The affinity/anti-affinity feature, greatly expands the types of constraints you can express. The key enhancements are</p> <p>The affinity/anti-affinity language is more expressive. The language offers more matching rules besides exact matches created with a logical AND operation;</p> </blockquote> <p>You can use the <strong>Affinity</strong> in Job YAML something like</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: with-node-affinity spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: kubernetes.io/e2e-az-name operator: In values: - e2e-az1 - e2e-az2 preferredDuringSchedulingIgnoredDuringExecution: - weight: 1 preference: matchExpressions: - key: another-node-label-key operator: In values: - another-node-label-value containers: - name: with-node-affinity image: k8s.gcr.io/pause:2.0 </code></pre> <p><strong>Update</strong></p> <p>Now if you have issue with the Deamon affinity with the Job is also useless, as Job will create the Single POD which will get schedule to Single node as per affinity. Either create 100 job with different affinity rules or you use <strong>Deployment</strong> + Affinity to schedule the Replicas on different nodes.</p> <p>We will create one Deployment with <strong>POD affinity</strong> and make sure, <strong>multiple</strong> PODs of a <strong>single</strong> deployment won't get scheduled on <strong>one Node</strong>.</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: test-deployment labels: app: test spec: replicas: 100 selector: matchLabels: app: test template: metadata: labels: app: test spec: containers: - name: test image: &lt;Image&gt; ports: - containerPort: 80 affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: &quot;app&quot; operator: In values: - test topologyKey: &quot;kubernetes.io/hostname&quot; </code></pre> <p>Try using this deployment template and replace your image here. You can reduce <strong>replicas</strong> first to <strong>10</strong> instead of <strong>100</strong> to check it's spreading PODs or not.</p> <p>Read more at : <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#an-example-of-a-pod-that-uses-pod-affinity" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#an-example-of-a-pod-that-uses-pod-affinity</a></p> <p><strong>Extra</strong> :</p> <p>You can also write and use your custom CRD : <a href="https://github.com/darkowlzz/daemonset-job" rel="nofollow noreferrer">https://github.com/darkowlzz/daemonset-job</a> which will behave as <strong>daemon set</strong> and <strong>job</strong></p>
<p>I am trying to use Ansible to put a pause in my playbook, since I am installing an operator from the Operator Hub and don't want to continue, until I know the CRDs I require in the following steps are installed. I have the following task but can't get it working yet.</p> <pre><code>- name: Wait for CRDs to be available command: kubectl get sub my-operator -n openshift-operators -o json register: cmd retries: 10 delay: 5 until: cmd.stdout | json_query('status.conditions[0].status') == true </code></pre> <p>Sample JSON</p> <pre><code>{ &quot;apiVersion&quot;: &quot;operators.coreos.com/v1alpha1&quot;, &quot;kind&quot;: &quot;Subscription&quot;, &quot;metadata&quot;: { &quot;creationTimestamp&quot;: &quot;2021-12-13T04:23:58Z&quot;, &quot;generation&quot;: 1, &quot;labels&quot;: { &quot;operators.coreos.com/argocd-operator.openshift-operators&quot;: &quot;&quot; }, &quot;name&quot;: &quot;argocd-operator&quot;, &quot;namespace&quot;: &quot;openshift-operators&quot;, &quot;resourceVersion&quot;: &quot;58122&quot;, &quot;uid&quot;: &quot;6eaad3c1-8329-4d00-90b8-1ab635b3b370&quot; }, &quot;spec&quot;: { &quot;channel&quot;: &quot;alpha&quot;, &quot;config&quot;: { &quot;env&quot;: [ { &quot;name&quot;: &quot;ARGOCD_CLUSTER_CONFIG_NAMESPACES&quot;, &quot;value&quot;: &quot;argocd&quot; } ] }, &quot;installPlanApproval&quot;: &quot;Automatic&quot;, &quot;name&quot;: &quot;argocd-operator&quot;, &quot;source&quot;: &quot;community-operators&quot;, &quot;sourceNamespace&quot;: &quot;openshift-marketplace&quot;, &quot;startingCSV&quot;: &quot;argocd-operator.v0.1.0&quot; }, &quot;status&quot;: { &quot;catalogHealth&quot;: [ { &quot;catalogSourceRef&quot;: { &quot;apiVersion&quot;: &quot;operators.coreos.com/v1alpha1&quot;, &quot;kind&quot;: &quot;CatalogSource&quot;, &quot;name&quot;: &quot;operatorhubio-catalog&quot;, &quot;namespace&quot;: &quot;olm&quot;, &quot;resourceVersion&quot;: &quot;57924&quot;, &quot;uid&quot;: &quot;95871859-edbc-45ad-885c-3edaad2a1df6&quot; }, &quot;healthy&quot;: true, &quot;lastUpdated&quot;: &quot;2021-12-13T04:23:59Z&quot; } ], &quot;conditions&quot;: [ { &quot;lastTransitionTime&quot;: &quot;2021-12-13T04:23:59Z&quot;, &quot;message&quot;: &quot;targeted catalogsource openshift-marketplace/community-operators missing&quot;, &quot;reason&quot;: &quot;UnhealthyCatalogSourceFound&quot;, &quot;status&quot;: &quot;True&quot;, &quot;type&quot;: &quot;CatalogSourcesUnhealthy&quot; } ], &quot;lastUpdated&quot;: &quot;2021-12-13T04:23:59Z&quot; } } </code></pre>
<p>There is a small detail that is tripping up the condition. In the JSON output, the status is a string <code>&quot;True&quot;</code> and not a boolean which we are comparing.</p> <p>Note: <code>&quot;status&quot;: &quot;True&quot;</code></p> <p>Changing the condition to match the string <code>True</code>...</p> <pre><code>until: cmd.stdout | json_query('status.conditions[0].status') == &quot;True&quot; </code></pre> <p>Or, applying the <code>| bool</code> filter...</p> <pre><code>until: stdout | json_query('status.conditions[0].status') | bool </code></pre> <p>The complete task:</p> <pre class="lang-yaml prettyprint-override"><code>- name: Wait for CRDs to be available command: kubectl get sub my-operator -n openshift-operators -o json register: cmd retries: 10 delay: 5 until: cmd.stdout | json_query('status.conditions[0].status') | bool </code></pre>
<p>Hey I'm trying to get a pipeline to work with kubernetes but I keep getting <code>ErrImagePull</code></p> <p>Earlier I was getting something along the lines <code>authentication failed</code>. I created a secret in the namespace of the pod and referring to it in the deployment file:</p> <pre><code> imagePullSecrets: - name: &quot;registry-secret&quot; </code></pre> <p>I still get <code>ErrImagePull</code> but now for different reasons. When describing the failed pod I get:</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 4m46s default-scheduler Successfully assigned &lt;project&gt; to &lt;server&gt; Normal Pulling 3m12s (x4 over 4m45s) kubelet Pulling image &quot;&lt;container_url&gt;&quot; Warning Failed 3m12s (x4 over 4m45s) kubelet Failed to pull image &quot;&lt;container_url&gt;&quot;: rpc error: code = Unknown desc = Requesting bear token: invalid status code from registry 403 (Forbidden) Warning Failed 3m12s (x4 over 4m45s) kubelet Error: ErrImagePull Warning Failed 3m (x6 over 4m45s) kubelet Error: ImagePullBackOff Normal BackOff 2m46s (x7 over 4m45s) kubelet Back-off pulling image &quot;&lt;container_url&gt;&quot; </code></pre> <p>I guess the Registry is returning 403, but why? Does it mean the user in <code>registry-secret</code> is not allowed to pull the image?</p>
<p>OP has posted in the comment that the problem is resolved:</p> <blockquote> <p>I found the error. So I had a typo and my secret was in fact not created in the correct namespace.</p> </blockquote>
<p>I have an <code>EKS cluster</code> with two <code>nodegroups</code> each in different <code>AZ</code>. One <code>deployment</code> <code>Deployment1</code> is running on 2 <code>namespaces</code> for redundancy, one copy per <code>namespace</code> and each of them run in separate <code>AZs</code>/<code>nodegroup</code>. Also there is another <code>deployment</code> <code>Deployment2</code> that does not have any <code>node affinity</code> set and K8s manages where pods get scheduled. Both <code>deployments</code> are huge with lots of pods. I have a subnet of 250 IPs available to me for each node group.</p> <p>The problem is that while <code>Deployment1</code> is fine on it's own, and gets split almost equally per <code>AZ/Nodegroup</code>, the <code>Deployment2</code> tends to schedule most pods in one of the <code>nodegroups</code> and that ends when there are no more IPs available. This is a problem for <code>Deployment1</code> since one <code>namespace</code> of it is tied to that <code>nodegroup</code> and no new pods can be scheduled there if load changes.</p> <p>Can I somehow balance <code>Deployment2</code> so it has 'soft affinity' that would split it 50/50 per each nodegroup, but if needed, can schedule pods in the other nodegroup?</p>
<p>If you're using Kubernetes 1.19 or later you can use <code>topologySpreadConstraints</code>, adding this to the pod template:</p> <pre><code>topologySpreadConstraints: - maxSkew: 1 topologyKey: topology.kubernetes.io/zone whenUnsatisfiable: ScheduleAnyway labelSelector: matchLabels: foo: bar </code></pre> <p>where <code>maxSkew</code> define how uneven pods can be scheduled, <code>topologyKey</code> is the key of node labels and the <code>labelSelector</code> matches a label of your deployment. See <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-topology-spread-constraints/" rel="nofollow noreferrer">docs</a></p> <p>If your on an older Kubernetes version, you can look at pod anti affinity.</p>
<p>I managed to install kubernetes 1.22, longhorn, kiali, prometheus and istio 1.12 (profile=minimal) on a dedicated server at a hosting provider (hetzner).</p> <p>I then went on to test httpbin with an istio ingress gateway from the istio tutorial. I had some problems making this accessible from the internet (I setup HAProxy to forward local port 80 to the dynamic port that was assigned in kubernetes, so port 31701/TCP in my case)</p> <p>How can I make kubernetes directly available on bare metal interface port 80 (and 443).</p> <p>I thought I found the solution with metallb but I cannot make that work so I think it's not intended for that use case. (I tried to set EXTERNAL-IP to the IP of the bare metal interface but that doesn't seem to work)</p> <p>My HAProxy setup is not working right now for my SSL traffic (with cert-manager on kubernetes) but before I continue looking into that I want to make sure. Is this really how you are suppose to route traffic into kubernetes with an istio gateway configuration on bare metal?</p> <p>I came across <a href="https://stackoverflow.com/questions/51331902/kubernetes-with-istio-ingress-not-running-on-standard-http-ports-443-80">this</a> but I don't have an external Load Balancer nor does my hosting provider provide one for me to use.</p>
<p>Posted community wiki answer for better visibility based on the comment. Feel free to expand it.</p> <hr /> <p>The solution for the issue is:</p> <blockquote> <p>I setup HAProxy in combination with Istio gateway and now it's working.</p> </blockquote> <p>The reason:</p> <blockquote> <p>I think the reason why SSL was not working was because <a href="https://istio.io/latest/docs/setup/additional-setup/gateway/" rel="nofollow noreferrer">istio.io/latest/docs/setup/additional-setup/gateway</a> creates the ingress gateway in a different namespace (<code>istio-ingress</code>) from the rest of the tutorials (<code>istio-system</code>).</p> </blockquote>
<p>Is there a way we can alter the resource names of the resources provisioned by AKS itself (screenshot below). I know I can change the node resource group name as per the documentation but cannot find any reference (or documentation) if we can change the AKS managed resource names. The resources for which I want to have custom naming specifically are:</p> <ol> <li>Load balancer</li> <li>AKS Virtual Machine Scale Set</li> </ol> <p><a href="https://i.stack.imgur.com/H8cSs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H8cSs.png" alt="enter image description here" /></a></p>
<p>You cannot change the resource names of the resources provisioned by AKS itself. Because it is managed by AKS only. you can give your own name of <code>node resource group</code> at the time of creation using IAC tool like <code>Terraform</code>, <code>Biceps</code> etc. But you can’t change the <code>node resource name</code> of AKS once created.</p> <p>From Portal you can not assign your own name of <code>node_resource_group</code></p> <p><strong>Note</strong> : <a href="https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster#node_resource_group" rel="nofollow noreferrer">node_resource_group</a> - (Optional) The name of the Resource Group where the Kubernetes Nodes should exist. Changing this forces a new resource to be created.</p> <p>Azure requires that a new, non-existent Resource Group is used, as otherwise the provisioning of the Kubernetes Service will fail.</p> <p>Please Refer these document : <a href="https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster#node_resource_group" rel="nofollow noreferrer">azurerm_kubernetes_cluster | Resources | hashicorp/azurerm | Terraform Registry</a></p> <p><a href="https://learn.microsoft.com/en-us/azure/templates/microsoft.containerservice/managedclusters?tabs=bicep" rel="nofollow noreferrer">Microsoft.ContainerService/managedClusters - Bicep &amp; ARM template reference | Microsoft Docs</a></p>
<p>We have a k8s cluster with 10 workers. we run hundreds of pods in the cluster. we want to avoid running pods with default service account. Need to find out the pods that are running with default service account. am able to find the number of pods using default service account with grep command but also need the pod name and the image it is using. Let us know your thoughts</p>
<ul> <li>In Case if you want to use just kubectl without jq :</li> </ul> <p>needed to print both namespace and the pod name</p> <pre><code>kubectl get pods --all-namespaces -o jsonpath='{range .items[?(@.spec.serviceAccountName == &quot;default&quot;)]}{.metadata.namespace} {.metadata.name}{&quot;\n&quot;}{end}' 2&gt;/dev/null </code></pre> <ul> <li>i have added 2&gt;/dev/null to avoid printing whole json template in case if no field was found</li> </ul>
<p>Currently, I have one Kubernetes with 2 namespaces: NS1 and NS2. I’m using <code>jboss/keycloak</code> Docker image.</p> <p>I am operating 2 Keycloak instances in those 2 namespaces and I expect that will run independently. But it is not true for Infinispan caching inside Keycloak. I got a problem that all sessions of KC in NS1 will be invalidated many times when the KC pod in NS2 is being stated “Crash Loopback”.</p> <p>The logs said as following whenever the “Crash Loopback” KC pod in NS2 tries to restart:</p> <pre><code>15:14:46,784 INFO [org.infinispan.CLUSTER] (remote-thread--p10-t412) [Context=clientSessions] ISPN100002: Starting rebalance with members [keycloak-abcdef, keycloak-qwerty], phase READ_OLD_WRITE_ALL, topology id 498 </code></pre> <p><code>keycloak-abcdef</code> is the KC pod in NS1 and <code>keycloak-qwerty</code> is the KC pod in NS2. So, the KC pod in NS1 can see and be affected by KC pod from NS2.</p> <p>After researching, I see that Keycloak uses Infinispan cache to manage session data and Infinispan uses JGroups to discover nodes with the default method PING. I am assuming that this mechanism is the root cause of the problem “invalidated session” because it will try to contact other KC pods in the same cluster (even different namespaces) to do something like synchronization.</p> <p>Is there any way that can isolate the working of Infinispan in Keycloak between namespaces?</p> <p>Thank you!</p>
<p>Posting comment as the community wiki answer for better visibility</p> <hr /> <p>I would use <code>JDBC_PING</code> for discovery, so only nodes which are using the same DB will be able to discover each other</p>
<p>I installed Rancher on my Kubernetes cluster on Azure as described <a href="https://rancher.com/docs/rancher/v2.5/en/installation/install-rancher-on-k8s/aks/" rel="nofollow noreferrer">here</a>. I ran the following command:</p> <pre><code>helm install rancher rancher-latest/rancher --namespace cattle-system --set hostname=rancher.mydomain.com --set replicas=1 --set ingress.tls.source=secret --set bootstrapPassword=someRandomPassword </code></pre> <p>Rancher was installed successfully and when I opened the page at rancher.mydomain.com, it showed the admin login page. I tried the password I had used in the previous command but it wouldn't log in. I kept getting the error in the following screenshot:</p> <p><a href="https://i.stack.imgur.com/OKdz5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OKdz5.png" alt="enter image description here" /></a></p>
<p>@Mar Chal</p> <p>Try below command to reset password it will work.</p> <pre><code>[]$ kubectl -n cattle-system exec $(kubectl -n cattle-system get pods -l app=demo-rancher | grep '1/1' | head -1 | awk '{ print $1 }') -- reset-password W1214 11:55:25.230447 127 client_config.go:615] Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work. New password for default admin user (user-zkgpr): oH9ySxxxxxxxxx7q_1767o </code></pre>
<p>I'm using Terraform <code>helm_release</code> resource to install <code>bitnami/redis</code> instance in my K8s cluster.</p> <p>The code looks like this:</p> <pre class="lang-js prettyprint-override"><code>resource &quot;helm_release&quot; &quot;redis-chart&quot; { name = &quot;redis-${var.env}&quot; repository = &quot;https://charts.bitnami.com/bitnami&quot; chart = &quot;redis&quot; namespace = &quot;redis&quot; create_namespace = true set { name = &quot;auth.enabled&quot; value = &quot;false&quot; } set { name = &quot;master.containerPort&quot; value = &quot;6379&quot; } set { name = &quot;replica.replicaCount&quot; value = &quot;2&quot; } } </code></pre> <p>It completes successfully and in a separate directory I have my <code>app</code> terraform configuration. In the <code>app</code> configuration, I want to get get the redis host from the above <code>helm_release</code>.</p> <p>I'm doing it like this:</p> <pre class="lang-js prettyprint-override"><code>data &quot;kubernetes_service&quot; &quot;redis-master&quot; { metadata { name = &quot;redis-${var.env}-master&quot; namespace = &quot;redis&quot; } } </code></pre> <p>And then in the <code>kubernetes_secret</code> resource I'm passing the data to my <code>app</code> deployment:</p> <pre class="lang-js prettyprint-override"><code>resource &quot;kubernetes_secret&quot; &quot;questo-server-secrets&quot; { metadata { name = &quot;questo-server-secrets-${var.env}&quot; namespace = kubernetes_namespace.app-namespace.metadata.0.name } data = { REDIS_HOST = data.kubernetes_service.redis-master.metadata.0.name REDIS_PORT = data.kubernetes_service.redis-master.spec.0.port.0.port } } </code></pre> <p>But unfortunately, when I run the app <code>deployment</code> I'm getting the following logs:</p> <blockquote> <p>[ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND redis-dev-master at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) [ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND</p> </blockquote> <p>Which suggests that <code>redis-dev-master</code> is not a correct host for the <code>redis</code> instance.</p> <p>How do I get the <code>redis</code> host from <code>helm_release</code> or any underlying services the <code>release</code> creates?</p> <p>I've tried debugging and <code>pinging</code> a specific pod from my <code>app</code> deployment.</p> <p>For reference, these are my <code>redis</code> resources:</p> <pre><code>NAME READY STATUS RESTARTS AGE pod/redis-dev-master-0 1/1 Running 0 34m pod/redis-dev-replicas-0 1/1 Running 1 34m pod/redis-dev-replicas-1 1/1 Running 0 32m NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/redis-dev-headless ClusterIP None &lt;none&gt; 6379/TCP 34m service/redis-dev-master ClusterIP 172.20.215.60 &lt;none&gt; 6379/TCP 34m service/redis-dev-replicas ClusterIP 172.20.117.134 &lt;none&gt; 6379/TCP 34m NAME READY AGE statefulset.apps/redis-dev-master 1/1 34m statefulset.apps/redis-dev-replicas 2/2 34m </code></pre>
<p>Maybe you were just using the wrong <code>attribute</code> to get that information. Checking the documentation at the <a href="https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/data-sources/service" rel="nofollow noreferrer">Terraform Registry Website</a> we can use the <code>cluster_ip</code> attribute as described at the <a href="https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/data-sources/service#spec" rel="nofollow noreferrer">spec</a> documentation description. So you should end up with something like:</p> <pre><code>data.kubernetes_service.redis-master.spec.cluster_ip </code></pre> <p>And finally ending up with the following:</p> <pre><code>resource &quot;kubernetes_secret&quot; &quot;questo-server-secrets&quot; { metadata { name = &quot;questo-server-secrets-${var.env}&quot; namespace = kubernetes_namespace.app-namespace.metadata.0.name } data = { REDIS_HOST = data.kubernetes_service.redis-master.spec.cluster_ip REDIS_PORT = data.kubernetes_service.redis-master.spec.port } } </code></pre>
<p>I created a <code>WorkflowTemplate</code> in which I want to pass result of a script template as an input parameter to another task</p> <p>Here is my <code>WorkflowTemplate</code></p> <pre><code>apiVersion: argoproj.io/v1alpha1 kind: WorkflowTemplate metadata: name: dag-wft spec: entrypoint: whalesay templates: - name: whalesay inputs: parameters: - name: message default: '[&quot;tests/hello&quot;, &quot;templates/hello&quot;, &quot;manifests/hello&quot;]' dag: tasks: - name: prepare-lst template: prepare-list-script arguments: parameters: - name: message value: &quot;{{inputs.parameters.message}}&quot; - name: templates depends: prepare-lst templateRef: name: final-dag-wft template: whalesay-final arguments: parameters: - name: fnl_message value: &quot;{{item}}&quot; withParam: &quot;{{tasks.prepare-lst.outputs.parameters.templates_lst}}&quot; - name: manifests depends: prepare-lst &amp;&amp; (templates.Succeeded || templates.Skipped) templateRef: name: final-dag-wft template: whalesay-final arguments: parameters: - name: fnl_message value: &quot;{{item}}&quot; withParam: &quot;{{tasks.prepare-lst.outputs.parameters.manifests_lst}}&quot; - name: prepare-list-script inputs: parameters: - name: message script: image: python command: [python] source: | manifests_lst = [] # templates list preparation templates_lst = ['templates/' for template in &quot;{{inputs.parameters.message}}&quot; if 'templates/' in template] print(templates_lst) # manifests list preparation for i in &quot;{{inputs.parameters.message}}&quot;: if 'templates/' not in i: manifests_lst.append(i) print(manifests_lst) outputs: parameters: - name: templates_lst - name: manifests_lst </code></pre> <p>In the above script template I've added print statement of two variables <code>templates_lst</code> and <code>manifests_lst</code>. I want to pass these two variables result as in input to two other tasks in the dag. The two other tasks are <code>templates</code> and <code>manifests</code></p> <p>The way I am accessing the output values is <code>&quot;{{tasks.prepare-lst.outputs.parameters.templates_lst}}&quot;</code> and <code>&quot;{{tasks.prepare-lst.outputs.parameters.manifests_lst}}&quot;</code>. It is not working</p> <p>How we can I do this?</p>
<p><strong>1. Fully define your output parameters</strong></p> <p>Your output parameter spec is incomplete. You need to specify <em>where</em> the output parameter comes from.</p> <p>Since you have multiple output parameters, you can't just use standard out (<code>{{tasks.prepare-lst.outputs.parameters.result}}</code>). You have to write two files and derive an output parameter from each.</p> <p><strong>2. Load the JSON array so it's iterable</strong></p> <p>If you iterate over the string representation of the array, you'll just get one character at a time.</p> <p><strong>3. Use an environment variable to pass input to Python</strong></p> <p>Although it's not strictly necessary, I consider it best practice. If a malicious actor had the ability to set the <code>message</code> parameter, they could inject Python into your workflow. Pass the parameter as an environment variable so the string remains a string.</p> <p><strong>Changes:</strong></p> <pre><code> - name: prepare-list-script inputs: parameters: - name: message script: image: python command: [python] + env: + - name: MESSAGE + value: &quot;{{inputs.parameters.message}}&quot; source: | + import json + import os + message = json.loads(os.environ[&quot;MESSAGE&quot;]) manifests_lst = [] # templates list preparation - templates_lst = ['templates/' for template in &quot;{{inputs.parameters.message}}&quot; if 'templates/' in template] + templates_lst = ['templates/' for template in message if 'templates/' in template] - print(templates_lst) + with open('/mnt/out/templates_lst.txt', 'w') as outfile: + outfile.write(str(json.dumps(templates_lst))) # manifests list preparation for i in &quot;{{inputs.parameters.message}}&quot;: if 'templates/' not in i: manifests_lst.append(i) - print(manifests_lst) + with open('/mnt/out/manifests_lst.txt', 'w') as outfile: + outfile.write(str(json.dumps(manifests_lst))) + volumeMounts: + - name: out + mountPath: /mnt/out + volumes: + - name: out + emptyDir: { } outputs: parameters: - name: templates_lst + valueFrom: + path: /mnt/out/templates_lst.txt - name: manifests_lst + valueFrom: + path: /mnt/out/manifests_lst.txt </code></pre>
<p>I have created a cluster on GCE and I am trying to register that in GKE console. </p> <p>I have created a service account with the roles:</p> <p><strong>roles/owner, roles/editor, roles/gkehub.connect</strong></p> <p>But, when I try to register my remote-cluster on GKE console, I am getting below error. Cloud someone help me to get out of this?</p> <p><em>gcloud container hub memberships register remote-cluster --context=remote-cluster --service-account-key-file=./workdir/gkehub-7c3ea7087141.json</em></p> <p><strong>ERROR: (gcloud.container.hub.memberships.register) Failed to check if the user is a cluster-admin: Unable to connect to the server: context deadline exceeded (Client.Timeout exceeded while awaiting headers)</strong></p> <p>Thanks in advance! </p>
<p>Install this sdk plugin solved my problem.</p> <pre><code>sudo apt-get install google-cloud-sdk-gke-gcloud-auth-plugin </code></pre>
<p><strong>skaffold.yaml</strong></p> <pre><code>apiVersion: skaffold/v2alpha3 kind: Config deploy: kubectl: manifests: - ./infra/k8s/* build: local: push: false artifacts: - image: karan346/auth context: auth docker: dockerfile: Dockerfile sync: manual: - src: 'src/**/*.ts' des: . </code></pre> <p><strong>Error</strong></p> <pre><code>parsing skaffold config: error parsing skaffold configuration file: unable to parse config: yaml: unmarshal errors: line 10: field des not found in type v2alpha3.SyncRule </code></pre> <p>Not able to fix the issue. Everything is setup correctly.</p> <p>Also, is there any version that is stable and won't give errors in the future?</p>
<p>Error you're facing is:</p> <pre><code>line 10: field des not found in type v2alpha3.SyncRule </code></pre> <p>There's no field <code>des</code> in these <code>api</code> and <code>kind</code>.</p> <p>Based on the <a href="https://skaffold.dev/docs/pipeline-stages/filesync/#manual-sync-mode" rel="nofollow noreferrer">documentation for manual file sync</a>, field should be named as <code>dest</code>. See the example below:</p> <pre><code>build: artifacts: - image: gcr.io/k8s-skaffold/node-example context: node sync: manual: # sync a single file into the `/etc` folder - src: '.filebaserc' dest: /etc </code></pre> <hr /> <p>Last available <code>apiVersion</code> of <code>skaffold</code> at the moment of posting the answer is <code>skaffold/v2beta26</code>.</p> <p>It's always can be checked on <a href="https://skaffold.dev/docs/references/yaml/" rel="nofollow noreferrer">skaffold.yaml documentation</a></p>
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>version</th> </tr> </thead> <tbody> <tr> <td>Java</td> <td>1.8.0_242-b08</td> </tr> <tr> <td>Spark</td> <td>2.4.5</td> </tr> <tr> <td>Zeppelin</td> <td>0.10.0</td> </tr> </tbody> </table> </div> <p>Inside a k8s Pod, with above set, web ui running, I opened Zeppelin's spark interpreter and ran <code>sc</code>. Following Error prints out:</p> <pre><code>io.fabric8.kubernetes.client.KubernetesClientException: Operation: [create] for kind: [Pod] with name: [null] in namespace: [default] failed. </code></pre> <p>Besides that it's not working, what I don't understand is whether Zeppelin use k8s and how.</p> <p>Did some searching. <code>fabric8</code> seems to be related to k8s and I suppose Zeppelin tries to run its interpreters in k8s cluster. Yet, k8s is not installed (?... like <code>kubectl</code>?) in the machine (where Zeppelin is running). So there are two explanation I can think of:</p> <ol> <li><code>fabric8</code> include k8s so Zeppelin creates local k8s cluster to run its interpreters.</li> <li>Zeppelin somehow detected it's been run in k8s Pod and tries to use that Cluster to create Pod, run interpreters in it.</li> </ol> <p>Think the first explanation is the correct one. But running local k8s cluster under the hood feels... how? Error itself was solved by using different versions: Spark 2.4.0, Zeppelin 0.8.2, yet would be nice if I could use up-to-date Spark and Zeppelin.</p> <p>And in addition, the error itself seems to be related with <a href="https://github.com/fabric8io/kubernetes-client/issues/2145" rel="nofollow noreferrer">specific Java version</a>.</p>
<p>Found out Zeppelin has a parameter ZEPPELIN_RUN_MODE. By default it is set as &quot;auto&quot;. If you are running Zeppelin in a Pod and don't want to run within k8s sidecar, you should set it &quot;local&quot;.</p>
<p>I use <strong>Kubernetes</strong> in my project, specially <strong>HPA</strong>. So, every minute in project we started <code>check-status</code> request for checking if all microservices are available. Availability is defined by simple response from one of replicas (not all) each microservice. <br /> But I have one moment related to HPA. When HPA automatically decides to remove some pods from cluster and my <code>check-status</code> request comes to server at the same time then very often occurs that my API-gateway service push it to deleted pod and doesn't get any response. It means that microservice is unavailable for our server.<br /> My question is what is the best way for setting autoscaler to avoid this cases.</p>
<p>It is not related to HPA in this case but more on how you graceful shut down your pods.</p> <p>In short, your service/LB is not aware if your pod is ready to accept new requests, so on a <code>SIGTERM</code> signal, your pod should set your <code>readiness probe</code> to false, and give some time for the app to shutdown. If your readiness probe is not healthy, the service won't send new requests to your pod. Then you can shut it down once all requests have been addressed AND the pod won't receive new requests.</p> <p>I would advise you of reading these sources:</p> <ul> <li><a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace" rel="nofollow noreferrer">https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace</a></li> <li><a href="https://pracucci.com/graceful-shutdown-of-kubernetes-pods.html" rel="nofollow noreferrer">https://pracucci.com/graceful-shutdown-of-kubernetes-pods.html</a></li> </ul>
<p>Creating a mongodb from the below <strong>minikube</strong> deployment, I am not able to authenticate from the command line.</p> <p>Basically I'd just want to list all databases because I suspect there is an issue with the connectivity to mongo-express.</p> <p>I exec into the pod using <code>kubectl exec -it mongodb-deployment-6b46455744-gfkzw -- /bin/bash</code>,</p> <p><code>mongo</code> to start up the cli</p> <p><code>db.auth(&quot;username&quot;, &quot;password&quot;)</code> gives <code>MongoServerError: Authentication failed.</code></p> <p>even though <code>printenv</code> gives</p> <pre><code>MONGO_INITDB_ROOT_PASSWORD=password MONGO_INITDB_ROOT_USERNAME=username </code></pre> <p>any help?</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: mongodb-deployment labels: app: mongodb spec: replicas: 1 selector: matchLabels: app: mongodb template: metadata: labels: app: mongodb spec: containers: - name: mongodb image: mongo ports: - containerPort: 27017 env: - name: MONGO_INITDB_ROOT_USERNAME valueFrom: secretKeyRef: name: mongodb-secret key: mongo-root-username - name: MONGO_INITDB_ROOT_PASSWORD valueFrom: secretKeyRef: name: mongodb-secret key: mongo-root-password - name: ME_CONFIG_MONGODB_ENABLE_ADMIN value: &quot;true&quot; --- apiVersion: v1 kind: Service metadata: name: mongodb-service spec: selector: app: mongodb ports: - protocol: TCP port: 27017 targetPort: 27017 </code></pre>
<p>managed to connect using</p> <pre><code>mongosh --port 27017 --authenticationDatabase \ &quot;admin&quot; -u &quot;myUserAdmin&quot; -p </code></pre> <p>from <a href="https://docs.mongodb.com/manual/tutorial/authenticate-a-user/#std-label-authentication-auth-as-user" rel="nofollow noreferrer">https://docs.mongodb.com/manual/tutorial/authenticate-a-user/#std-label-authentication-auth-as-user</a> and docker hub page.</p>
<p>I'm building an API than enable users to stream (push) large content through HTTP and I would like to be able to process the request from a nodejs express server <strong>while the client is still pushing</strong>.</p> <p><em>client.js</em></p> <pre class="lang-js prettyprint-override"><code>const request = require('request'); someReadableStream.pipe(request({ method: &quot;POST&quot;, uri: `${process.env.SERVER_URL || &quot;https://streaming.service.com/&quot;}/`, headers: { 'Authorization': `Bearer ${API_TOKEN}`, }, })); </code></pre> <p><em>server.js</em></p> <pre class="lang-js prettyprint-override"><code>const express = require('express'); const app = express(); app.post('/', function rootPostHandler(req, res) { console.log('request received'); const tickInterval = setInterval(() =&gt; console.log('tick'), 1000); req.on('data', (chunk) =&gt; console.log('data received')); req.on('end', () =&gt; { console.log('request end received'); clearInterval(tickInterval); res.end('done') }); }); app.listen(process.env.PORT); </code></pre> <p>Everything works as expected on my development server: server receives data and can start processing it while client is still pushing (see per-second <code>tick</code>s in output below).</p> <p><em>dev server output:</em></p> <pre><code>request received data received data received data received tick data received data received data received tick data received data received data received tick data received data received request end received </code></pre> <p>Now, when we deploy the same server code to our kubernetes cluster, initial experiments suggest that <a href="https://kubernetes.github.io/ingress-nginx/" rel="nofollow noreferrer">Nginx Ingress</a> (or some other K8s component) wait the request to be completed before sending it to the underlying HTTP service (no <code>tick</code> in output below).</p> <p><em>server pod logs</em></p> <pre><code>request received data received data received data received data received data received data received data received data received data received data received data received request end received </code></pre> <p><em>kubernetes config</em></p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress labels: tier: ingress annotations: kubernetes.io/ingress.class: &quot;nginx&quot; cert-manager.io/cluster-issuer: &quot;issuer&quot; nginx.ingress.kubernetes.io/proxy-body-size: 30720m nginx.ingress.kubernetes.io/proxy-connect-timeout: &quot;180&quot; nginx.ingress.kubernetes.io/proxy-read-timeout: &quot;180&quot; nginx.ingress.kubernetes.io/proxy-send-timeout: &quot;180&quot; nginx.ingress.kubernetes.io/enable-cors: &quot;true&quot; nginx.ingress.kubernetes.io/cors-allow-origin: &quot;*&quot; nginx.ingress.kubernetes.io/configuration-snippet: | proxy_pass_request_headers on; spec: ingressClassName: nginx tls: - hosts: - streaming.service.com secretName: streaming-tls rules: - host: streaming.service.com http: paths: - path: / pathType: Prefix backend: service: name: streaming port: number: 80 --- apiVersion: v1 kind: Service metadata: name: streaming labels: app: streaming spec: type: ClusterIP clusterIP: None sessionAffinity: ClientIP ports: - port: 80 selector: app: streaming </code></pre> <p><strong>Question:</strong> Is here a way to tell nginx-ingress to forward bytes to underlying HTTP service as they arrive, through <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/" rel="nofollow noreferrer">annotations</a> or <a href="https://docs.nginx.com/nginx-ingress-controller/configuration/ingress-resources/advanced-configuration-with-snippets/" rel="nofollow noreferrer">snippets</a> for example ?</p>
<p><strong>Answering to my own question</strong> since it may help others</p> <p>All you have to do is to add <code>nginx.ingress.kubernetes.io/proxy-request-buffering: &quot;off&quot;</code> annotation</p> <p><em>New Ingress configuration</em></p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-stream labels: name: ingress-stream tier: ingress annotations: nginx.ingress.kubernetes.io/proxy-request-buffering: &quot;off&quot; # here spec: ingressClassName: nginx rules: - host: streaming.service.com http: paths: - path: / pathType: Prefix backend: service: name: streaming port: number: 80 </code></pre>
<p>I am able to mount different directories to the same container at different mount points using <code>volumeMounts.subPath</code> attribute.</p> <p>Is it OK to use this in production environment? I am using <code>AWS EFS</code> as my persistent storage.</p> <p><a href="https://kubernetes.io/docs/concepts/storage/volumes/#using-subpath" rel="nofollow noreferrer">This</a> doc says it is not recommended. What is the concern if this is used?</p>
<h2>Short answer</h2> <p>It's absolutely fine to use the <code>subPath</code> in production</p> <h2>Detailed answer</h2> <p><strong>Kubernetes example with <code>subPath</code> used.</strong></p> <p>What this phrase &quot;This sample subPath configuration is not recommended for production use.&quot; means is exactly this sample is not recommended, not the <code>subPath</code> usage.</p> <p>The example contains frontend and backend applications' containers in a single pod which is fundamentally wrong approach for production usage (for testing it's applicable).</p> <p>In production frontend and backend applications should be separated to different deployments, it will allow:</p> <ul> <li>manage front and back end applications separately</li> <li>fault tolerance - in single pod if one of the app crashes, the whole pod is affected</li> <li>pod are disposable units and for databases separate set of pods should be used (like statefulset), it allows to maintain sticky sessions and data persistence even if pod crashed</li> </ul> <p><strong><code>subPath</code> vulnerabilities</strong></p> <p>First it's a good idea to figure out <a href="https://kubernetes.io/blog/2018/04/04/fixing-subpath-volume-vulnerability/#kubernetes-background" rel="nofollow noreferrer">how <code>subPath</code> works</a> to understand what risks/vulnerabilities can be introduced.</p> <p>I found at least two ones:</p> <ul> <li><a href="https://github.com/kubernetes/kubernetes/issues/60813" rel="nofollow noreferrer">CVE-2017-1002101</a></li> <li><a href="https://github.com/kubernetes/kubernetes/issues/104980" rel="nofollow noreferrer">CVE-2021-25741</a></li> </ul> <p>Both are fixed as for today. It's very important to use last available versions which contain fixes for different issues (including both mentioned above).</p> <p>Since kubernetes developers fix vulnerabilities related to <code>subPath</code> it can be safely used in production clusters.</p>
<h3>Setup</h3> <p>I'm playing around with K8s and I set up a small, single-node, bare metal cluster. For this cluster I pulled the NGINX Ingress Controller config <a href="https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/cloud/deploy.yaml" rel="nofollow noreferrer">from here</a>, which is coming from the <a href="https://kubernetes.github.io/ingress-nginx/deploy/" rel="nofollow noreferrer">official getting started guide</a>.</p> <h3>Progress</h3> <p>Ok, so pulling this set up a bunch of things, including a LoadBalancer in front. I like that.</p> <p>For my app <em>(single pod, returns the caller IP)</em> I created a bunch of things to play around with. I now have SSL enabled and another ingress controller, which I pointed to my app's service, which then points to the deployed pod. This all works perfectly, I can browse the page with https. See:</p> <p><a href="https://i.stack.imgur.com/ufKt8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ufKt8.png" alt="Cluster setup" /></a></p> <h2>BUT...</h2> <p>My app is not getting <strong>the original IP from the client</strong>. All client requests end up as coming from 10.42.0.99... here's the controller config from <code>describe</code>:</p> <p><a href="https://i.stack.imgur.com/dsDvz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dsDvz.png" alt="Ingress Controller config" /></a></p> <h3>Debugging</h3> <p>I tried like <a href="https://www.google.com/search?q=nginx-ingress+load+balancer+get+real+IP" rel="nofollow noreferrer">50 solutions</a> that were proposed online, none of them worked (ConfigMaps, annotations, proxy mode, etc). And I debugged in-depth, there's no <code>X-Forwarder-For</code> or any similar header in the request that reaches the pod. Previously I tested the same app on apache directly, and also in a docker setup, it works without any issues.</p> <p>It's also worth mentioning that I looked into the ingress controller's pod and I already saw the same internal IP in there. I don't know how to debug the controller's pod further.</p> <p>Happy to share more information and config if it helps.</p> <h3>UPDATE 2021-12-15</h3> <p>I think I know what the issue is... I didn't mention how I installed the cluster, assuming it's irrelevant. Now I think it's the most important thing 😬</p> <p>I set it up <a href="https://rancher.com/docs/k3s/latest/en/networking/#how-the-service-lb-works" rel="nofollow noreferrer">using K3S</a>, which has <a href="https://github.com/k3s-io/klipper-lb" rel="nofollow noreferrer">its own LoadBalancer</a>. And through debugging, I see now that all of my requests in NGINX have the IP of the load balancer's pod...</p> <p>I still don't know how to make this Klipper LB give the source IP address though.</p> <h3>UPDATE 2021-12-17</h3> <p>Opened <a href="https://github.com/k3s-io/klipper-lb/issues/31" rel="nofollow noreferrer">an issue</a> with the Klipper LB.</p>
<p>Make sure your Nginx ingress configmap have enabled user IP <code>real-ip-header: proxy_protocol</code> try updating this line into configmap.</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: labels: app.kubernetes.io/component: controller name: ingress-nginx-controller namespace: ingress-nginx data: compute-full-forwarded-for: &quot;true&quot; use-forwarded-headers: &quot;false&quot; real-ip-header: proxy_protocol </code></pre> <p>still if that not work you can just inject this config as annotation your ingress configuration and test once.</p> <pre><code>nginx.ingress.kubernetes.io/configuration-snippet: | more_set_headers &quot;X-Forwarded-For $http_x_forwarded_for&quot;; </code></pre>
<p>I want to write a script to health check our elasticsearch cluster (deploy on kubernetes)</p> <ol> <li>I go inside pod which run elasticsearch master container and run below commands:</li> </ol> <pre><code>[elasticsearch@elasticsearch-master-0 ~]$ curl localhost:9200/frontend-dev-2021.12.03/_count {&quot;count&quot;:76,&quot;_shards&quot;:{&quot;total&quot;:1,&quot;successful&quot;:1,&quot;skipped&quot;:0,&quot;failed&quot;:0}} [elasticsearch@elasticsearch-master-0 ~]$ curl localhost:9200/_cluster/health?pretty { &quot;cluster_name&quot; : &quot;elasticsearch&quot;, &quot;status&quot; : &quot;green&quot;, &quot;timed_out&quot; : false, &quot;number_of_nodes&quot; : 3, &quot;number_of_data_nodes&quot; : 3, &quot;active_primary_shards&quot; : 617, &quot;active_shards&quot; : 1234, &quot;relocating_shards&quot; : 0, &quot;initializing_shards&quot; : 0, &quot;unassigned_shards&quot; : 0, &quot;delayed_unassigned_shards&quot; : 0, &quot;number_of_pending_tasks&quot; : 0, &quot;number_of_in_flight_fetch&quot; : 0, &quot;task_max_waiting_in_queue_millis&quot; : 0, &quot;active_shards_percent_as_number&quot; : 100.0 } </code></pre> <p>As you can see, both index count and health check command are success. But when I run these command from outside (I give elasticsearch cluster an public endpoint)</p> <pre><code>root@ip-192-168-1-1:~# curl --user username:password esdev.example.com/frontend-dev-2021.12.03/_count {&quot;count&quot;:76,&quot;_shards&quot;:{&quot;total&quot;:1,&quot;successful&quot;:1,&quot;skipped&quot;:0,&quot;failed&quot;:0}} root@ip-192-168-1-1:~# curl --user username:password esdev.example.com/_cluster/health &lt;html&gt; &lt;head&gt;&lt;title&gt;403 Forbidden&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;center&gt;&lt;h1&gt;403 Forbidden&lt;/h1&gt;&lt;/center&gt; &lt;hr&gt;&lt;center&gt;nginx&lt;/center&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Only the index count command is success, the health check command always produce <code>403 Forbidden</code> error.</p> <p>I have searched and read through the official <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html" rel="nofollow noreferrer">docs</a> from elasticsearch but event the offcial docs only run command internal elasticsearch cluster or using kibana (http service kubernetes - internal k8s cluster).</p> <p>How can I health check elasticsearch from outside? Or we can not do this because some mechanism of elasticsearch cluster?</p> <p>Notes: I create a basic auth nginx (username:password) stand before the elasticsearch and this nginx has an ingressroute from traefik-v2</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: annotations: meta.helm.sh/release-name: basic-auth-nginx-dev meta.helm.sh/release-namespace: dev creationTimestamp: &quot;2021-01-23T08:12:55Z&quot; generation: 2 labels: app: basic-auth-nginx-dev app.kubernetes.io/managed-by: Helm managedFields: - apiVersion: traefik.containo.us/v1alpha1 fieldsType: FieldsV1 fieldsV1: f:metadata: f:annotations: .: {} f:meta.helm.sh/release-name: {} f:meta.helm.sh/release-namespace: {} f:labels: .: {} f:app: {} f:app.kubernetes.io/managed-by: {} f:spec: .: {} f:entryPoints: {} f:routes: {} manager: Go-http-client operation: Update time: &quot;2021-01-23T08:12:55Z&quot; name: basic-auth-nginx-dev-web namespace: dev resourceVersion: &quot;103562796&quot; selfLink: /apis/traefik.containo.us/v1alpha1/namespaces/dev/ingressroutes/basic-auth-nginx-dev-web uid: 5832b501-b2d7-4600-93b6-b3c72c420115 spec: entryPoints: - web routes: - kind: Rule match: Host(`esdev.example.com`) &amp;&amp; PathPrefix(`/`) priority: 1 services: - kind: Service name: basic-auth-nginx-dev port: 80 </code></pre>
<p>Could you please show us your nginx config?</p> <ol> <li><p>I think the problem come from your nginx because I see the output you show that nginx return 403 for you, not the elasticsearch.</p> </li> <li><p>Could you please try another command start with <code>_</code> like <code>_template</code> or something like that, there is a chance your nginx prevent access to path start with <code>_</code> character.</p> </li> </ol>
<p>How would I start a specific number of replicas of the same image, when that number is defined at startup?</p> <p>On startup I need to call an API endpoint which returns a number. I then want to use this number to deploy that number of replicas of a pod (with each pod being aware of what order it was started in, even after restarts, etc).</p> <p>For example the API endpoint returns 15, and 15 replicas are started with each having an 'order' / index number of 1 - 15, and maintaining always having a single pod with an 'order' number for each number between 1-15.</p> <p>I was thinking of using an init container to call the API endpoint, I can't find how to then start that number of replicas and pass the 'order' to the pod.</p>
<p>Your problem can be solved in several ways. You can use <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" rel="nofollow noreferrer">Statefulset</a> to <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-identity" rel="nofollow noreferrer">identify your pods</a>, but you won't be able to number them from 1 to 15. Statefulset behaves slightly differently. Take a look at the <a href="https://github.com/kubernetes/kubernetes/blob/12f36302f9ee98093d0a01910e345825f1d3a86e/pkg/controller/statefulset/stateful_set_control.go#L319" rel="nofollow noreferrer">source code</a>:</p> <pre><code>// for any empty indices in the sequence [0,set.Spec.Replicas) create a new Pod at the correct revision for ord := 0; ord &lt; replicaCount; ord++ { if replicas[ord] == nil { replicas[ord] = newVersionedStatefulSetPod( currentSet, updateSet, currentRevision.Name, updateRevision.Name, ord) } } </code></pre> <p>For a StatefulSet with X replicas, the numbering will start from 0 up through X-1 (see: <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#ordinal-index" rel="nofollow noreferrer">Ordinal Index</a>).</p> <p>I think you might be interested in using <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/" rel="nofollow noreferrer">Cronjob</a> that runs your custom script periodically on a given schedule. This script can use the Discord Gateway Bot endpoint to determine the recommended number of shards and automatically scale up your bot when Discord recommends it. A good example of such an approach is <a href="https://github.com/Auttaja-OpenSource/Marver" rel="nofollow noreferrer">Marver - a K8s StatefulSet autoscaler</a>. Just take into account that this was made in 2018, so it will need to change to accommodate your Kubernetes version. Additionally, in order to use Marver (or other similar tools), the following requirements must be met:</p> <blockquote> <p>This project requires that you already be using Kubernetes, and assume you have some understand of how Kubernetes works. It also assumes that you have your bot set up to handle changes in the StatefulSet's replica count gracefully. Meaning: if we scale up, all existing shards will need to re-identify with Discord to present the new shard count, and update their local cache as necessary.</p> </blockquote> <p>Of course you can also use an <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/operator/" rel="nofollow noreferrer">operator</a> as <a href="https://stackoverflow.com/users/4216641/turing85" title="15,090 reputation">Turing85</a> has mentioned in the comment:</p> <blockquote> <p>Sounds like a job for an <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/operator/" rel="nofollow noreferrer">operator</a>. I would, however, highly advice against the approach of assigning an id to each pod since this, in essence, gives each pod an identity. This would, in return, mean that we have to use a StatefulSet, not a Deployment. Remember: pods are <a href="https://devops.stackexchange.com/questions/653/what-is-the-definition-of-cattle-not-pets">cattle, not pets</a>.</p> </blockquote>
<p>I am running a GPU intensive workload on demand on GKE Standard, where I have created the appropriate node pool with minimum 0 and maximum 5 nodes. However, when a Job is scheduled on the node pool, GKE presents the following error:</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning FailedScheduling 59s (x2 over 60s) default-scheduler 0/1 nodes are available: 1 node(s) didn't match Pod's node affinity/selector. Normal NotTriggerScaleUp 58s cluster-autoscaler pod didn't trigger scale-up: 1 node(s) had taint {nvidia.com/gpu: present}, that the pod didn't tolerate, 1 in backoff after failed scale-up </code></pre> <p>I have set up nodeSelector according to the documentation and I have autoscaling enabled, I can confirm it does find the node pool in spite of the error saying &quot;didn't match Pod's node affinity/selector&quot; and tries to scale up the cluster. But then it fails shortly thereafter saying 0/1 nodes are available? Which is completely false, seeing there are 0/5 nodes used in the node pool. What am I doing wrong here?</p>
<p><code>1 node(s) had taint {nvidia.com/gpu: present}, that the pod didn't tolerate...</code></p> <p>Try add <code>tolerations</code> to your job's pod spec:</p> <pre><code>... spec: containers: - name: ... ... tolerations: - key: nvidia.com/gpu value: present operator: Exists </code></pre>
<p>This is from <a href="https://kubernetes.io/docs/concepts/overview/components/#etcd" rel="nofollow noreferrer">Kubernetes documentation</a>:</p> <blockquote> <p><strong>Consistent</strong> and <strong>highly-available</strong> key value store used as Kubernetes' backing store for all cluster data.</p> </blockquote> <p>Does Kubernetes have a separate mechanism internally to make ETCD more available? or does ETCD use, let's say, a modified version of Raft that allows this superpower?</p>
<p>When it comes to going into etcd details, it is best to use the <a href="https://etcd.io/" rel="noreferrer">official etcd documentation</a>:</p> <blockquote> <p><strong>etcd</strong> is a strongly consistent, distributed key-value store that provides a reliable way to store data that needs to be accessed by a distributed system or cluster of machines. It gracefully handles leader elections during network partitions and can tolerate machine failure, even in the leader node.</p> </blockquote> <p>There is no mention here that this is high-availability. As for the fault tolerance, you will find a very good paragraph on this topic <a href="https://etcd.io/docs/v3.5/faq/#what-is-failure-tolerance" rel="noreferrer">here</a>:</p> <blockquote> <p>An etcd cluster operates so long as a member quorum can be established. If quorum is lost through transient network failures (e.g., partitions), etcd automatically and safely resumes once the network recovers and restores quorum; Raft enforces cluster consistency. For power loss, etcd persists the Raft log to disk; etcd replays the log to the point of failure and resumes cluster participation. For permanent hardware failure, the node may be removed from the cluster through <a href="https://etcd.io/docs/v3.5/op-guide/runtime-configuration/" rel="noreferrer">runtime reconfiguration</a>.</p> <p>It is recommended to have an odd number of members in a cluster. An odd-size cluster tolerates the same number of failures as an even-size cluster but with fewer nodes.</p> </blockquote> <p>You can also find very good article about <a href="https://medium.com/@ahadrana/understanding-etcd3-8784c4f61755" rel="noreferrer">understanding etcd</a>:</p> <blockquote> <p>Etcd is a strongly consistent system. It provides <a href="http://jepsen.io/consistency/models/linearizable" rel="noreferrer">Linearizable</a> reads and writes, and <a href="http://jepsen.io/consistency/models/serializable" rel="noreferrer">Serializable</a> isolation for transactions. Expressed more specifically, in terms of the <a href="https://en.wikipedia.org/wiki/PACELC_theorem" rel="noreferrer">PACELC</a> theorem, an extension of the ideas expressed in the CAP theorem, it is a CP/EC system. <strong>It optimizes for consistency over latency in normal situations and consistency over availability in the case of a partition.</strong></p> </blockquote> <p>Look also at this picture:<img src="https://i.stack.imgur.com/MjdFG.jpg" alt="enter image description here" /></p>
<p>&quot;Failed to scrape node&quot; `</p> <pre><code>err=&quot;GET \&quot;https://10.128.0.17:10250/stats/summary? only_cpu_and_memory=true\&quot;: bad status code \&quot;403 Forbidden\&quot;&quot; node=&quot;gke-zipydev-cluster-zipy-pool-b4bfa53a-t575&quot; I1215 10:33:03.405180 1 server.go:188] &quot;Failed probe&quot; probe=&quot;metric-storage-ready&quot; err=&quot;not metrics to serve&quot; E1215 10:33:10.513042 1 scraper.go:139] &quot;Failed to scrape node&quot; err=&quot;GET \&quot;https://10.128.0.16:10250/stats/summary? only_cpu_and_memory=true\&quot;: bad status code \&quot;403 Forbidden\&quot;&quot; node=&quot;gke-zipydev-cluster-zipy-pool-b4bfa53a-sg4t&quot; </code></pre> <p>please help if anyone faced same issue.</p>
<p>The privileges for the metrics server are not correctly added as the “403“ error is because access to the requested resource is forbidden.</p> <p>The Metrics Server requires the <strong>“CAP_NET_BIND_SERVICE”</strong> capability in order to bind to a privileged ports as non-root as this applies even if you use the <strong>--secure-port</strong> flag to change the port that Metrics Server binds to to a non-privileged port. Refer <a href="https://github.com/kubernetes-sigs/metrics-server#security-context" rel="nofollow noreferrer">Security context</a> for information.</p> <p>As described in the <a href="https://github.com/kubernetes/kubernetes/pull/105938/files" rel="nofollow noreferrer">Github link</a>, Granting metrics-server necessary permissions to access(query/read) <em><strong>nodes/stat</strong></em> API resource is the workaround to solve this issue. You can grant metrics-server necessary permissions by using the below configuration file.</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: system:metrics-server rules: - apiGroups: - &quot;&quot; resources: - nodes/stats - nodes verbs: - get - list </code></pre> <p><strong>NOTE:</strong> Check your metrics-server has a recent version if you installed it manually. In order to update your metrics-server deployment, you can refer to the <a href="https://github.com/kubernetes-sigs/metrics-server/releases?page=1" rel="nofollow noreferrer">Github link</a> and select the version which suits you.</p> <p>Refer <a href="https://stackoverflow.com/questions/61125754/">stackpost</a> for more information about 403 forbidden errors.</p>
<p>I'm using simple pattern where one Node had one Pod in it, and that Pod is controlled by a Deployment with one replicas set.</p> <p>Deployment is there to ensure Pod restarts when it gets evicted by <code>DiskPressureEviction</code>. The problem I'm facing is caused by Deployment retrying to restart the Pod too fast. As the Pod is set to be in specific Node that hasn't cleaned up <code>DiskPressure</code> yet, restarting Pod fails sequentially before Node is ready to accept new Pod:</p> <pre><code>NAME READY STATUS RESTARTS AGE deployment-adid-7bb998fccc-4v9dx 0/1 Evicted 0 6m17s deployment-adid-7bb998fccc-59kvv 0/1 Evicted 0 6m20s deployment-adid-7bb998fccc-59zzl 0/1 Evicted 0 6m20s deployment-adid-7bb998fccc-dmm9k 0/1 Evicted 0 6m16s deployment-adid-7bb998fccc-gn59z 0/1 Evicted 0 6m20s deployment-adid-7bb998fccc-j4v25 0/1 Evicted 0 6m18s deployment-adid-7bb998fccc-mw4ps 0/1 Evicted 0 6m20s deployment-adid-7bb998fccc-n7krq 0/1 Evicted 0 18h deployment-adid-7bb998fccc-rm4tr 0/1 Evicted 0 6m18s deployment-adid-7bb998fccc-vn44q 0/1 ContainerCreating 0 6m15s </code></pre> <p>Here, 8 Pods are created and evicted in like 5 seconds before 9th get accepted by the designated Node.</p> <p>While the last Pod finally becomes <code>Running</code> I don't like making garbage Pods. Would be nice if Pod can wait for the Node becoming ready, yet if it's impossible, I suppose restarting could be simply delayed. Presumably by describing <code>waitTime</code> before start recreating a Pod, or describing <code>restartInterval</code> that says in which interval should Deployment try to restart Pod.</p> <p>So how can I set this kind of control in Deployment's spec?</p> <p>ADDITION:</p> <p>With excluding meaningless labels, Deployment spec is something like this:</p> <pre><code>deployment_template = { 'apiVersion': 'apps/v1', 'kind': 'Deployment', 'metadata': { 'name': 'first', }, 'spec': { 'replicas': '1', 'selector': { 'matchLabels': { &quot;podName&quot; : &quot;first&quot; } }, 'template': { 'metadata': { 'labels': { &quot;podName&quot; : &quot;first&quot; } }, 'spec': { 'nodeSelector': { &quot;node&quot;: &quot;1&quot; }, 'restartPolicy': 'Always', 'hostNetwork': True, 'dnsPolicy': 'ClusterFirstWithHostNet', 'containers': [ { 'name': 'containername', 'image': &quot;somecontainerimage&quot;, 'imagePullPolicy': 'Always', } ] } } } } </code></pre>
<p>First I'd suggest updating to the newest, supported Kubernetes version. The maintenance support for version 1.17 that you are using <a href="https://endoflife.date/kubernetes" rel="nofollow noreferrer">ended 11 months ago</a>. <a href="https://kubernetes.io/blog/2021/12/07/kubernetes-1-23-release-announcement/" rel="nofollow noreferrer">The actual version (as of today 15.12.2021) is v1.23</a>. Since Kubernetes v1.18 <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/#feature-gates-for-graduated-or-deprecated-features" rel="nofollow noreferrer">the feature <code>TaintBasedEvictions</code></a> is in stable mode.</p> <p>Another thing is that, instead of trying to delay the deployment which is kind of a workaround and not the best practice and better to fix a main issue which is disk pressure eviction that you are occurring. You should consider changing behaviour of your application, or at least try to avoid disk pressure on node by increasing it's storage size.</p> <p>Anyway, If you want to keep it in that way, you may try to setup some additional parameters. You can't itself delay the deployment, but you can change the behaviour of the <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/" rel="nofollow noreferrer">kubelet agent</a> on your node.</p> <hr /> <p>Below example is for the Kubernetes version 1.23. Keep in mind that for version 1.17 it may differ.</p> <p>I created a cluster with one master node and one worker node, the pods are only scheduled on the worker node. I am fulfilling worker storage to create <code>node.kubernetes.io/disk-pressure</code>. By default the behaviour is similar to yours, many pods are created in <code>Evicted</code> state, which, worth to note, it's totally normal and it's expected behaviour. They are creating until node get taint <code>disk-pressure</code>, <a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/" rel="nofollow noreferrer">which is occurring after ~10 seconds by default</a>:</p> <blockquote> <p>nodeStatusUpdateFrequency is the frequency that kubelet computes node status. ... Default: &quot;10s&quot;</p> </blockquote> <p>After that time, as you can observe, there are no pods created in <code>Evicted</code> state. The taint is deleted (i.e in you case the disk storage on node is back to the proper value) after ~5 min, it is <a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletConfiguration" rel="nofollow noreferrer">defined by <code>evictionPressureTransitionPeriod</code> parameter</a>:</p> <blockquote> <p>evictionPressureTransitionPeriod is the duration for which the kubelet has to wait before transitioning out of an eviction pressure condition. ... Default: &quot;5m&quot;</p> </blockquote> <p>Okay, let's change some configuration by editing <a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletConfiguration" rel="nofollow noreferrer">kubelet config file</a> on the worker node- it is located at <code>/var/lib/kubelet/config.yaml</code> for kubeadm.</p> <p>I will change three parameters:</p> <ul> <li>earlier mentioned <a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletConfiguration" rel="nofollow noreferrer"><code>evictionPressureTransitionPeriod</code> parameter</a> set to 120s so taint will be deleted faster</li> <li><a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletConfiguration" rel="nofollow noreferrer"><code>evictionSoft</code></a> to define a soft eviction - in my case it will occur when worker node has available less than 15GB of the storage</li> <li><a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletConfiguration" rel="nofollow noreferrer"><code>evictionSoftGracePeriod</code></a> to define a period after pod will enter into eviction state if defined <code>evictionSoft</code>occurs, in my case it's 60 seconds</li> </ul> <p>The file <code>var/lib/kubelet/config.yaml</code> - only the changed / added fields:</p> <pre><code>evictionPressureTransitionPeriod: 120s evictionSoftGracePeriod: nodefs.available: 60s evictionSoft: nodefs.available: 15Gi </code></pre> <p>To sum up - after my node storage is less than 15 GB, the pod will be in running state for 60 seconds. After that, is storage is still less than 15 GB, pods will enter into <code>Evicted</code> / <code>Completed</code> state, the new pods will occur in <code>Pending</code> state:</p> <pre><code>NAME READY STATUS RESTARTS AGE my-nginx-deployment-6cf77b6d6b-2hr2s 0/1 Completed 0 115m my-nginx-deployment-6cf77b6d6b-8f8wv 0/1 Completed 0 115m my-nginx-deployment-6cf77b6d6b-9kpc9 0/1 Pending 0 108s my-nginx-deployment-6cf77b6d6b-jbx5g 0/1 Pending 0 107s </code></pre> <p>After the available storage is higher than 15 GB, it will take 2 minutes to remove the taint and create new pods.</p> <p>If during these 60 seconds the available storage will be again higher than 15GB, then no action will be done, the pods will be still in <code>Running</code> state.</p> <p>If you have any garbage pods running, run this command to delete them:</p> <pre><code>kubectl get pods | grep -e &quot;ContainerStatusUnknown&quot; -e &quot;Evicted&quot; -e &quot;Completed&quot; -e &quot;Error&quot; | awk '{print $1}' | xargs kubectl delete pod </code></pre> <p>Keep in mind that pod eviction may behave differently for different <a href="https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/" rel="nofollow noreferrer">QoS classes</a> and <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/#priorityclass" rel="nofollow noreferrer">priority classes</a>- check this article -&gt; <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/#pod-selection-for-kubelet-eviction" rel="nofollow noreferrer">Node-pressure Eviction - Pod selection for kubelet eviction</a> for more information.</p> <p>You should try to monitor how exactly the disk pressure is happening on your node and you can adjust the kubelet configuration accordingly. Also check these articles:</p> <ul> <li><a href="https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/" rel="nofollow noreferrer">Node-pressure Eviction</a>.</li> <li><a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/" rel="nofollow noreferrer">Parameters to configure in kubelet</a></li> </ul>
<p>I created a service account user and got the token for the user. However, ever time I try to access the names spaces I get the following error:</p> <pre><code>{ &quot;kind&quot;: &quot;Status&quot;, &quot;apiVersion&quot;: &quot;v1&quot;, &quot;metadata&quot;: {}, &quot;status&quot;: &quot;Failure&quot;, &quot;message&quot;: &quot;namespaces is forbidden: User \&quot;system:serviceaccount:default:svcacc\&quot; cannot list resource \&quot;namespaces\&quot; in API group \&quot;\&quot; at the cluster scope&quot;, &quot;reason&quot;: &quot;Forbidden&quot;, &quot;details&quot;: { &quot;kind&quot;: &quot;namespaces&quot; }, &quot;code&quot;: 403 } </code></pre> <p>This is my service account:</p> <pre><code>Name: svcacc-token-87jd6 Namespace: default Labels: &lt;none&gt; Annotations: kubernetes.io/service-account.name: svcacc kubernetes.io/service-account.uid: 384aa590-dac4-472c-a9a7-116c5fb0562b Type: kubernetes.io/service-account-token </code></pre> <p>Do I need to give the service account roles or add it to a group? This is running in AWS EKS, not sure if that make a difference.</p> <p>I am trying to use ServiceNow discovery to discover my Kubernetes cluster. Regardless if I am using ServiceNow or Postman, I get the same message.</p> <p>EDIT: Ended up using YAML to configure the service account and roles.</p> <pre><code>apiVersion: v1 kind: ServiceAccount metadata: name: svcacc namespace: default --- # Create ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: svcacc roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: svcacc namespace: default </code></pre> <p>Once this was configured I updated the <code>kubeconfig</code> and ran to get token:</p> <pre><code>$(kubectl describe secrets &quot;$(kubectl describe serviceaccount svcacc -n default| grep -i Tokens | awk '{print $2}')&quot; -n default | grep token: | awk '{print $2}') </code></pre>
<p>To clarify I am posting a Community Wiki answer.</p> <p>You solved this problem using YAML file to configure the service account and roles.</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: ServiceAccount metadata: name: svcacc namespace: default --- # Create ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: svcacc roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: svcacc namespace: default </code></pre> <p>And after that you updated the <code>kubeconfig</code> and ran to get token:</p> <pre class="lang-yaml prettyprint-override"><code>$(kubectl describe secrets &quot;$(kubectl describe serviceaccount svcacc -n default| grep -i Tokens | awk '{print $2}')&quot; -n default | grep token: | awk '{print $2}') </code></pre> <p><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/" rel="nofollow noreferrer">Here</a> is documentation about RBAC Authorization with many examples.</p> <blockquote> <p>Role-based access control (RBAC) is a method of regulating access to computer or network resources based on the roles of individual users within your organization.</p> </blockquote>
<p>I want to expose k8s api's using a service. My issue is that the api only respond on port 6443 on https. Any attempt on http return status 400 bad request. How can I &quot;force&quot; the service to user https ?</p> <pre><code>apiVersion: v1 kind: Service metadata: name: k8s-api namespace: kube-system labels: label: k8s-api spec: ports: - port: 80 #Port on which your service is running targetPort: 6443 protocol: TCP name: http selector: name: kube-apiserver-master-node </code></pre> <p>May be this ?</p> <pre><code>apiVersion: v1 kind: Service metadata: name: k8s-api namespace: kube-system labels: label: k8s-api spec: ports: - port: 443 #Port on which your service is running targetPort: 6443 protocol: TCP name: http selector: name: kube-apiserver-master-node </code></pre>
<p>If you are using the Nginx ingress by default it does <strong>SSL</strong> <strong>off load</strong> and sends plain <strong>HTTP</strong> in the background.</p> <p>Changing port <strong>6443</strong> might be helpful if you request direct connecting to the <strong>service</strong>.</p> <p>If you are using the Nginx ingress make sure it doesn't terminate SSL.</p> <pre><code>nginx.ingress.kubernetes.io/backend-protocol: &quot;HTTPS&quot; nginx.ingress.kubernetes.io/ssl-passthrough: &quot;true&quot; </code></pre>
<p>The Node JS app that I'm trying to deploy in Kubernetes runs on <code>express js</code> as a backend framework.The repository is managed via <code>Bitbucket</code>. The application is a microservice and the pipeline manifest file for building the Docker image is written this way:</p> <pre><code>options: docker: true image: node:14.17.0 pipelines: branches: test: - step: services: - docker name: Build and push new docker image deployment: dev script: - yarn install - yarn build - yarn test - yarn lint - make deploy.dev - docker login -u $DOCKER_HUB_USERNAME -p $DOCKER_HUB_PASSWORD - docker build -t testapp/helloapp:latest -f ./Dockerfile . - docker push testapp/helloapp caches: - docker # adds docker layer caching </code></pre> <p>The K8s cluster is hosted on <a href="https://upcloud.com/community/tutorials/deploy-kubernetes-using-kubespray/" rel="nofollow noreferrer">cloud</a> but does not have the internal <code>Load Balancer</code> of their own. The K8s cluster version is <code>v1.22.4</code> and <code>MetalLB v0.11.0</code> is configured to serve the Load Balancing purpose. To expose the K8s <code>service</code>- Cloudflare Tunnel is configured as a K8s <code>deployment</code>.</p> <p>So, this is the manifest file set-up used for building the Docker image. The pipeline deploys successfully and in the Kubernetes part, this is the <code>service</code> and <code>deployment</code> manifest:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: helloapp labels: app: helloapp spec: type: NodePort ports: - port: 5000 targetPort: 7000 protocol: TCP name: https selector: app: helloapp --- apiVersion: apps/v1 kind: Deployment metadata: name: helloapp labels: app: helloapp spec: replicas: 3 selector: matchLabels: app: helloapp template: metadata: labels: app: helloapp spec: imagePullSecrets: - name: regcred containers: - name: helloapp image: testapp/helloapp:latest </code></pre> <p>Also, here is the <code>Dockerfile</code> snippet to give more clarity on what I have been doing:</p> <pre><code>FROM node:14.17.0 WORKDIR /app COPY package.json /app RUN npm install COPY . /app CMD node app.js EXPOSE 8100 </code></pre> <p>Just to give a context, the service and deployment works fine, with no <code>CrashLoopBackOff</code> or any other errors. My doubt here is, there is <code>dist</code> directory which is not getting deployed to Docker Hub as it is generated during <code>npm build</code>. How can I deploy the app along with the <code>dist</code> directory without having to worry about security risks? Any feedbacks and suggestions on where I could add a script to pull the <code>dist</code> directory would be appreciated.</p>
<p>Eventually, I could resolve the issue. The issue was trivial yet bothering. In the <code>Dockerfile</code>, there was a missing script, i.e., <code>npm run build</code>. So, here is the final <code>Dockerfile</code> I used it for building the <code>dist</code> directory along with other requirements:</p> <pre><code>FROM node:14.17.0 WORKDIR /app COPY package.json /app RUN npm install RUN npm run build &lt;------ the missing script COPY . /app CMD node app.js EXPOSE 8100 </code></pre> <p>This way, the entire <code>dist</code> directory gets built inside the container. Also, I removed all the <code>.ENV</code> dependencies from <code>dist</code> directory and stored as Kubernetes secret in <code>base64</code> format.</p>
<p>I am using prisma, postgres, docker, kubernets.</p> <p><strong>npx prisma migrate dev</strong> working.</p> <p>and <strong>npx prisma generate</strong> produce below output:</p> <pre><code>✔ Generated Prisma Client (2.23.0) to ./node_modules/@prisma/client in 68ms You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() </code></pre> <p>but when I tried to use in my route file produce the error:</p> <p>new-route.ts</p> <pre><code>import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); </code></pre> <p>my docker file:</p> <pre><code>FROM node:alpine WORKDIR /app COPY package.json . RUN npm install --only=prod COPY . . CMD [&quot;npm&quot;, &quot;start&quot;] </code></pre>
<p>I know that this has been marked as solved, but I just wanted to share my setup for anyone interested.</p> <p>Dockerfile</p> <pre><code># Build image FROM node:16.13-alpine as builder WORKDIR /app # Not sure if you will need this # RUN apk add --update openssl COPY package*.json ./ RUN npm ci --quiet COPY ./prisma prisma COPY ./src src RUN npm run build # Production image FROM node:16.13-alpine WORKDIR /app ENV NODE_ENV production COPY package*.json ./ RUN npm ci --only=production --quiet COPY --chown=node:node --from=builder /app/prisma /app/prisma COPY --chown=node:node --from=builder /app/src /app/src USER node EXPOSE 8080 CMD [&quot;node&quot;, &quot;src/index.js&quot;] </code></pre> <p>package.json</p> <pre><code>{ &quot;name&quot;: &quot;example&quot;, &quot;description&quot;: &quot;&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;scripts&quot;: { &quot;generate&quot;: &quot;npx prisma generate&quot;, &quot;deploy&quot;: &quot;npx prisma migrate deploy&quot;, &quot;dev&quot;: &quot;npm run generate &amp;&amp; nodemon --watch \&quot;src/**\&quot; --ext \&quot;js,json\&quot; --exec \&quot;node src/index.js\&quot;&quot;, &quot;build&quot;: &quot;npm run generate&quot;, &quot;start&quot;: &quot;npm run build &amp;&amp; node build/index.js&quot; }, &quot;prisma&quot;: { &quot;schema&quot;: &quot;prisma/schema.prisma&quot; }, &quot;dependencies&quot;: { &quot;@prisma/client&quot;: &quot;^3.6.0&quot; }, &quot;devDependencies&quot;: { &quot;@tsconfig/node16&quot;: &quot;^1.0.2&quot;, &quot;@types/node&quot;: &quot;^16.11.12&quot;, &quot;nodemon&quot;: &quot;^2.0.15&quot;, &quot;prisma&quot;: &quot;^3.6.0&quot; } } </code></pre> <p>I run this in Kubernetes. To make things smooth with database and migrations I run an initContainer that runs the <code>prisma migrate deploy</code>.</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: EXAMPLE spec: replicas: 1 selector: matchLabels: app: EXAMPLE strategy: rollingUpdate: maxSurge: 100% maxUnavailable: 0 type: RollingUpdate template: metadata: labels: app: EXAMPLE spec: containers: image: DOCKER_IMAGE imagePullPolicy: IfNotPresent name: SERVICE_NAME ports: - containerPort: 8080 name: http protocol: TCP initContainers: - command: - npm - run - deploy image: DOCKER_IMAGE imagePullPolicy: IfNotPresent name: database-migrate-deploy </code></pre> <p>(This is a live service I just copied and stripped away anything non essential)</p> <p>I hope this could be of use to someone</p>
<p>The following example would expose the services externally. So why is <code>NodePort</code>/<code>LB</code> allowed in this context, would not that be redundant?</p> <pre><code> rules: - host: lab.example.com http: paths: - path: /service-root backend: serviceName: clusterip-svc servicePort: 8080 - path: /service-one backend: serviceName: nodeport-svc servicePort: 8080 - path: /service-two backend: serviceName: headless-svc servicePort: 8080 </code></pre> <p>Is there any particular advantage of using <code>NodePort</code>, <code>ClusterIP</code>, <code>LoadBalancer</code>, or <code>Headless</code> as back-end to Ingress?</p>
<p>Services are a way to define logical set of Pods and a policy to access them. The Pods are ephemeral resources, so Services make it possible to connect to them regardless of their IP addresses. They usually use selectors to do so. There are different types of Services in Kubernetes and these are the main differences.</p> <p>Cluster IP is a default type of Service. It exposes the Service on a cluster-internal IP and makes it available only from within the cluster.</p> <p>NodePort exposes the Service on each Node's IP at a static port. This option also creates ClusterIP Service, to which NodePort routes.</p> <p>LoadBalancer goes a step further and exposes the Service externally using cloud provider's load balancer. NodePort and ClusterIP resources are created automatically.</p> <p>Follow <a href="https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types" rel="noreferrer">this link</a> to get more information about different ServiceTypes.</p> <p>And there are Headless Services. You would use these when you don't need load-balancing and a single Service IP. You can follow <a href="https://kubernetes.io/docs/concepts/services-networking/service/#headless-services" rel="noreferrer">this</a> section in documentation for further clarification.</p> <p>Answering your question - it depends on your use-case, you might find different advantages using these Services.</p>
<p>We need to send large (very) amount of logs to <code>Splunk</code> server from only <strong>one k8s pod</strong>( pod with huge traffic load), I look at the docs and found this:</p> <p><a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/#sidecar-container-with-a-logging-agent" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/cluster-administration/logging/#sidecar-container-with-a-logging-agent</a></p> <p>However, there is a <strong>Note in the docs, that is stating about a significant resource consumption</strong>. Is there any other option to do it? I mean more efficient ? As these pods handle traffic and we cannot add the additional load, that can risk it stability...</p>
<p>There's an official solution to get Kubernets logs: Splunk Connect for Kubernetes. Under the hood it also uses fluentd for the logging part.</p> <p><a href="https://github.com/splunk/splunk-connect-for-kubernetes" rel="nofollow noreferrer">https://github.com/splunk/splunk-connect-for-kubernetes</a></p> <p>You will find a sample config and a methodology to test it on microK8s first to get acquainted with the config and deployment: <a href="https://mattymo.io/deploying-splunk-connect-for-kubernetes-on-microk8s-with-helm/" rel="nofollow noreferrer">https://mattymo.io/deploying-splunk-connect-for-kubernetes-on-microk8s-with-helm/</a></p> <p>And if you only want logs from a specific container you can use this section of the values file to select only logs from the container you're interested in:</p> <pre><code> fluentd: # path of logfiles, default /var/log/containers/*.log path: /var/log/containers/*.log # paths of logfiles to exclude. object type is array as per fluentd specification: # https://docs.fluentd.org/input/tail#exclude_path exclude_path: # - /var/log/containers/kube-svc-redirect*.log # - /var/log/containers/tiller*.log # - /var/log/containers/*_kube-system_*.log (to exclude `kube-system` namespace) </code></pre>
<p>I am trying to setup a local cluster using minikube in a Windows machine. Following some tutorials in <code>kubernetes.io</code>, I got the following manifest for the cluster:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: external-nginx-deployment labels: app: external-nginx spec: selector: matchLabels: app: external-nginx replicas: 2 template: metadata: labels: app: external-nginx spec: containers: - name: external-nginx image: nginx ports: - containerPort: 80 --- apiVersion: v1 kind: Service metadata: name: expose-nginx labels: service: expose-nginx spec: type: NodePort selector: app: external-nginx ports: - protocol: TCP port: 80 targetPort: 80 nodePort: 32000 </code></pre> <p>If I got things right, this should create a pod with a nginx instance and expose it to the host machine at port 32000. However, when I run <code>curl http://$(minikube ip):32000</code>, I get a <strong>connection refused</strong> error.</p> <p>I ran bash inside the service <em>expose-nginx</em> via <code>kubectl exec svc/expose-nginx -it bash</code> and from there I was able to access the <em>external-nginx</em> pods normally, which lead me to believe it is not a problem within the cluster.</p> <p>I also tried to change the type of the service to LoadBalancer and enable the <code>minikube tunnel</code>, but got the same result.</p> <p>Is there something I am missing?</p>
<p>Almost always by default <code>minikube</code> uses <code>docker</code> driver for the <code>minikube</code> VM creation. In the host system it looks like a big docker container for the VM in which other kubernetes components are run as containers as well. Based on tests <code>NodePort</code> for services often doesn't work as it's supposed to like accessing the service exposed via <code>NodePort</code> should work on <code>minikube_IP:NodePort</code> address.</p> <p>Solutions are:</p> <ul> <li><p>for local testing use <a href="https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/" rel="nofollow noreferrer"><code>kubectl port-forward</code></a> to expose service to the local machine (which OP did)</p> </li> <li><p>use <a href="https://minikube.sigs.k8s.io/docs/commands/service/" rel="nofollow noreferrer"><code>minikube service</code></a> command which will expose the service to the host machine. Works in a very similar way as <code>kubectl port-forward</code>.</p> </li> <li><p>instead of <code>docker</code> driver use proper virtual machine which will get its own IP address (<code>VirtualBox</code> or <code>hyperv</code> drivers - depends on the system). <a href="https://minikube.sigs.k8s.io/docs/drivers/" rel="nofollow noreferrer">Reference</a>.</p> </li> <li><p>(Not related to <code>minikube</code>) Use built-in feature <code>kubernetes</code> in Docker Desktop for Windows. I've already <a href="https://stackoverflow.com/a/69113528/15537201">tested it</a> and service type should be <code>LoadBalancer</code> - it will be exposed to the host machine on <code>localhost</code>.</p> </li> </ul>
<p>I am trying to make an nginx deployment and during the container creation, I want to create multiply symbolic links. But for some reason, it doesn't work and the container crashes.</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: labels: app: tcc component: nginx name: tcc-nginx-deployment namespace: dev2 spec: replicas: 1 selector: matchLabels: app: tcc component: nginx template: metadata: labels: app: tcc component: nginx spec: containers: - image: nginx name: nginx command: - /bin/sh - -c - | ln -s /shared/apps/ /var/www rm -r /etc/nginx/conf.d ln -s /shared/nginx-config/ /etc/nginx/conf.d ports: - containerPort: 80 protocol: TCP volumeMounts: - mountPath: /shared name: efs-pvc volumes: - name: efs-pvc persistentVolumeClaim: claimName: tcc-efs-storage-claim </code></pre>
<p>The container is not running, because after the <code>command</code> block is executed, container is exiting, which is expected behaviour.</p> <p>Instead of playing with symbolic links in <code>command</code> in yaml template (which is not the best practice solution), why just don't use solution builtin Kubernetes and do not use <code>command</code> block at all?</p> <p>You should use <a href="https://kubernetes.io/docs/concepts/storage/volumes/#using-subpath" rel="nofollow noreferrer"><code>subPath</code> which is designed to share directories from one volume for multiple, different directories on the single pod</a>:</p> <blockquote> <p>Sometimes, it is useful to share one volume for multiple uses in a single pod. The <code>volumeMounts.subPath</code> property specifies a sub-path inside the referenced volume instead of its root.</p> </blockquote> <p>In your case, the deployment yaml should look like this:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1 kind: Deployment metadata: labels: app: tcc component: nginx name: tcc-nginx-deployment namespace: dev2 spec: replicas: 1 selector: matchLabels: app: tcc component: nginx template: metadata: labels: app: tcc component: nginx spec: containers: - image: nginx name: nginx ports: - containerPort: 80 protocol: TCP volumeMounts: - mountPath: /shared name: efs-pvc - mountPath: /etc/nginx/conf.d name: efs-pvc subPath: nginx-config - mountPath: /var/www name: efs-pvc subPath: apps volumes: - name: efs-pvc persistentVolumeClaim: claimName: tcc-efs-storage-claim </code></pre> <p>Also if you want to mount only config files for NGINX, you may use ConfigMap instead of volume - check <a href="https://stackoverflow.com/a/42078899/16391991">this answer</a> for more information.</p>
<p>I have a kubernetes cluster in google cloud. Due to the resource limit, I could not run a app that would take a large amount of memory. So I run the app in another cloud machine, and using <code>kubectl</code> to forward the service port, this is my <code>kubectl</code> forward script:</p> <pre><code>#!/usr/bin/env bash set -u set -e set -x namespace=reddwarf-cache kubectl config use-context reddwarf-kubernetes POD=$(kubectl get pod -l app.kubernetes.io/instance=cruise-redis -n ${namespace} -o jsonpath=&quot;{.items[0].metadata.name}&quot;) kubectl port-forward ${POD} 6380:6379 -n ${namespace} </code></pre> <p>And I could connect the kubernetes cluster service from the remote server like this, local app connect to local mechine port and <code>kubectl</code> will forward the connection to kubernetes cluster. But sadly I found the <code>kubectl</code> forward could not keep stable for a long time, when the app runs for some time, always give connection refused error in the future time. Is it possible to fix this problem? To let me connect to kubernetes cluster service in a stable way? For example, when I port forward the redis connection, it will throw this error in the future:</p> <pre><code>E1216 11:58:43.452204 7756 portforward.go:346] error creating error stream for port 6379 -&gt; 6379: write tcp 172.17.0.16:60112-&gt;106.14.183.131:6443: write: broken pipe Handling connection for 6379 E1216 11:58:43.658372 7756 portforward.go:346] error creating error stream for port 6379 -&gt; 6379: write tcp 172.17.0.16:60112-&gt;106.14.183.131:6443: write: broken pipe Handling connection for 6379 E1216 11:58:43.670151 7756 portforward.go:346] error creating error stream for port 6379 -&gt; 6379: write tcp 172.17.0.16:60112-&gt;106.14.183.131:6443: write: broken pipe Handling connection for 6379 </code></pre> <p>When I using this command to connect the kubernetes cluster's redis service using port forward and execute some command, will show this error:</p> <pre><code>➜ ~ redis-cli -h 127.0.0.1 -p 6379 -a 'uoGTdVy3P7' 127.0.0.1:6379&gt; info Error: Connection reset by peer </code></pre> <p>I have read this GitHub <a href="https://github.com/kubernetes/kubernetes/issues/74551" rel="nofollow noreferrer">issue</a> seem no one knows what's happened.</p>
<p>Following the GitHub <a href="https://github.com/kubernetes/kubernetes/issues/74551" rel="nofollow noreferrer">issue</a> you posted I stumbled upon a solution that might help you. First, let kubectl decide which host port to use by running:</p> <pre><code>kubectl port-forward ${POD} :6379 -n ${namespace} </code></pre> <p>Then, forward the same port on the host by running:</p> <pre><code>kubectl port-forward ${POD} 6379:6379 -n ${namespace} </code></pre> <p>Another thing you could do is to create a Service that maps your desired port to port 6379 in your redis Pods, example Service file would look like this:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app: redis ports: - protocol: TCP port: &lt;port&gt; targetPort: 6379 </code></pre> <p>Apply the Service resource. Then, create Ingress backed by a single Service to make redis available from outside the cluster, example file:</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: test-ingress spec: defaultBackend: service: name: my-service port: number: &lt;port&gt; </code></pre> <p>Apply the Ingress resource and get its IP address by running:</p> <pre><code>kubectl get ingress test-ingress </code></pre> <p>After that check your redis connection from another machine using Ingress IP address.</p>
<p>I'm developing a Java application that creates some Kubernetes Jobs using the official Kubernetes Java client. Each Job uses its configuration directory, which already exists as a configMap in the cluster. (This configMap was created using <code>kubectl create configmap {name} --from-file=/... </code>)</p> <p>Using Java client, I successfully created a <code>V1ConfigMap</code> object that refers to a specific configMap, and I also found that <code>V1Volume.setConfigMap()</code> will convert <code>V1ConfigMapVolumeSource</code> to <code>V1Volume</code> that can be mounted by a container.</p> <p>However, I couldn't find the way to map <code>V1ConfigMap</code> and <code>V1ConfigMapVolumeSource</code>.</p> <p>Here is my code:</p> <pre class="lang-java prettyprint-override"><code>public void setConfigMap(V1ConfigMap cm, String mountPath){ V1ConfigMapVolumeSource volSource = new V1ConfigMapVolumeSource(); //Some additional mappings are needed here. //volSource = ...(cm) //create V1Volume from V1ConfigMapVolumeSource String volName = &quot;appSetting&quot;; V1Volume settingVol = new V1Volume().name(volName); settingVol.setConfigMap(volSource); //create V1VolumeMount V1VolumeMount volumeMount = new V1VolumeMount(); volumeMount.setMountPath(mountPath); volumeMount.setName(volName); //set created objects to the Job job.getSpec().getTemplate().getSpec().addVolumesItem(settingVol); job.getSpec().getTemplate().getSpec().getContainers().get(0).addVolumeMountsItem(volumeMount); } </code></pre> <p>Does anyone know the way to solve this, or is my way to approach completely wrong?</p>
<p>As stated into the <a href="https://github.com/kubernetes-client/java/blob/master/kubernetes/docs/V1ConfigMapVolumeSource.md" rel="nofollow noreferrer">documentation</a> for <code>V1ConfigMapVolumeSource</code>, there is a <code>name</code> parameter (type <code>String</code>) which is the <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names" rel="nofollow noreferrer">name of the referent</a>.</p> <p>To link a <code>ConfigMap</code> inside a <code>ConfigMapVolumeSource</code>, just put the name of the <code>ConfigMap</code> in the name parameter, that should be enough.</p>
<p>I am following <a href="https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/" rel="nofollow noreferrer">this official k8 ingress tutorial</a>. However I am not able to <code>curl</code> the minikube IP address and access the &quot;web&quot; application.</p> <pre><code>minikube addons enable ingress kubectl create deployment web --image=gcr.io/google-samples/hello-app:1.0 kubectl expose deployment web --type=NodePort --port=8080 kubectl apply -f https://k8s.io/examples/service/networking/example-ingress.yaml </code></pre> <p>I'm able to curl the result of <code>minikube service web --url</code></p> <pre><code> curl http://127.0.0.1:64671 Hello, world! Version: 1.0.0 Hostname: web-79d88c97d6-8z8tc </code></pre> <p>But not though ingress, with <code>kubectl apply -f https://k8s.io/examples/service/networking/example-ingress.yaml</code></p> <p>(I don't have an external IP - just &quot;localhost&quot;. )</p> <pre><code>NGG282 kubernetes-ingress % kubectl get ingress NAME CLASS HOSTS ADDRESS PORTS AGE example-ingress nginx * localhost 80 66m </code></pre> <p>This seems to be normal with minikube. Trying to curl the minikube IP:</p> <pre><code>curl $(minikube ip) curl: (7) Failed to connect to 192.168.49.2 port 80: Operation timed out </code></pre> <p>Any help?</p> <p>----------EDIT :</p> <pre><code>kubectl get deploy -n ingress-nginx -o yaml ports: - containerPort: 80 hostPort: 80 name: http protocol: TCP - containerPort: 443 hostPort: 443 name: https protocol: TCP - containerPort: 8443 name: webhook protocol: TCP kubectl get svc -n ingress-nginx -o yaml apiVersion: v1 items: - apiVersion: v1 kind: Service metadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {&quot;apiVersion&quot;:&quot;v1&quot;,&quot;kind&quot;:&quot;Service&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{},&quot;labels&quot;:{&quot;app.kubernetes.io/component&quot;:&quot;controller&quot;,&quot;app.kubernetes.io/instance&quot;:&quot;ingress-nginx&quot;,&quot;app.kubernetes.io/name&quot;:&quot;ingress-nginx&quot;},&quot;name&quot;:&quot;ingress-nginx-controller&quot;,&quot;namespace&quot;:&quot;ingress-nginx&quot;},&quot;spec&quot;:{&quot;ipFamilies&quot;:[&quot;IPv4&quot;],&quot;ipFamilyPolicy&quot;:&quot;SingleStack&quot;,&quot;ports&quot;:[{&quot;appProtocol&quot;:&quot;http&quot;,&quot;name&quot;:&quot;http&quot;,&quot;port&quot;:80,&quot;protocol&quot;:&quot;TCP&quot;,&quot;targetPort&quot;:&quot;http&quot;},{&quot;appProtocol&quot;:&quot;https&quot;,&quot;name&quot;:&quot;https&quot;,&quot;port&quot;:443,&quot;protocol&quot;:&quot;TCP&quot;,&quot;targetPort&quot;:&quot;https&quot;}],&quot;selector&quot;:{&quot;app.kubernetes.io/component&quot;:&quot;controller&quot;,&quot;app.kubernetes.io/instance&quot;:&quot;ingress-nginx&quot;,&quot;app.kubernetes.io/name&quot;:&quot;ingress-nginx&quot;},&quot;type&quot;:&quot;NodePort&quot;}} creationTimestamp: &quot;2021-12-16T11:41:35Z&quot; labels: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx name: ingress-nginx-controller namespace: ingress-nginx resourceVersion: &quot;489&quot; uid: 63826bc2-5d90-42f1-861f-f7f082ccf0fb spec: clusterIP: 10.104.208.171 clusterIPs: - 10.104.208.171 externalTrafficPolicy: Cluster internalTrafficPolicy: Cluster ipFamilies: - IPv4 ipFamilyPolicy: SingleStack ports: - appProtocol: http name: http nodePort: 30783 port: 80 protocol: TCP targetPort: http - appProtocol: https name: https nodePort: 30860 port: 443 protocol: TCP targetPort: https selector: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx sessionAffinity: None type: NodePort status: loadBalancer: {} - apiVersion: v1 kind: Service metadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {&quot;apiVersion&quot;:&quot;v1&quot;,&quot;kind&quot;:&quot;Service&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{},&quot;labels&quot;:{&quot;app.kubernetes.io/component&quot;:&quot;controller&quot;,&quot;app.kubernetes.io/instance&quot;:&quot;ingress-nginx&quot;,&quot;app.kubernetes.io/name&quot;:&quot;ingress-nginx&quot;},&quot;name&quot;:&quot;ingress-nginx-controller-admission&quot;,&quot;namespace&quot;:&quot;ingress-nginx&quot;},&quot;spec&quot;:{&quot;ports&quot;:[{&quot;appProtocol&quot;:&quot;https&quot;,&quot;name&quot;:&quot;https-webhook&quot;,&quot;port&quot;:443,&quot;targetPort&quot;:&quot;webhook&quot;}],&quot;selector&quot;:{&quot;app.kubernetes.io/component&quot;:&quot;controller&quot;,&quot;app.kubernetes.io/instance&quot;:&quot;ingress-nginx&quot;,&quot;app.kubernetes.io/name&quot;:&quot;ingress-nginx&quot;},&quot;type&quot;:&quot;ClusterIP&quot;}} creationTimestamp: &quot;2021-12-16T11:41:35Z&quot; labels: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx name: ingress-nginx-controller-admission namespace: ingress-nginx resourceVersion: &quot;483&quot; uid: fe797532-27c9-4dd1-a1bc-0662a3d2a4da spec: clusterIP: 10.106.175.35 clusterIPs: - 10.106.175.35 internalTrafficPolicy: Cluster ipFamilies: - IPv4 ipFamilyPolicy: SingleStack ports: - appProtocol: https name: https-webhook port: 443 protocol: TCP targetPort: webhook selector: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx sessionAffinity: None type: ClusterIP status: loadBalancer: {} kind: List metadata: resourceVersion: &quot;&quot; selfLink: &quot;&quot; </code></pre>
<p>OK so apparently this is a <a href="https://minikube.sigs.k8s.io/docs/drivers/docker/#known-issues" rel="nofollow noreferrer">known issue with minikube</a>, Ingress works properly on linux only.</p> <blockquote> <p>The ingress, and ingress-dns addons are currently only supported on Linux. See #7332</p> </blockquote> <p>you need to <code>minikube tunnel</code> on windows/macOS before being able to <code>curl</code>, but still there are differences:</p> <p>On <strong>Windows</strong>, both <code>127.0.0.1</code> and <code>localhost</code> redirect to the application. On <strong>macOS</strong>, <code>127.0.0.1</code> and <code>localhost</code> show an &quot;nginX not found&quot; message, but <code>curl hello-world.info</code> works only after changing <code>etc/hosts</code>.</p>
<p>I dig everywhere to see why we don't have DNS resolution for static pods and couldn't find a right answer. Most basic stuff and couldn't find appealing answer.</p> <p>Like you create a static pod, exec into it, do a &quot;nslookup pod-name&quot; or like &quot;nslookup 10-44-0-7.default.pod.cluster.local&quot;, I know the second one is for Deployment and DaemonSet which creates A record, why not for static pods because they are ephemeral, in that way Deployment also is. Please tell me if it is possible and how we enable it.</p> <p>My testing for the failed queries, all are static pods created with &quot;kubectl run busybox-2 --image=busybox --command sleep 1d&quot;</p> <p>Used this as syntax:</p> <p>In general a pod has the following DNS resolution: pod-ip-address.my-namespace.pod.cluster-domain.example.</p> <pre><code>vagrant@kubemaster:~$ kubectl get pods -n default -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES busybox-1 1/1 Running 0 135m 10.36.0.6 kubenode02 &lt;none&gt; &lt;none&gt; busybox-2 1/1 Running 0 134m 10.44.0.7 kubenode01 &lt;none&gt; &lt;none&gt; busybox-sleep 1/1 Running 19 (24h ago) 23d 10.44.0.3 kubenode01 &lt;none&gt; &lt;none&gt; / # cat /etc/resolv.conf nameserver 10.96.0.10 search default.svc.cluster.local svc.cluster.local cluster.local Dlink options ndots:5 / # nslookup 10-44-0-7.default.pod.cluster.local Server: 10.96.0.10 Address: 10.96.0.10:53 Name: 10-44-0-7.default.pod.cluster.local Address: 10.44.0.7 *** Can't find 10-44-0-7.default.pod.cluster.local: No answer / # nslookup 10-44-0-6.default.pod.cluster.local Server: 10.96.0.10 Address: 10.96.0.10:53 *** Can't find 10-44-0-6.default.pod.cluster.local: No answer </code></pre> <p>Appreciate the help.</p>
<p>You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:</p> <p>Katacoda Play with Kubernetes Your cluster must be running the CoreDNS add-on. Migrating to CoreDNS explains how to use kubeadm to migrate from kube-dns.</p> <p>Your Kubernetes server must be at or later than version v1.12. To check the version, enter kubectl version.</p>
<p>I dig everywhere to see why we don't have DNS resolution for static pods and couldn't find a right answer. Most basic stuff and couldn't find appealing answer.</p> <p>Like you create a static pod, exec into it, do a &quot;nslookup pod-name&quot; or like &quot;nslookup 10-44-0-7.default.pod.cluster.local&quot;, I know the second one is for Deployment and DaemonSet which creates A record, why not for static pods because they are ephemeral, in that way Deployment also is. Please tell me if it is possible and how we enable it.</p> <p>My testing for the failed queries, all are static pods created with &quot;kubectl run busybox-2 --image=busybox --command sleep 1d&quot;</p> <p>Used this as syntax:</p> <p>In general a pod has the following DNS resolution: pod-ip-address.my-namespace.pod.cluster-domain.example.</p> <pre><code>vagrant@kubemaster:~$ kubectl get pods -n default -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES busybox-1 1/1 Running 0 135m 10.36.0.6 kubenode02 &lt;none&gt; &lt;none&gt; busybox-2 1/1 Running 0 134m 10.44.0.7 kubenode01 &lt;none&gt; &lt;none&gt; busybox-sleep 1/1 Running 19 (24h ago) 23d 10.44.0.3 kubenode01 &lt;none&gt; &lt;none&gt; / # cat /etc/resolv.conf nameserver 10.96.0.10 search default.svc.cluster.local svc.cluster.local cluster.local Dlink options ndots:5 / # nslookup 10-44-0-7.default.pod.cluster.local Server: 10.96.0.10 Address: 10.96.0.10:53 Name: 10-44-0-7.default.pod.cluster.local Address: 10.44.0.7 *** Can't find 10-44-0-7.default.pod.cluster.local: No answer / # nslookup 10-44-0-6.default.pod.cluster.local Server: 10.96.0.10 Address: 10.96.0.10:53 *** Can't find 10-44-0-6.default.pod.cluster.local: No answer </code></pre> <p>Appreciate the help.</p>
<ul> <li>DNS Lookup &amp; Reverse lookups does not work for pods/podIPs (<em><strong>By Design!</strong></em>).</li> <li>Why ? I also had the similar question , After spending a lot of time exploring following are reasons that convinced me :</li> </ul> <ol> <li>Pods &amp; and its IPs are ephemeral. even static pods when they get restarted(recreated) they might end up getting a different IP Address.</li> <li>It will be huge overload on coredns/any dns server to keep a track of ever changing POD IP Addresses.</li> <li>Due to above reasons It is recommended to access the POD through a <em><strong>service</strong></em> because service will have a constant IP irrespective of how the endpoint IPS have changed. for services DNS lookups &amp; reverse loookups work fine.</li> </ol>
<p>I am following a very simple tutorial where it spawns a simple pod with an http endpoint and a service to expose that app using kubernetes.</p> <p>The setup is very simple:</p> <p>app-pod.yml</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: hello-pod labels: app: web spec: containers: - name: web-ctr image: nigelpoulton/getting-started-k8s:1.0 ports: - containerPort: 8080 </code></pre> <p>And the nodeport service:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: ps-nodeport spec: type: NodePort ports: - port: 80 targetPort: 8080 nodePort: 31111 protocol: TCP selector: app: web </code></pre> <p>The service and pod seem to be healthy:</p> <p><a href="https://i.stack.imgur.com/tNLmF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tNLmF.png" alt="enter image description here" /></a></p> <p>But I can't reach the running app:</p> <p><code>locahost:31111</code></p> <p>Give &quot; This site can't be reached message&quot;</p> <p>I am new to this stuff so any help will be appreciated.</p>
<p>In Kubernetes Kind cluster, by default, <code>NodePort</code> may not be bound to <code>localhost</code>. Please check the following resources:</p> <ul> <li><a href="https://kind.sigs.k8s.io/docs/user/quick-start/#mapping-ports-to-the-host-machine" rel="nofollow noreferrer">https://kind.sigs.k8s.io/docs/user/quick-start/#mapping-ports-to-the-host-machine</a></li> <li><a href="https://stackoverflow.com/questions/62432961/how-to-use-nodeport-with-kind">How to use NodePort with kind?</a></li> </ul>
<p>I am trying to setup google kubernetes engine and its pods has to communicate with cloud sql database. The cloud sql database credentials are stored on google cloud secret manger. How pods will fetch credentials from secret manager and if secret manager credentials are updated than how pod will get update the new secret?</p> <p>How to setup above requirement? Can you someone please help on the same?</p> <p>Thanks, Anand</p>
<p>You can find information regarding that particular solution in this <a href="https://cloud.google.com/secret-manager/docs/using-other-products#google-kubernetes-engine" rel="nofollow noreferrer">doc</a>.<br /> There are also good examples on medium <a href="https://medium.com/google-cloud/consuming-google-secret-manager-secrets-in-gke-911523207a79" rel="nofollow noreferrer">here</a> and <a href="https://alessio-trivisonno.medium.com/injecting-secrets-in-gke-with-secret-manager-fd961bbeea73" rel="nofollow noreferrer">here</a>.</p> <p>To answer your question regarding updating the secrets:<br /> Usually secrets are pulled when the container is being created, but if you expect the credentials to change often (or for the pods to stick around for very long) you can adjust the code to update the secrets on every execution.</p>
<p>I'm trying to expose a port 8080 on a pod, so I can wget directly from server. With port-forward everything works fine (<code>kubectl --namespace jenkins port-forward pods/jenkins-6f8b486759-6vwkj 9000:8080</code>) , I'm able to connect to 127.0.0.1:9000</p> <p>But when I try to avoid port-forward and open ports permanently (<code>kubectl expose deployment jenkins --type=LoadBalancer -njenkins</code>): I see it in svc (<code>kubectl describe svc jenkins -njenkins</code>):</p> <pre><code>Name: jenkins Namespace: jenkins Labels: &lt;none&gt; Annotations: &lt;none&gt; Selector: app=jenkins Type: LoadBalancer IP Families: &lt;none&gt; IP: 10.111.244.192 IPs: 10.111.244.192 Port: port-1 8080/TCP TargetPort: 8080/TCP NodePort: port-1 31461/TCP Endpoints: 172.17.0.2:8080 Port: port-2 50000/TCP TargetPort: 50000/TCP NodePort: port-2 30578/TCP Endpoints: 172.17.0.2:50000 Session Affinity: None External Traffic Policy: Cluster Events: &lt;none&gt; </code></pre> <p>but port is still not up, <code>netstat</code> does not show anything. How it should be done correctly?</p> <p>Using minikube version: v1.20.0 , pod yaml just in case:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: jenkins spec: replicas: 1 selector: matchLabels: app: jenkins template: metadata: labels: app: jenkins spec: securityContext: containers: - name: jenkins image: jenkins/jenkins:lts ports: - name: http-port containerPort: 8080 hostPort: 8080 - name: jnlp-port containerPort: 50000 volumeMounts: - name: task-pv-storage mountPath: /var/jenkins_home volumes: - name: task-pv-storage persistentVolumeClaim: claimName: task-pv-claim </code></pre>
<p>I see that you are running your k8s cluster locally, in this case, LoadBalancer ServiceType is not recommended as this type uses cloud providers' load balancer to expose services externally. You might use a self-hosted or hardware load balancer but I suppose it's a bit overkill for minikube cluster.</p> <p>In your minikube deployment, I'd suggest using NodePort Service Type as it uses IP address of your node to expose service. Example YAML:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: jenkins-service spec: type: NodePort selector: app: jenkins ports: - port: 8080 targetPort: 8080 # nodePort field is optional, Kubernetes will allocate port from a range 30000-32767, but you can choose nodePort: 30007 - port: 50000 targetPort: 50000 nodePort: 30008 </code></pre> <p>Then, you can access your app on <code>&lt;NodeIP&gt;:&lt;nodePort&gt;</code>. If you want to read more about k8s Services go <a href="https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types" rel="nofollow noreferrer">here</a>.</p>
<p>I am trying to setup google kubernetes engine and its pods has to communicate with cloud sql database. The cloud sql database credentials are stored on google cloud secret manger. How pods will fetch credentials from secret manager and if secret manager credentials are updated than how pod will get update the new secret?</p> <p>How to setup above requirement? Can you someone please help on the same?</p> <p>Thanks, Anand</p>
<p>You can make your deployed application get the secret (password) programmatically, from Google Cloud Secret Manager. You can find and example in many languages in the following link: <a href="https://cloud.google.com/secret-manager/docs/samples/secretmanager-access-secret-version" rel="nofollow noreferrer">https://cloud.google.com/secret-manager/docs/samples/secretmanager-access-secret-version</a></p> <p>But before make sure that your GKE setup, more specifically your application is able to authenticate to Google Cloud Secret Manager. The following links can help you to choose the appropriate approche:</p> <ul> <li><a href="https://cloud.google.com/kubernetes-engine/docs/tutorials/authenticating-to-cloud-platform" rel="nofollow noreferrer">https://cloud.google.com/kubernetes-engine/docs/tutorials/authenticating-to-cloud-platform</a></li> <li><a href="https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity" rel="nofollow noreferrer">https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity</a></li> </ul>
<p>I'm trying to deploy a Flask python API to Kubernetes (EKS). I've got the Dockerfile setup, but with some weird things going on.</p> <p><code>Dockerfile</code>:</p> <pre><code>FROM python:3.8 WORKDIR /app COPY . /app RUN pip3 install -r requirements.txt EXPOSE 43594 ENTRYPOINT [&quot;python3&quot;] CMD [&quot;app.py&quot;] </code></pre> <p>I build the image running <code>docker build -t store-api .</code>.</p> <p>When I try running the container and hitting an endpoint, I get <code>socker hung up</code>. However, if I run the image doing</p> <pre class="lang-sh prettyprint-override"><code>docker run -d -p 43594:43594 store-api </code></pre> <p>I can successfully hit the endpoint with a response.</p> <p><strong>My hunch is the port mapping.</strong></p> <p>Now having said all that, running the image in a Kubernetes pod, I cannot get anything back from the endpoint and get <code>socket hung up</code>.</p> <p>My question is, how do I explicitly add port mapping to my Kubernetes deployment/service?</p> <p>Part of the <code>Deployment.yaml</code>:</p> <pre class="lang-yaml prettyprint-override"><code> spec: containers: - image: store-api name: store-api ports: - containerPort: 43594 resources: {} volumeMounts: - mountPath: /usr/local/bin/wait-for-it.sh name: store-api-claim0 imagePullPolicy: Always </code></pre> <p><code>Service.yaml</code>:</p> <pre><code>spec: type: LoadBalancer ports: - port: 43594 protocol: TCP targetPort: 43594 selector: app: store-api status: loadBalancer: {} </code></pre> <p>If I port forward using <code>kubectl port-forward deployment/store-api 43594:43594</code> and post the request to <code>localhost:43594/</code> it works fine.</p>
<p><em>This is a community wiki answer posted for better visibility. Feel free to expand it.</em></p> <p><strong>Problem</strong></p> <p>Output for <code>kubectl describe service &lt;name_of_the_service&gt;</code> command contains <code>Endpoints: &lt;none&gt;</code></p> <p><strong>Some theory</strong></p> <p>From Kubernetes Glossary:</p> <p><a href="https://kubernetes.io/docs/reference/glossary/?all=true#term-service" rel="nofollow noreferrer">Service</a></p> <blockquote> <p>An abstract way to expose an application running on a set of Pods as a network service. The set of Pods targeted by a Service is (usually) determined by a selector. If more Pods are added or removed, the set of Pods matching the selector will change. The Service makes sure that network traffic can be directed to the current set of Pods for the workload.</p> </blockquote> <p><a href="https://kubernetes.io/docs/reference/glossary/?all=true#term-endpoints" rel="nofollow noreferrer">Endpoints</a></p> <blockquote> <p>Endpoints track the IP addresses of Pods with matching selectors.</p> </blockquote> <p><a href="https://kubernetes.io/docs/reference/glossary/?all=true#term-selector" rel="nofollow noreferrer">Selector</a>:</p> <p>Allows users to filter a list of resources based on labels. Selectors are applied when querying lists of resources to filter them by labels.</p> <p><strong>Solution</strong></p> <p>Labels in <code>spec.template.metadata.labels</code> of the Deployment should be the same as in <code>spec.selector</code> from the Service.</p> <p>Additional information related to such issue can be found at <a href="https://kubernetes.io/docs/tasks/debug-application-cluster/debug-service/#does-the-service-have-any-endpoints" rel="nofollow noreferrer">Kubernetes site</a>:</p> <blockquote> <p>If the ENDPOINTS column is &lt;none&gt;, you should check that the spec.selector field of your Service actually selects for metadata.labels values on your Pods.</p> </blockquote>
<p>I have an application running on Kubernetes that needs to access SMB shares that are configured dynamically (host, credentials, etc) within said application. I am struggling to achieve this (cleanly) with Kubernetes.</p> <p>I am facing several difficulties:</p> <ul> <li>I do not want &quot;a&quot; storage, I want explicitly specified SMB shares</li> <li>These shares are dynamically defined within the application and not known beforehand</li> <li>I have a variable amount of shares and a single pod needs to be able to access all of them</li> </ul> <p>We currently have a solution where, on each kubernetes worker node, all shares are mounted to mountpoints in a common folder. This folder is then given as <code>HostPath</code> volume to the containers that need access to those storages. Finally, each of those containers has a logic to access the subfolder(s) matching the storage(s) he needs.</p> <p>The downside, and the reason why I'm looking for a cleaner alternative, is:</p> <ul> <li><code>HostPath</code> volumes present security risks</li> <li>For this solution, I need something outside Kubernetes that mounts the SMB shares automatically on each Kubernetes node</li> </ul> <p>Is there a better solution that I am missing?</p> <p>The Kubernetes object that seems to match this approach the most closely is the Projected Volume, since it &quot;maps existing volume sources into the same directory&quot;. However, it doesn't support the type of volume source I need and I don't think it is possible to add/remove volume sources dynamically without restarting the pods that use this Projected Volume.</p>
<p>For sure your current solution using HostPath on the nodes is not flexible, not secure thus it is not a good practice.</p> <p>I think you should consider using one of the custom drivers for your SMB shares:</p> <ul> <li><a href="https://github.com/fstab/cifs#cifs-flexvolume-plugin-for-kubernetes" rel="nofollow noreferrer">CIFS FlexVolume Plugin</a> - older solution, not maintained</li> <li><a href="https://github.com/kubernetes-csi/csi-driver-smb#smb-csi-driver-for-kubernetes" rel="nofollow noreferrer">SMB CSI Driver</a> - actively developed (recommended)</li> </ul> <hr /> <p><strong>CIFS FlexVolume Plugin</strong>:</p> <p>This solution is older and it is replaced by a CSI Driver. The advantage compared to CSI is that you can specify <a href="https://github.com/fstab/cifs#running" rel="nofollow noreferrer">SMB shares directly from the pod definition (including credentials as Kubernetes secret) as you prefer</a>.</p> <p><a href="https://github.com/fstab/cifs#installing" rel="nofollow noreferrer">Here</a> you can find instructions on how to install this plugin on your cluster.</p> <p><strong>SMB CSI Driver</strong>:</p> <p>This driver will automatically take care of <a href="https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/v1.4.0/csi-smb-node.yaml" rel="nofollow noreferrer">mounting SMB shares on all nodes by using DaemonSet</a>.</p> <p>You can install SMB CSI Driver either by <a href="https://github.com/kubernetes-csi/csi-driver-smb/blob/master/docs/install-csi-driver-master.md#install-smb-csi-driver-master-version-on-a-kubernetes-cluster" rel="nofollow noreferrer">bash script</a> or by using <a href="https://github.com/kubernetes-csi/csi-driver-smb/tree/master/charts" rel="nofollow noreferrer">a helm chart</a>.</p> <p>Assuming you have your SMB server ready, you can use one of the following solution to access it from your pod:</p> <ul> <li><a href="https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/example/e2e_usage.md#option1-storage-class-usage" rel="nofollow noreferrer">Storage class</a></li> <li><a href="https://github.com/kubernetes-csi/csi-driver-smb/blob/master/deploy/example/e2e_usage.md#option2-pvpvc-usage" rel="nofollow noreferrer">PV/PVC</a></li> </ul> <p>In both cases you have to use a previously created secret with the credentials.</p> <p>In your case, for every SMB share you should create a Storage class / PV and mount it to the pod.</p> <p>The advantage of CSI Driver is that it is <a href="https://medium.com/flant-com/kubernetes-volume-plugins-from-flexvolume-to-csi-c9a011d2670d" rel="nofollow noreferrer">newer, currently maintained solution and it replaced FlexVolume</a>.</p> <p>Below is diagram representing how CSI plugin operates: <img src="https://miro.medium.com/max/2400/0*I4HPfmFAGgM6-oGw" alt="" /></p> <p>Also check:</p> <ul> <li><a href="https://medium.com/flant-com/kubernetes-volume-plugins-from-flexvolume-to-csi-c9a011d2670d" rel="nofollow noreferrer">Kubernetes volume plugins evolution from FlexVolume to CSI</a></li> <li><a href="https://kubernetes.io/blog/2018/01/introducing-container-storage-interface/" rel="nofollow noreferrer">Introducing Container Storage Interface (CSI) Alpha for Kubernetes</a></li> </ul>
<p>Assuming I have a Kubernetes Deployment object with the <code>Recreate</code> strategy and I update the Deployment with a new container image version. Kubernetes will:</p> <ol> <li>scale down/kill the existing Pods of the Deployment,</li> <li>create the new Pods,</li> <li>which will pull the new container images</li> <li>so the new containers can finally run.</li> </ol> <p>Of course, the <code>Recreate</code> strategy is exepected to cause a downtime between steps 1 and 4, where no Pod is actually running. However, step 3 can take a lot of time if the container images in question are or the container registry connection is slow, or both. In a test setup (Azure Kubernetes Services pulling a Windows container image from Docker Hub), I see it taking 5 minutes and more, which makes for a really long downtime.</p> <p>So, what is a good option to reduce that downtime? Can I somehow get Kubernetes to pull the new images before killing the Pods in step 1 above? (Note that the solution should work with Windows containers, which are notoriously large, in case that is relevant.)</p> <p>On the Internet, I have found <a href="https://codefresh.io/kubernetes-tutorial/single-use-daemonset-pattern-pre-pulling-images-kubernetes/" rel="nofollow noreferrer">this Codefresh article using a DaemonSet and Docker in Docker</a>, but I guess <a href="https://kubernetes.io/blog/2020/12/02/dont-panic-kubernetes-and-docker/#so-why-the-confusion-and-what-is-everyone-freaking-out-about" rel="nofollow noreferrer">Docker in Docker is no longer compatible with containerd</a>.</p> <p>I've also found <a href="https://stackoverflow.com/a/59588935/62838">this StackOverflow answer</a> that suggests using an Azure Container Registry with Project Teleport, but that is in private preview and doesn't support Windows containers yet. Also, it's specific to Azure Kubernetes Services, and I'm looking for a more general solution.</p> <p>Surely, this is a common problem that has a &quot;standard&quot; answer?</p> <p><strong>Update 2021-12-21:</strong> Because I've got a corresponding answer, I'll clarify that I cannot easily change the deployment strategy. The application in question does not support running Pods of different versions at the same time because it uses a database that needs to be migrated to the corresponding application version, without forwards or backwards compatibility.</p>
<p>Via <a href="https://www.reddit.com/r/kubernetes/comments/oeruh9/can_kubernetes_prepull_and_cache_images/" rel="nofollow noreferrer">https://www.reddit.com/r/kubernetes/comments/oeruh9/can_kubernetes_prepull_and_cache_images/</a>, I've found these ideas:</p> <ul> <li>Implement a DaemonSet that runs a &quot;sleep&quot; loop on all the images I need.</li> <li>Use <a href="http://github.com/mattmoor/warm-image" rel="nofollow noreferrer">http://github.com/mattmoor/warm-image</a>, which has no Windows support.</li> <li>Use <a href="https://github.com/ContainerSolutions/ImageWolf" rel="nofollow noreferrer">https://github.com/ContainerSolutions/ImageWolf</a>, which says, &quot;ImageWolf is currently alpha software and intended as a PoC - please don't run it in production!&quot;</li> <li>Use <a href="https://github.com/uber/kraken" rel="nofollow noreferrer">https://github.com/uber/kraken</a>, which seems to be a registry, not a pre-pulling solution.</li> <li>Use <a href="https://github.com/dragonflyoss/Dragonfly" rel="nofollow noreferrer">https://github.com/dragonflyoss/Dragonfly</a> (now <a href="https://github.com/dragonflyoss/Dragonfly2" rel="nofollow noreferrer">https://github.com/dragonflyoss/Dragonfly2</a>), which also seems to do somethings completely different.</li> <li>Use <a href="https://github.com/senthilrch/kube-fledged" rel="nofollow noreferrer">https://github.com/senthilrch/kube-fledged</a>, which looks exactly right and more mature than the others, but <a href="https://github.com/senthilrch/kube-fledged/issues/118" rel="nofollow noreferrer">has no Windows support</a>.</li> <li>Use <a href="https://github.com/dcherman/image-cache-daemon" rel="nofollow noreferrer">https://github.com/dcherman/image-cache-daemon</a>, which <a href="https://hub.docker.com/r/exiges/image-cache-daemon/tags" rel="nofollow noreferrer">has no Windows support</a>.</li> <li>Use <a href="https://goharbor.io/blog/harbor-2.1/" rel="nofollow noreferrer">https://goharbor.io/blog/harbor-2.1/</a>, which also seems to be a registry, not a pre-pulling solution.</li> <li>Use <a href="https://openkruise.io/docs/user-manuals/imagepulljob/" rel="nofollow noreferrer">https://openkruise.io/docs/user-manuals/imagepulljob/</a>, which also looks right, but a) OpenKruise is huge and I'm not sure I want to install this just to preload images, and b) it seems <a href="https://hub.docker.com/r/openkruise/kruise-manager/tags" rel="nofollow noreferrer">it has no Windows support</a>.</li> </ul> <p>So, it seems I have to implement this on my own, with a DaemonSet. I still hope someone can provide a better answer than this one 🙂 .</p>
<p>Promtail, Grafana, Loki version is 2.4.1. running is Kubernetes.</p> <p>I was following the <a href="https://grafana.com/docs/loki/latest/clients/promtail/stages/multiline/#custom-log-format" rel="nofollow noreferrer">documentation</a>.</p> <ul> <li>The exception in the log matches the regular expression. (ZeroWidthSpace is at the beginning of a log line)</li> <li>multiline stage is set see the attached configuration (promtail.yaml)</li> </ul> <p>I was expecting that error stacktrace will be in a single entry in grafana/loki but every line is a separate entry. Am I missing some configs?</p> <pre><code># cat /etc/promtail/promtail.yaml server: log_level: info http_listen_port: 3101 client: url: http://***-loki:3100/loki/api/v1/push positions: filename: /run/promtail/positions.yaml scrape_configs: # See also https://github.com/grafana/loki/blob/master/production/ksonnet/promtail/scrape_config.libsonnet for reference - job_name: kubernetes-pods pipeline_stages: - multiline: firstline: ^\x{200B}\[ max_lines: 128 max_wait_time: 3s kubernetes_sd_configs: - role: pod relabel_configs: - source_labels: - __meta_kubernetes_pod_controller_name regex: ([0-9a-z-.]+?)(-[0-9a-f]{8,10})? action: replace target_label: __tmp_controller_name - source_labels: - __meta_kubernetes_pod_label_app_kubernetes_io_name - __meta_kubernetes_pod_label_app - __tmp_controller_name - __meta_kubernetes_pod_name regex: ^;*([^;]+)(;.*)?$ action: replace target_label: app - source_labels: - __meta_kubernetes_pod_label_app_kubernetes_io_component - __meta_kubernetes_pod_label_component regex: ^;*([^;]+)(;.*)?$ action: replace target_label: component - action: replace source_labels: - __meta_kubernetes_pod_node_name target_label: node_name - action: replace source_labels: - __meta_kubernetes_namespace target_label: namespace - action: replace replacement: $1 separator: / source_labels: - namespace - app target_label: job - action: replace source_labels: - __meta_kubernetes_pod_name target_label: pod - action: replace source_labels: - __meta_kubernetes_pod_container_name target_label: container - action: replace replacement: /var/log/pods/*$1/*.log separator: / source_labels: - __meta_kubernetes_pod_uid - __meta_kubernetes_pod_container_name target_label: __path__ - action: replace regex: true/(.*) replacement: /var/log/pods/*$1/*.log separator: / source_labels: - __meta_kubernetes_pod_annotationpresent_kubernetes_io_config_hash - __meta_kubernetes_pod_annotation_kubernetes_io_config_hash - __meta_kubernetes_pod_container_name target_label: __path__ </code></pre>
<p>It turned out that the logs look different than what we see in lens pod logs or <code>kubectl logs {pod}</code>.</p> <p>The original logs consumed by promtail can be found on the host machine:</p> <pre><code>minikube ssh cat /var/log/pods/{namespace}_{pod}/{container}/0.log </code></pre> <p>They look something like this:</p> <pre><code>{&quot;log&quot;:&quot;​[default-nioEventLoopGroup-1-1] INFO HTTP_ACCESS_LOGGER - \&quot;GET /health/readiness HTTP/1.1\&quot; 200 523\n&quot;,&quot;stream&quot;:&quot;stdout&quot;,&quot;time&quot;:&quot;2021-12-17T12:26:29.702621198Z&quot;} </code></pre> <p>So, the firstline regexp did not match any log line. Unfortunatly, there are no errors about this in the promtail logs.</p> <p>This is the docker log format and there is a pipeline stage to parse this:</p> <pre><code>- docker: {} </code></pre> <p>Additionally there was an issue in the logs. There were extra line breaks in the multi line stacktrace, so this additional pipeline stage filters them:</p> <pre><code>- replace: expression: '(\n)' replace: '' </code></pre> <p>So my working config looks like this:</p> <pre><code>server: log_level: info http_listen_port: 3101 client: url: http://***-loki:3100/loki/api/v1/push positions: filename: /run/promtail/positions.yaml scrape_configs: # See also https://github.com/grafana/loki/blob/master/production/ksonnet/promtail/scrape_config.libsonnet for reference - job_name: kubernetes-pods pipeline_stages: - docker: {} - multiline: firstline: ^\x{200B}\[ max_lines: 128 max_wait_time: 3s - replace: expression: (\n) replace: &quot;&quot; #config continues below (not copied) </code></pre>
<p>Assuming I have a Kubernetes Deployment object with the <code>Recreate</code> strategy and I update the Deployment with a new container image version. Kubernetes will:</p> <ol> <li>scale down/kill the existing Pods of the Deployment,</li> <li>create the new Pods,</li> <li>which will pull the new container images</li> <li>so the new containers can finally run.</li> </ol> <p>Of course, the <code>Recreate</code> strategy is exepected to cause a downtime between steps 1 and 4, where no Pod is actually running. However, step 3 can take a lot of time if the container images in question are or the container registry connection is slow, or both. In a test setup (Azure Kubernetes Services pulling a Windows container image from Docker Hub), I see it taking 5 minutes and more, which makes for a really long downtime.</p> <p>So, what is a good option to reduce that downtime? Can I somehow get Kubernetes to pull the new images before killing the Pods in step 1 above? (Note that the solution should work with Windows containers, which are notoriously large, in case that is relevant.)</p> <p>On the Internet, I have found <a href="https://codefresh.io/kubernetes-tutorial/single-use-daemonset-pattern-pre-pulling-images-kubernetes/" rel="nofollow noreferrer">this Codefresh article using a DaemonSet and Docker in Docker</a>, but I guess <a href="https://kubernetes.io/blog/2020/12/02/dont-panic-kubernetes-and-docker/#so-why-the-confusion-and-what-is-everyone-freaking-out-about" rel="nofollow noreferrer">Docker in Docker is no longer compatible with containerd</a>.</p> <p>I've also found <a href="https://stackoverflow.com/a/59588935/62838">this StackOverflow answer</a> that suggests using an Azure Container Registry with Project Teleport, but that is in private preview and doesn't support Windows containers yet. Also, it's specific to Azure Kubernetes Services, and I'm looking for a more general solution.</p> <p>Surely, this is a common problem that has a &quot;standard&quot; answer?</p> <p><strong>Update 2021-12-21:</strong> Because I've got a corresponding answer, I'll clarify that I cannot easily change the deployment strategy. The application in question does not support running Pods of different versions at the same time because it uses a database that needs to be migrated to the corresponding application version, without forwards or backwards compatibility.</p>
<p>Implement a &quot;blue-green&quot; deployment strategy. For instance, the service might be running and active in the &quot;blue&quot; state. A new deployment is created with a new container image, which deploys the &quot;green&quot; pods with the new container image. When all of the &quot;green&quot; pods are ready, the &quot;switch live&quot; step is run, which switches the active color. Very little downtime.</p> <p>Obviously, this has tradeoffs. Your cluster will need more memory to run the additional transitional pods. The deployment process will be more complex.</p>
<p>I have a deployment file with replicas set to 1. So when I do 'kubectl get ...' I get 1 record each for deployment, replicaset and pod.</p> <p>Now I set replicas to 2 in deployment.yaml, apply it and when I run 'kubectl get ..' command, I get 2 records each for deployments, replicaset and pods each.</p> <p>Shouldn't previous deployment be overwritten, hence resulting in a single deployment, and similar for replicaset(2 pods are ok as now replicas is set to 2)?</p> <p>This is deployment file content:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.16 ports: - containerPort: 80 </code></pre>
<p><code>...Now I set replicas to 2 in deployment.yaml, apply it and when I run 'kubectl get ..' command, I get 2 records each for deployments, replicaset and pods each.</code></p> <p>Can you try <code>kubectl get deploy --field-selector metadata.name=nginx-deployment</code>. You should get just 1 deployment. The number of pods should follow this deployment's <code>replicas</code>.</p>
<p>I have created kubernetes ingress with frontend config and the ECDSA P-384 TLS cert on Google Cloud Platform, after few seconds of creating process i received the followind error:</p> <blockquote> <p>Error syncing to GCP: error running load balancer syncing routine: loadbalancer <em><strong><strong><strong>-default-</strong></strong></strong>-ingress-</em>****** does not exist: Cert creation failures - k8s2-cr-<em><strong><strong>-</strong></strong></em><em><strong><strong><strong><strong><strong><strong>-</strong></strong></strong></strong></strong></strong></em>***** Error:googleapi: Error 400: The ECDSA curve is not supported., sslCertificateUnsupportedCurve</p> </blockquote> <p>Why The ECDSA curve is not supported? Is there any way to enable this support?</p> <p>Create tls-secret command:</p> <pre><code>kubectl create secret tls tls --key [key-path] --cert [cert-path] </code></pre> <p>Frontend-config:</p> <pre><code>apiVersion: networking.gke.io/v1beta1 kind: FrontendConfig metadata: name: frontend-config spec: redirectToHttps: enabled: true responseCodeName: MOVED_PERMANENTLY_DEFAULT </code></pre> <p>Ingress:</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress namespace: default labels: kind: ingress annotations: networking.gke.io/v1beta1.FrontendConfig: frontend-config spec: tls: - hosts: - '*.mydomain.com' secretName: tls rules: - host: mydomain.com http: paths: - path: /* pathType: ImplementationSpecific backend: service: name: spa-ingress-service port: number: 80 - host: api.mydomain.com http: paths: - path: /* pathType: ImplementationSpecific backend: service: name: api-ingress-service port: number: 80 </code></pre> <p>spa services:</p> <pre><code># SERVICE LOAD BALANCER apiVersion: v1 kind: Service metadata: name: spa-service labels: app/name: spa spec: type: LoadBalancer selector: app/template: spa ports: - name: http protocol: TCP port: 80 targetPort: http --- # SERVICE NODE PORT - FOR INGRESS apiVersion: v1 kind: Service metadata: name: spa-ingress-service labels: app/name: ingress.spa spec: type: NodePort selector: app/template: spa ports: - name: https protocol: TCP port: 80 targetPort: http </code></pre> <p>api services:</p> <pre><code># SERVICE LOAD BALANCER apiVersion: v1 kind: Service metadata: name: api-service labels: app/name: api spec: type: LoadBalancer selector: app/template: api ports: - name: http protocol: TCP port: 80 targetPort: http --- # SERVICE NODE PORT - FOR INGRESS apiVersion: v1 kind: Service metadata: name: api-ingress-service labels: app/name: ingress.api spec: type: NodePort selector: app/template: api ports: - name: https protocol: TCP port: 80 targetPort: http </code></pre> <p>kubectl describe ingress response:</p> <p><img src="https://i.stack.imgur.com/Ywsie.jpg" alt="describe" /></p>
<p>The gcp <a href="https://cloud.google.com/load-balancing/docs/ssl-certificates/self-managed-certs#private-key" rel="nofollow noreferrer">load balancer</a> supports <strong>RSA-2048 or ECDSA P-256</strong> certificates. Also DownstreamTlsContexts support multiple TLS certificates. These may be a mix of RSA and <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/security/ssl#certificate-selection" rel="nofollow noreferrer">P-256 ECDSA</a> certificates.</p> <p>The following error is due to the incompatibility with the P-384 certificate currently being used rather than the P-256 certificate.</p> <p>For additional information refer to the <a href="https://cloud.google.com/load-balancing/docs/l7-internal" rel="nofollow noreferrer">Load Balancing Overview</a>.</p>
<p>In a Deployment, under what circumstances would the matchLabels in the selector not precisely match the template metadata labels? If they didn't match, any pod created wouldn't match the selector, and I'd imagine K8s would go on creating new pods until every node is full. If that's true, why does K8s want us to specify the same labels twice? Either I'm missing something or this violates the DRY principle.</p> <p>The only thing I can think of would be creating a Deployment with matchLabels &quot;key: A&quot; &amp; &quot;key: B&quot; that simultaneously puts existing/un-owned pods that have label &quot;key: A&quot; into the Deployment while at the same time any new pods get label &quot;key: B&quot;. But even then, it feels like any label in the template metadata should automatically be in the selector matchLabels.</p> <p>K8s docs give the following example:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 </code></pre>
<p><code>...In a Deployment, under what circumstances would the matchLabels in the selector not precisely match the template metadata labels?</code></p> <p>Example when doing <a href="https://kubernetes.io/docs/concepts/cluster-administration/manage-deployment/#canary-deployments" rel="nofollow noreferrer">canary deployment</a>.</p> <p><code>...If they didn't match, any pod created wouldn't match the selector, and I'd imagine K8s would go on creating new pods until every node is full.</code></p> <p>Your deployment will not proceed, it will fail with error message <code>&quot;selector&quot; does not match template &quot;labels&quot;</code>. No pod will be created.</p> <p><code>...it feels like any label in the template metadata should automatically be in the selector matchLabels.</code></p> <p>Labels under template.metadata are used for many purposes and not only for deployment, example labels added by CNI pertain to IP on the fly. Labels meant for selector should be minimum and specific.</p>
<p>When using <a href="https://docs.gitlab.com/ee/topics/autodevops/" rel="nofollow noreferrer">GitLab Auto DevOps</a> to build and deploy application from my repository to <a href="https://microk8s.io/" rel="nofollow noreferrer">microk8s</a>, the build jobs often take a long time to run, eventually timing out. The issue happens 99% of the time, but some builds run through. Often, the build stops at a different time in the build script.</p> <p>The projects do not contain a <code>.gitlab-ci.yml</code> file and fully rely on the Auto DevOps feature to do its magic.</p> <p>For Spring Boot/Java projects, the build often fails when downloading the Gradle via the Gradle wrapper, other times it fails while downloading the dependencies itself. The error message is very vague and not helpful at all:</p> <pre><code>Step 5/11 : RUN /bin/herokuish buildpack build ---&gt; Running in e9ec110c0dfe -----&gt; Gradle app detected -----&gt; Spring Boot detected The command '/bin/sh -c /bin/herokuish buildpack build' returned a non-zero code: 35 </code></pre> <p>Sometimes, if you get lucky, the error is different:</p> <pre><code>Step 5/11 : RUN /bin/herokuish buildpack build ---&gt; Running in fe284971a79c -----&gt; Gradle app detected -----&gt; Spring Boot detected -----&gt; Installing JDK 11... done -----&gt; Building Gradle app... -----&gt; executing ./gradlew build -x check Downloading https://services.gradle.org/distributions/gradle-7.0-bin.zip ..........10%...........20%...........30%..........40%...........50%...........60%...........70%..........80%...........90%...........100% To honour the JVM settings for this build a single-use Daemon process will be forked. See https://docs.gradle.org/7.0/userguide/gradle_daemon.html#sec:disabling_the_daemon. Daemon will be stopped at the end of the build &gt; Task :compileJava &gt; Task :compileJava FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':compileJava'. &gt; Could not download netty-resolver-dns-native-macos-4.1.65.Final-osx-x86_64.jar (io.netty:netty-resolver-dns-native-macos:4.1.65.Final) &gt; Could not get resource 'https://repo.maven.apache.org/maven2/io/netty/netty-resolver-dns-native-macos/4.1.65.Final/netty-resolver-dns-native-macos-4.1.65.Final-osx-x86_64.jar'. &gt; Could not GET 'https://repo.maven.apache.org/maven2/io/netty/netty-resolver-dns-native-macos/4.1.65.Final/netty-resolver-dns-native-macos-4.1.65.Final-osx-x86_64.jar'. &gt; Read timed out </code></pre> <p>For React/TypeScript problems, the symptoms are similar but the error itself manifests in a different way:</p> <pre><code>[INFO] Using npm v8.1.0 from package.json /cnb/buildpacks/heroku_nodejs-npm/0.4.4/lib/build.sh: line 179: /layers/heroku_nodejs-engine/toolbox/bin/yj: Permission denied ERROR: failed to build: exit status 126 ERROR: failed to build: executing lifecycle: failed with status code: 145 </code></pre> <p>The problem seems to occur mostly when the GitLab runners itself are deplyoed in Kubernetes. microk8s uses <a href="https://projectcalico.docs.tigera.io/getting-started/kubernetes/" rel="nofollow noreferrer">Project Calico</a> to implement virtual networks.</p> <p>What gives? Why are the error messages to unhelpful? Is there a way to turn up verbose build logs or debug the build steps?</p>
<p>This seems to be a networking problem caused by incompatbile MTU settings between the Calico network layer and Docker's network configuration (and an inability to autoconfige the MTU correctly?) When the MTU values don't match, network packets get fragmented and the Docker runners fail to complete TLS handshakes. As far as I understand, this only affects DIND (docker-in-docker) runners.</p> <p>Even finding this out requires jumping through a few hoops. You have to:</p> <ol> <li>Start a CI pipeline and wait for the job to &quot;hang&quot;</li> <li><code>kubectl exec</code> into the current/active GitLab runner pod</li> <li>Find out the correct value for the <code>DOCKER_HOST</code> environment variable (e.g. by grepping through <code>/proc/$pid/environ</code>. Very likely, this will be <code>tcp://localhost:2375</code>.</li> <li>Export the value to be used by the <code>docker</code> client: <code>export DOCKER_HOST=tcp://localhost:2375</code></li> <li><code>docker ps</code> and then <code>docker exec</code> into the actual CI job container</li> <li>Use ping and other tools to find proper MTU values (but MTU for what? Docker, Calico, OS, router, …?). Use curl/openssl to verify that (certain) https sites cause problems from inside the DIND container.</li> </ol> <p>Execute</p> <pre><code>microk8s kubectl get -n kube-system cm calico-config -o yaml </code></pre> <p>and look for the <code>veth_mtu</code> value, which will very likely be set to <code>1440</code>. DIND uses the same MTU and thus fails send or receive certain network packages (each virtual network needs to add its own header to the network packet, which adds a few bytes at every layer).</p> <p>The naïve fix would be to change the Calico settings to a higher or lower value, but somehow this did not really work, even after the Calico deployment. Furthermore, the value seems to be reset to its original value from time to time; probably caused by automatic updates to microk8s (which comes as a <a href="https://snapcraft.io/" rel="nofollow noreferrer">Snap</a>).</p> <p>So what is a solution that actually works and is permanent? It is possible to override DIND settings for Auto DevOps by writing a custom <code>.gitlab-ci.yml</code> file and simply includes the Auto DevOps template:</p> <pre class="lang-yaml prettyprint-override"><code>build: services: - name: docker:20.10.6-dind # make sure to update version command: ['--tls=false', '--host=tcp://0.0.0.0:2375', '--mtu=1240'] include: - template: Auto-DevOps.gitlab-ci.yml </code></pre> <p>The <code>build.services</code> definition is copied from the <a href="https://gitlab.com/gitlab-org/gitlab-foss/-/blob/master/lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml" rel="nofollow noreferrer"><code>Jobs/Build.gitlab-ci</code></a> template and extended with an additional <code>--mtu</code> option.</p> <p>I've had good experience so far by setting the DIND MTU to 1240, which is 200 bytes lower than Calico's MTU. As an added bonus, it doesn't affect any other pods' network settings. And for CI builds I can live with non-optimal network settings.</p> <p>References:</p> <ul> <li><a href="https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27300" rel="nofollow noreferrer">https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27300</a></li> <li><a href="https://projectcalico.docs.tigera.io/networking/mtu" rel="nofollow noreferrer">https://projectcalico.docs.tigera.io/networking/mtu</a></li> <li><a href="https://liejuntao001.medium.com/fix-docker-in-docker-network-issue-in-kubernetes-cc18c229d9e5" rel="nofollow noreferrer">https://liejuntao001.medium.com/fix-docker-in-docker-network-issue-in-kubernetes-cc18c229d9e5</a></li> <li><a href="https://kb.netgear.com/19863/Ping-Test-to-determine-Optimal-MTU-Size-on-Router" rel="nofollow noreferrer">https://kb.netgear.com/19863/Ping-Test-to-determine-Optimal-MTU-Size-on-Router</a></li> </ul>
<p>How to upgrade an existing running deployment with yaml deployment file without changing the number of running replicas of that deployment? So, I need to set the number of replicas on the fly without changing the yaml file.</p> <p>It is like running kubectl apply -f deployment.yaml along with kubectl scale --replicas=3 both together, or in another wards to apply deployment yaml changes with keeping the numebr of running replicas the same as it is.</p> <p>For example: I have a running deployment which already scaled its pods to 5 replicas, need to change deployment parameters within CD (like upgrade container image, change environment variabls, .. etc) without manualy check the #running pods and update the yaml with it, how can achieve this?</p>
<p>Use the kubectl edit command</p> <pre><code>kubectl edit (RESOURCE/NAME | -f FILENAME) E.g. kubectl edit deployment.apps/webapp-deployment </code></pre> <p>It will open an editor. You can update the value for number of replicas in the editor and save.</p> <p>Refer the documentation section - Editing resources <a href="https://kubernetes.io/docs/reference/kubectl/cheatsheet/#editing-resources" rel="nofollow noreferrer">https://kubernetes.io/docs/reference/kubectl/cheatsheet/#editing-resources</a></p>
<p>I am deploying a k8s cluster locally using Kind. The image gets deployed ok and when I view the list of services I see the following</p> <p><a href="https://i.stack.imgur.com/m27JG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m27JG.png" alt="enter image description here" /></a></p> <p>the service I'm trying to access is <code>chatt-service</code> and if you notice the <code>EXTERNAL-IP</code> is pending. I know minikube has a command which makes this accessible, but how do I do it on a <code>Kind</code> cluster ?</p>
<p>for Loadbalancer service type you will not able to get public ip because you're running it locally and you will need to run it in a cloud provider which will provide the LB for you like ALB in aws or LoadBalancer in Digital ocean. however, you can access this service locally using the Kubectl proxy tool.</p> <p>.</p> <pre><code>kubectl port-forward service/chatt-service 3002:3002 </code></pre>
<p>I have deploy my application in kubernetes using deployment.</p> <ol> <li>Whenever user gets login to application pod will generate session for that user.</li> <li>To maintain session stickiness I have set session cookie using Nginx ingress annotations.</li> <li>When hpa scale down pods application user is phasing a logout problem when pod is get terminated. If ingress has generated a session using this pod. It needs to log in again.</li> <li>What I want is some sort of graceful termination of the connection. when pod is in a terminating state it should serve existing sessions until grace period.</li> </ol>
<blockquote> <p>What i want is some sort of graceful termination of connection. when pod is in terminating state it should serve existing sessions until grace period.</p> </blockquote> <p>You can use the key in POD spec : <strong>terminationGracePeriodSeconds</strong></p> <p>this will wait for the mentioned second and after that POD will get terminated.</p> <p>You can read more at : <a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace" rel="nofollow noreferrer">https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace</a></p>
<p>I am trying to install loki with helm</p> <pre><code>$ helm upgrade --install loki grafana/loki-stack </code></pre> <p>I got the following error msg:</p> <pre><code>Release &quot;loki&quot; does not exist. Installing it now. Error: rendered manifests contain a resource that already exists. Unable to continue with install: could not get information about the resource: podsecuritypolicies.policy &quot;loki&quot; is forbidden: User &quot;secret user :)&quot; cannot get resource &quot;podsecuritypolicies&quot; in API group &quot;policy&quot; at the cluster scope $ helm list -all NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION </code></pre> <p>I'm a simple user, but I can make deployment/pods via yaml files manual. I need to use helm charts.</p>
<p>It seems that your User has insufficient privileges to create policies. You need to ask your cluster administrator for more privileges, unless you can assign them yourself to this user. I'm providing example yaml below to achieve that. First, create ClusterRole with proper privileges:</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: &lt;role name&gt; rules: - apiGroups: ['policy'] resources: ['podsecuritypolicies'] verbs: ['get'] </code></pre> <p>Then, you need to bind this ClusterRole to user(s):</p> <pre><code>apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: &lt;binding name&gt; roleRef: kind: ClusterRole name: &lt;role name&gt; apiGroup: rbac.authorization.k8s.io subjects: # Authorize all service accounts in a namespace (recommended): - kind: Group apiGroup: rbac.authorization.k8s.io name: system:serviceaccounts:&lt;authorized namespace&gt; # Authorize specific service accounts (not recommended): - kind: ServiceAccount name: &lt;authorized service account name&gt; namespace: &lt;authorized pod namespace&gt; # Authorize specific users (not recommended): - kind: User apiGroup: rbac.authorization.k8s.io name: &lt;authorized user name&gt; </code></pre> <p>Go <a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/#enabling-pod-security-policies" rel="nofollow noreferrer">here</a> for more detailed explanation.</p>
<p>I have deploy my application in kubernetes using deployment.</p> <ol> <li>Whenever user gets login to application pod will generate session for that user.</li> <li>To maintain session stickiness I have set session cookie using Nginx ingress annotations.</li> <li>When hpa scale down pods application user is phasing a logout problem when pod is get terminated. If ingress has generated a session using this pod. It needs to log in again.</li> <li>What I want is some sort of graceful termination of the connection. when pod is in a terminating state it should serve existing sessions until grace period.</li> </ol>
<p>The answer <a href="https://stackoverflow.com/users/5525824/harsh-manvar">Harsh Manvar</a> is great, However, I want to expand it a bit :)</p> <p>You can of course use <strong>terminationGracePeriodSeconds</strong> in the POD spec. Look at the example yaml:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Pod metadata: name: my-pod spec: containers: - name: my-container image: my-image terminationGracePeriodSeconds: 60 </code></pre> <blockquote> <p>At this point, Kubernetes waits for a specified time called the termination grace period. By default, this is 30 seconds. It’s important to note that this happens in parallel to the preStop hook and the SIGTERM signal. Kubernetes does not wait for the preStop hook to finish.</p> <p>If your app finishes shutting down and exits before the terminationGracePeriod is done, Kubernetes moves to the next step immediately.</p> <p>If your pod usually takes longer than 30 seconds to shut down, make sure you increase the grace period. You can do that by setting the terminationGracePeriodSeconds option in the Pod YAML. For example, to change it to 60 seconds.</p> </blockquote> <p>For more look <a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace" rel="nofollow noreferrer">here</a>.</p> <p>If you want to know how exactly looks like <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/" rel="nofollow noreferrer">pod lifecycle</a> see this link to the official documentation. The part about the <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination" rel="nofollow noreferrer">termination of pods</a> should be most interesting. You will also have it described how exactly the termination takes place.</p> <p>It is recommended that applications deployed on Kubernetes have a design that complies with the recommended standards. One set of standards for modern, cloud-based applications is known as the <a href="https://12factor.net/" rel="nofollow noreferrer">Twelve-Factor App</a>:</p> <blockquote> <p>Twelve-factor processes are stateless and share-nothing. Any data that needs to persist must be stored in a stateful backing service, typically a database. Some web systems rely on “sticky sessions” – that is, caching user session data in memory of the app’s process and expecting future requests from the same visitor to be routed to the same process. Sticky sessions are a violation of twelve-factor and should never be used or relied upon. Session state data is a good candidate for a datastore that offers time-expiration, such as Memcached or Redis.</p> </blockquote>
<p>Unable to mount a Kubernetes secret to <code>${HOME}/.ssh/id_rsa</code> path.</p> <p>Following are my secrets.yaml created using</p> <pre><code> kubectl create secret generic secret-ssh-auth --type=kubernetes.io/ssh-auth --from-file=ssh-privatekey=keys/id_rsa </code></pre> <pre><code>apiVersion: v1 data: ssh-privatekey: abcdefgh kind: Secret metadata: name: secret-ssh-auth namespace: app type: kubernetes.io/ssh-auth --- apiVersion: v1 data: username: YWRtaW4= password: MWYyZDFlMmU2N2Rm kind: Secret metadata: name: mysecret namespace: app type: Opaque </code></pre> <p>Following is my <code>deployment.yaml</code></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: nginx-helm-test labels: helm.sh/chart: helm-test-0.1.0 app.kubernetes.io/name: helm-test app.kubernetes.io/instance: nginx app.kubernetes.io/version: &quot;1.16.0&quot; app.kubernetes.io/managed-by: Helm spec: replicas: 1 selector: matchLabels: app.kubernetes.io/name: helm-test app.kubernetes.io/instance: nginx template: metadata: labels: app.kubernetes.io/name: helm-test app.kubernetes.io/instance: nginx spec: serviceAccountName: nginx-helm-test securityContext: {} containers: - name: helm-test securityContext: {} image: &quot;nginx:1.16.0&quot; imagePullPolicy: IfNotPresent ports: - name: http containerPort: 80 protocol: TCP livenessProbe: httpGet: path: / port: http readinessProbe: httpGet: path: / port: http resources: {} env: - name: HOME value: /root volumeMounts: - mountPath: ${HOME}/.ssh/id_rsa name: sshdir readOnly: true - name: foo mountPath: /etc/foo readOnly: true volumes: - name: sshdir secret: secretName: secret-ssh-auth - name: foo secret: secretName: mysecret </code></pre> <p>All I wanted is to mount the <code>ssh-privatekey</code> value in <code>${HOME}/.ssh/id_rsa</code> but for some reason, the above mount does not happen</p> <p>But at the same time, I was able to see the <code>foo</code> secret correctly in <code>/etc/foo/username</code>. Exhaust to be honest but still want to finish this</p> <p>What am I doing wrong?</p>
<p>K8s Secret <a href="https://kubernetes.io/docs/concepts/configuration/secret/#ssh-authentication-secrets" rel="nofollow noreferrer">type: kubernetes.io/ssh-auth</a> (i.e. ssh-key-secret) does not work out of the box as mount point for <code>SSH</code>, since it mounts it under the filename <code>ssh-privatekey</code>. To fix this you have to do few things:</p> <ol> <li>You need to mount the <code>ssh-privatekey</code> key to <code>id_rsa</code> filename via <a href="https://kubernetes.io/docs/concepts/configuration/secret/#projection-of-secret-keys-to-specific-paths" rel="nofollow noreferrer">secret:items:key projection</a> in your volume definition.</li> <li>Mount the secret so it is NOT group/world readable because the <a href="https://kubernetes.io/docs/concepts/configuration/secret/#secret-files-permissions" rel="nofollow noreferrer">default mode/permissions</a> is <code>0644</code> (i.e. add <code>defaultMode: 0400</code> to your VolumeMount) .</li> </ol> <p>Here is what I believe you need to change in your <code>deployment.yaml</code> to fix this problem:</p> <pre class="lang-yaml prettyprint-override"><code>... volumeMounts: - mountPath: ${HOME}/.ssh name: sshdir readOnly: true volumes: - name: sshdir secret: secretName: secret-ssh-auth defaultMode: 0400 items: - key: ssh-privatekey path: id_rsa </code></pre>
<p>I'm trying kubernetes and making some progress, but I'm running into an issue with ingress when trying to make my hello world app publicly available.</p> <p><strong>SUCCESS WITH DEPLOYMENT AND SERVICE</strong></p> <p>I created a simple <code>hello world</code> type of nodejs app and pushed the image to my docker hub <code>johnlai2004/swarm2</code>. I successfully created a deployment and service with this yaml file:</p> <p><code>nodejs.yaml</code></p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: nodejs-hello labels: app: nodejs-hello spec: replicas: 1 selector: matchLabels: app: nodejs-hello template: metadata: labels: app: nodejs-hello spec: containers: - name: nodejs-hello image: johnlai2004/swarm2 ports: - containerPort: 3000 --- apiVersion: v1 kind: Service metadata: name: nodejs-hello-service spec: selector: app: nodejs-hello type: LoadBalancer ports: - protocol: TCP port: 3000 targetPort: 3000 nodePort: 30000 </code></pre> <p>I uploaded these files to a VPS with a new installation of ubuntu 20.04, minikube, kubectl and docker.</p> <p>I ran the following commands and got the results I wanted:</p> <pre><code>minikube start --driver=docker kubectl apply -f nodejs.yaml minikube service nodejs-hello-service |-----------|----------------------|-------------|---------------------------| | NAMESPACE | NAME | TARGET PORT | URL | |-----------|----------------------|-------------|---------------------------| | default | nodejs-hello-service | 3000 | http://192.168.49.2:30000 | |-----------|----------------------|-------------|---------------------------| </code></pre> <p>When I do a <code>wget http://192.168.49.2:30000</code>, I get an <code>index.html</code> file that says <code>hello from nodejs-hello-556dc868-6lrdz at 12/19/2021, 10:29:56 PM</code>. This is perfect.</p> <p><strong>FAILURE WITH INGRESS</strong></p> <p>Next, I want to use ingress so that I can see the page at <code>http://website.example.com</code> (replace <code>website.example.com</code> with the actual domain that points to my server). I put this file on my server:</p> <p><code>nodejs-ingress.yaml</code></p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: nodejs-ingress namespace: default annotations: kubernetes.io/ingress.class: &quot;nginx&quot; spec: rules: - host: website.example.com http: paths: - path: / pathType: Prefix backend: service: name: nodejs-hello-service port: number: 3000 </code></pre> <p>And I ran the commands</p> <pre><code>minikube addons enable ingress kubectl apply -f nodejs-ingress.yaml kubectl get ingress NAME CLASS HOSTS ADDRESS PORTS AGE nodejs-ingress &lt;none&gt; website.example.com localhost 80 15m </code></pre> <p>But when I visit <code>http://website.example.com</code> with my browser, the browser says it can't connect. Using <code>wget http://website.example.com</code> gave the same connection issue.</p> <p>Can someone point out what I may have done wrong?</p> <hr /> <p><strong>UPDATE</strong></p> <p>I ran these commands because I think it shows I didn't install ingress-controller in the right name space?</p> <pre><code>kubectl get pod -n ingress-nginx NAME READY STATUS RESTARTS AGE ingress-nginx-admission-create--1-tqsrp 0/1 Completed 0 4h25m ingress-nginx-admission-patch--1-sth26 0/1 Completed 0 4h25m ingress-nginx-controller-5f66978484-tmx72 1/1 Running 0 4h25m kubectl get pod -n default NAME READY STATUS RESTARTS AGE nodejs-hello-556dc868-6lrdz 1/1 Running 0 40m </code></pre> <p>So does this mean my nodejs app is in a name space that doesn't have access to the ingress controller?</p> <hr /> <p>UPDATE 2</p> <p>I also tried following <a href="https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/" rel="nofollow noreferrer">this guide</a> step by step. One difference I noticed was when I ran the command <code>kubectl get ingress</code>, <code>ADDRESS</code> says <code>localhost</code>. But in the guide, it says it is supposed to be <code>172.17.0.15</code></p> <p><a href="https://i.stack.imgur.com/IsjYW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IsjYW.png" alt="enter image description here" /></a></p> <p>Does this difference matter? I'm hosting things in a cloud vps called linode.com. Does that change the way I do things?</p>
<p>The behaviour you have is expected. Let me explain why. Going point through point, and at the end I will present my tips.</p> <p>First I think it's worth to present minikube architecture. I'm assuming you have installed minikube using default driver <code>docker</code> as you have address <code>192.168.49.2</code> which is standard for <a href="https://minikube.sigs.k8s.io/docs/drivers/docker/" rel="nofollow noreferrer"><code>docker</code> driver</a>.</p> <p>The layers are:</p> <ul> <li>your VM with Ubuntu 20.04</li> <li>Kubernetes cluster setup by minikube which is docker container with address <code>192.168.49.2</code> on the VM</li> </ul> <p>So... you can not just run <code>curl</code> on the VM using a <code>localhost</code> address to connect to the service. <a href="https://en.wikipedia.org/wiki/Localhost" rel="nofollow noreferrer">The <code>localhost</code> is referring to the device that you are making curl request (so your VM)</a>, not the docker container. That's why you need to use the <code>192.168.49.2</code> address.</p> <p>You can type <code>docker ps -a</code>, and you will see the container which is an actual Kubernetes cluster. You can exec into it using <code>docker exec</code> command and then run <code>curl</code> command with the localhost address:</p> <pre><code>user@example-ubuntu-minikube-template-1:~$ curl -H &quot;Host: hello-world.info&quot; localhost curl: (7) Failed to connect to localhost port 80: Connection refused user@example-ubuntu-minikube-template-1:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1a4ba3895990 gcr.io/k8s-minikube/kicbase:v0.0.28 &quot;/usr/local/bin/entr…&quot; 4 days ago Up 4 days 127.0.0.1:49157-&gt;22/tcp, 127.0.0.1:49156-&gt;2376/tcp, 127.0.0.1:49155-&gt;5000/tcp, 127.0.0.1:49154-&gt;8443/tcp, 127.0.0.1:49153-&gt;32443/tcp minikube user@example-ubuntu-minikube-template-1:~$ docker exec -it 1a sh # curl -H &quot;Host: hello-world.info&quot; localhost Hello, world! Version: 1.0.0 Hostname: web-79d88c97d6-nl4c7 </code></pre> <p>Keep in mind that you can access this container only from the VM that is hosting this container. Without any further configuration it's you can't just access it from the other VMs. It is possible, but not recommended.</p> <p>Good explanation in the <a href="https://minikube.sigs.k8s.io/docs/faq/" rel="nofollow noreferrer">minikube FAQ</a>:</p> <blockquote> <p>How can I access a minikube cluster from a remote network?<a href="https://minikube.sigs.k8s.io/docs/faq/#how-can-i-access-a-minikube-cluster-from-a-remote-network" rel="nofollow noreferrer"></a></p> </blockquote> <blockquote> <p>minikube’s primary goal is to quickly set up local Kubernetes clusters, and therefore we strongly discourage using minikube in production or for listening to remote traffic. By design, minikube is meant to only listen on the local network.</p> </blockquote> <blockquote> <p>However, it is possible to configure minikube to listen on a remote network. This will open your network to the outside world and is not recommended. If you are not fully aware of the security implications, please avoid using this.</p> </blockquote> <blockquote> <p>For the docker and podman driver, use <code>--listen-address</code> flag:</p> <pre><code>minikube start --listen-address=0.0.0.0 </code></pre> </blockquote> <p>So I'd avoid it. I will present a better possible solution at the end of the answer.</p> <p>You asked:</p> <blockquote> <p>But when I visit <code>http://website.example.com</code> with my browser, the browser says it can't connect. Using <code>wget http://website.example.com</code> gave the same connection issue.</p> </blockquote> <blockquote> <p>Can someone point out what I may have done wrong?</p> </blockquote> <p>Your computer does not know what it is <code>website.example.com</code>. It's not aware that this name is used by your Ingress. If your computer does not find this name in <a href="https://en.wikipedia.org/wiki/Hosts_(file)" rel="nofollow noreferrer">hosts file</a> it will start looking for this over the Internet.</p> <p>So you have some possible solutions:</p> <ul> <li>use <code>curl -H 'HOST: website.example.com' http://192.168.49.2:80</code> - it will work only on the VM where is minikube</li> <li><a href="https://linuxize.com/post/how-to-edit-your-hosts-file/" rel="nofollow noreferrer">add host to the hosts file</a> - something like <code>192.168.49.2 website.example.com</code> - it will work only on the VM where is minikube</li> <li>Setup a bare-metal cluster (more details in the sum up section) and point the domain address to the VM address. In GCP and AWS you can do it using <a href="https://cloud.google.com/dns" rel="nofollow noreferrer">Google Cloud DNS</a> or <a href="https://aws.amazon.com/route53/" rel="nofollow noreferrer">Amazon Route 53</a>. On linode cloud maybe <a href="https://www.linode.com/docs/guides/dns-manager/" rel="nofollow noreferrer">this one - DNS Manager</a> ?</li> </ul> <p><strong>EDIT:</strong> You wrote that you have a domain pointed to the server, so please just check the sum up section of my answer.</p> <p>Also you asked:</p> <blockquote> <p>I ran these commands because I think it shows I didn't install ingress-controller in the right name space?</p> </blockquote> <blockquote> <p>So does this mean my nodejs app is in a name space that doesn't have access to the ingress controller?</p> </blockquote> <p><a href="https://kubernetes.github.io/ingress-nginx/deploy/#quick-start" rel="nofollow noreferrer">It's absolutely normal</a>:</p> <blockquote> <p>It will install the controller in the <code>ingress-nginx</code> namespace, creating that namespace if it doesn't already exist.</p> </blockquote> <p>Also:</p> <blockquote> <p>I also tried following this guide step by step: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/</a></p> </blockquote> <blockquote> <p>One difference I noticed was when I ran the command <code>kubectl get ingress</code>, <code>ADDRESS</code> says <code>localhost</code>. But in the guide, it says it is supposed to be <code>172.17.0.15</code></p> </blockquote> <blockquote> <p>Does this difference matter? I'm hosting things in a cloud vps called linode.com. Does that change the way I do things?</p> </blockquote> <p>It's also normal and expected when using minikube with a docker driver.</p> <p>To sum up / other tips:</p> <ul> <li>Minkube is fine for local testing; you can easily access apps and services using from the host - check <a href="https://minikube.sigs.k8s.io/docs/handbook/accessing/" rel="nofollow noreferrer">Accessing apps</a>.</li> <li>However, for exposing it outside the network you should consider using solutions like <a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/" rel="nofollow noreferrer">kubeadm</a> or <a href="https://github.com/kubernetes-sigs/kubespray" rel="nofollow noreferrer">kubespray</a> for cluster setup + <a href="https://metallb.universe.tf/" rel="nofollow noreferrer">MetalLB</a> for LoadBalancer solution. Check &quot;<a href="https://kubernetes.github.io/ingress-nginx/deploy/baremetal/" rel="nofollow noreferrer">Bare-metal considerations</a>&quot; and <a href="https://stackoverflow.com/questions/61583350/exposing-a-kubernetes-service-on-a-bare-metal-cluster-over-the-external-network">Exposing a Kubernetes service on a bare-metal cluster over the external network architecture</a></li> <li>If you are planning to use your service with ingress, don't use LoadBalancer type. It's ok to use ClusterIP.</li> </ul>
<p>I set up K3s on a server with:</p> <pre><code>curl -sfL https://get.k3s.io | K3S_TOKEN={token} INSTALL_K3S_EXEC=&quot;server --cluster-init --disable=traefik --write-kubeconfig-mode 644&quot; sh -s - </code></pre> <p>Then I grabbed the kube config from <code>/etc/rancher/k3s/k3s.yaml</code> and copy it to my local machine so I can interact with the cluster from my machine rather than the server node I installed K3s on. I had to swap out references to 127.0.0.1 and change it to the actual hostname of the server I installed K3s on as well but other than that it worked.</p> <p>I then hooked up 2 more server nodes to the cluster for a High Availability setup using:</p> <pre><code>curl -sfL https://get.k3s.io | K3S_TOKEN={token} INSTALL_K3S_EXEC=&quot;server --server {https://{hostname or IP of server 1}:6443 --disable=traefik --write-kubeconfig-mode 644&quot; sh -s - </code></pre> <p>Now on my local machine again I run <code>kubectl get pods</code> (for example) and that works but I want a highly available setup so I placed a TCP Load Balancer (NGINX actually) in front of my cluster. Now I am trying to connect to the Kubernetes API through that proxy / load balancer and unfortunately, since my <code>~/.kube/config</code> has a client certificate for authentication, this no longer works because my load balancer / proxy that lives in front of that server cannot pass my client cert on to the K3s server.</p> <p>My <code>~/.kube/config</code>:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 clusters: - cluster: certificate-authority-data: {omitted} server: https://my-cluster-hostname:6443 name: default contexts: - context: cluster: default user: default name: default current-context: default kind: Config preferences: {} users: - name: default user: client-certificate-data: {omitted} client-key-data: {omitted} </code></pre> <p>I also grabbed that client cert and key in my kube config, exported it to a file, and hit the API server with curl and it works when I directly hit the server nodes but NOT when I go through my proxy / load balancer.</p> <p>What I would like to do instead of using the client certificate approach is use <code>token</code> authentication as my proxy would not interfere with that. However, I am not sure how to get such a token. I read the <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/" rel="nofollow noreferrer">Kubernetes Authenticating guide</a> and specifically I tried creating a new service account and getting the token associated with it as described in the <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/#service-account-tokens" rel="nofollow noreferrer">Service Account Tokens</a> section but that also did not work. I also dug through <a href="https://rancher.com/docs/k3s/latest/en/installation/install-options/server-config/" rel="nofollow noreferrer">K3s server config options</a> to see if there was any mention of static token file, etc. but didn't find anything that seemed likely.</p> <p>Is this some limitation of K3s or am I just doing something wrong (likely)?</p> <p>My <code>kubectl version</code> output:</p> <pre><code>Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;20&quot;, GitVersion:&quot;v1.20.7&quot;, GitCommit:&quot;132a687512d7fb058d0f5890f07d4121b3f0a2e2&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-05-12T12:40:09Z&quot;, GoVersion:&quot;go1.15.12&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;} Server Version: version.Info{Major:&quot;1&quot;, Minor:&quot;21&quot;, GitVersion:&quot;v1.21.7+k3s1&quot;, GitCommit:&quot;ac70570999c566ac3507d2cc17369bb0629c1cc0&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-11-29T16:40:13Z&quot;, GoVersion:&quot;go1.16.10&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;} </code></pre>
<p>I figured out an approach that works for me by reading through the <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/" rel="nofollow noreferrer">Kubernetes Authenticating Guide</a> in more detail. I settled on the <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/#service-account-tokens" rel="nofollow noreferrer">Service Account Tokens</a> approach as it says:</p> <blockquote> <p>Normally these secrets are mounted into pods for in-cluster access to the API server, but can be used from outside the cluster as well.</p> </blockquote> <p>My use is for outside the cluster.</p> <p>First, I created a new <code>ServiceAccount</code> called <code>cluster-admin</code>:</p> <pre><code>kubectl create serviceaccount cluster-admin </code></pre> <p>I then created a <code>ClusterRoleBinding</code> to assign cluster-wide permissions to my ServiceAccount (I named this <code>cluster-admin-manual</code> because K3s already had created one called <code>cluster-admin</code> that I didn't want to mess with):</p> <pre><code>kubectl create clusterrolebinding cluster-admin-manual --clusterrole=cluster-admin --serviceaccount=default:cluster-admin </code></pre> <p>Now you have to get the <code>Secret</code> that is created for you when you created your <code>ServiceAccount</code>:</p> <pre><code>kubectl get serviceaccount cluster-admin -o yaml </code></pre> <p>You'll see something like this returned:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: ServiceAccount metadata: creationTimestamp: &quot;2021-12-20T15:55:55Z&quot; name: cluster-admin namespace: default resourceVersion: &quot;3973955&quot; uid: 66bab124-8d71-4e5f-9886-0bad0ebd30b2 secrets: - name: cluster-admin-token-67jtw </code></pre> <p>Get the Secret content with:</p> <pre><code>kubectl get secret cluster-admin-token-67jtw -o yaml </code></pre> <p>In that output you will see the <code>data/token</code> property. This is a base64 encoded JWT bearer token. Decode it with:</p> <pre><code>echo {base64-encoded-token} | base64 --decode </code></pre> <p>Now you have your bearer token and you can add a user to your <code>~/.kube/config</code> with the following command. You can also paste that JWT into <a href="https://jwt.io/" rel="nofollow noreferrer">jwt.io</a> to take a look at the properties and make sure you base64 decoded it properly.</p> <pre><code>kubectl config set-credentials my-cluster-admin --token={token} </code></pre> <p>Then make sure your existing <code>context</code> in your <code>~/.kube/config</code> has the user set appropriately (I did this manually by editing my kube config file but there's probably a <code>kubectl config</code> command for it). For example:</p> <pre class="lang-yaml prettyprint-override"><code>- context: cluster: my-cluster user: my-cluster-admin name: my-cluster </code></pre> <p>My user in the kube config looks like this:</p> <pre class="lang-yaml prettyprint-override"><code>- name: my-cluster-admin user: token: {token} </code></pre> <p>Now I can authenticate to the cluster using the token instead of relying on a transport layer specific mechanism (TLS with Mutual Auth) that my proxy / load-balancer does not interfere with.</p> <p>Other resources I found helpful:</p> <ul> <li><a href="https://medium.com/devops-mojo/kubernetes-role-based-access-control-rbac-overview-introduction-rbac-with-kubernetes-what-is-2004d13195df" rel="nofollow noreferrer">Kubernetes — Role-Based Access Control (RBAC) Overview by Anish Patel</a></li> </ul>
<p>For example, a defer function is implemented within a webhook's logic (the webhook is written in Golang). The webhook times out after taking too long to complete. In this case, will the defer function still get executed?</p> <p>The request timeout is set via <a href="https://pkg.go.dev/context#WithTimeout" rel="nofollow noreferrer">context.WithTimeout</a> for the webhook.</p>
<p>It's usually a good idea to clearly mention what programming language you're talking about, although I can figure it out.</p> <p>In Go, the defer functor (whatever you want to call it) will be executed when the method returns, no matter how it completes, unless you manage to kill the executing process in a drastic manner, and perhaps even then.</p>
<p>I hope it's ok to ask for your advice.</p> <p>The problem in a nutshell: my pipeline cannot pull private images from GHCR.IO into Okteto Kubernetes, but public images from the same private repo work.</p> <p>I'm on Windows 10 and use WSL2-Ubuntu 20.04 LTS with kinD for development and tried minikube too.</p> <p>I get an error in Okteto which says that the image pull is “unauthorized” -&gt; “imagePullBackOff”.</p> <p>Things I did:browsed Stack Overflow, RTFM, Okteto FAQ, download the Okteto kubeconfig, pulled my hair out and spent more hours than I would like to admit – still no success yet.</p> <p>For whatever reason I cannot create a “kubectl secret” that works. When logged-in to ghcr.io via “docker login --username” I can pull private images locally.</p> <p>No matter what I’ve tried I still get the error “unauthorized” when trying to pull a private image in Okteto.</p> <p>My Setup with latest updates:</p> <ul> <li>Windows 10 Pro</li> <li>JetBrains Rider IDE</li> <li>WSL2-Ubuntu 20.04 LTS</li> <li>ASP.NET Core MVC app</li> <li>.NET 6 SDK</li> <li>Docker</li> <li>kinD</li> <li>minikube</li> <li>Chocolatey</li> <li>Homebrew</li> </ul> <p>Setup kinD</p> <pre><code>kind create cluster --name my-name kubectl create my-namespace // create a secret to pull images from ghcr.io kubectl create secret docker-registry my-secret -n my-namespace --docker-username=&quot;my-username&quot; --docker-password=&quot;my-password&quot; --docker-email=&quot;my-email&quot; --docker-server=&quot;https://ghcr.io&quot; // patch local service account kubectl patch serviceaccount default -p '{&quot;imagePullSecrets&quot;: [{&quot;name&quot;: &quot;my-secret&quot;}]}' </code></pre> <p>kubernetes.yaml</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: okteto-repo namespace: my-namespace spec: replicas: 1 selector: matchLabels: app: okteto-repo template: metadata: labels: app: okteto-repo spec: containers: - name: okteto-repo image: ghcr.io/user/okteto-repo:latest ports: - containerPort: 80 imagePullSecrets: - name: my-secret --- apiVersion: v1 kind: Service metadata: name: okteto-repo annotations: dev.okteto.com/auto-ingress: &quot;true&quot; spec: type: ClusterIP selector: app: okteto-repo ports: - protocol: TCP port: 8080 targetPort: 80 </code></pre> <p>Do you have an idea why it doesn't work and what I could do?</p> <p>Thanks a lot my dear friends, every input is highly appreciated!</p> <p>Hope you guys have great holidays.</p> <p>Cheers, Michael</p>
<p>I was able to pull a private image by doing the following:</p> <ol> <li>Create a personal token in GitHub with <code>repo</code> access.</li> <li>Build and push the image to GitHub's Container registry (I used <code>okteto build -t ghcr.io/rberrelleza/go-getting-started:0.0.1</code>)</li> <li>Download my <a href="https://okteto.com/docs/reference/cli/#update-kubeconfig" rel="noreferrer">kubeconfig credentials</a> from Okteto Cloud by running <code>okteto context update-kubeconfig</code>.</li> <li>Create a secret with my credentials: <code>kubectl create secret docker-registry gh-regcred --docker-server=ghcr.io --docker-username=rberrelleza --docker-password=ghp_XXXXXX</code></li> <li>Patched the default account to include the secret as an image pull secret: <code>kubectl patch serviceaccount default -p '{&quot;imagePullSecrets&quot;: [{&quot;name&quot;: &quot;gh-regcred&quot;}]}'</code></li> <li>Updated the image name in the kubernetes manifest</li> <li>Created the deployment (<code>kubectl apply -f k8s.yaml</code>)</li> </ol> <p>These is what my kubernetes resources looks like, in case it helps:</p> <pre><code># k8s.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-world spec: replicas: 1 selector: matchLabels: app: hello-world template: metadata: labels: app: hello-world spec: containers: - image: ghcr.io/rberrelleza/go-getting-started:0.0.1 name: hello-world --- apiVersion: v1 kind: Service metadata: name: hello-world annotations: dev.okteto.com/auto-ingress: &quot;true&quot; spec: type: ClusterIP ports: - name: &quot;hello-world&quot; port: 8080 selector: app: hello-world </code></pre> <pre><code># default SA apiVersion: v1 imagePullSecrets: - name: gh-regcred - name: okteto-regcred kind: ServiceAccount metadata: creationTimestamp: &quot;2021-05-21T22:26:38Z&quot; name: default namespace: rberrelleza resourceVersion: &quot;405042662&quot; uid: 2b6a6eef-2ce7-40d3-841a-c0a5497279f7 secrets: - name: default-token-7tm42 </code></pre>
<p>can someone help? I am trying to inject a helm value on a config map, but it breaks the format. If I use the value directly instead of .Values, it works fine.</p> <p>What I have:</p> <pre><code>data: application.instanceLabelKey: argocd.argoproj.io/instance oidc.config: | name: Okta issuer: https://mycompany.okta.com clientID: {{ .Values.okta.clientID }} clientSecret: {{ .Values.okta.clientSecret }} requestedScopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;, &quot;groups&quot;] requestedIDTokenClaims: {&quot;groups&quot;: {&quot;essential&quot;: true}} </code></pre> <p>The result</p> <pre><code>data: application.instanceLabelKey: argocd.argoproj.io/instance oidc.config: &quot;name: Okta\nissuer: https://mycompany.okta.com\nclientID: myClientId \nclientSecret: mySecret\nrequestedScopes: [\&quot;openid\&quot;, \&quot;profile\&quot;, \&quot;email\&quot;, \&quot;groups\&quot;]\nrequestedIDTokenClaims: {\&quot;groups\&quot;: {\&quot;essential\&quot;: true}}\n&quot; </code></pre>
<p>it should be with the values.yaml . it worked for me in both ways :</p> <ol> <li>using the values in values.yaml</li> </ol> <hr /> <p>Values.yaml:</p> <pre><code>okta: clientSecret: test1233 clientID: testnew </code></pre> <p>configmap</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: test-config namespace: default labels: app: test data: application.instanceLabelKey: argocd.argoproj.io/instance oidc.config: | name: Okta issuer: https://mycompany.okta.com clientID: {{ .Values.okta.clientID }} clientSecret: {{ .Values.okta.clientSecret }} requestedScopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;, &quot;groups&quot;] requestedIDTokenClaims: {&quot;groups&quot;: {&quot;essential&quot;: true}} </code></pre> <hr /> <p>command used :</p> <pre><code> helm install testchart .\mycharttest --dry-run </code></pre> <p>-----Output-------------------</p> <pre><code># Source: mycharttest/templates/configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: test-config namespace: default labels: app: test product: test db: test data: application.instanceLabelKey: argocd.argoproj.io/instance oidc.config: | name: Okta issuer: https://mycompany.okta.com clientID: testnew clientSecret: test1233 requestedScopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;, &quot;groups&quot;] requestedIDTokenClaims: {&quot;groups&quot;: {&quot;essential&quot;: true}} </code></pre> <ol start="2"> <li>using the values in runtime</li> </ol> <hr /> <p>---Command --</p> <pre><code> helm install test .\mycharttest --dry-run --set okta.clientID=newclientid --set okta.clientSecret=newsecret </code></pre> <p>----Output ---</p> <pre><code># Source: mycharttest/templates/configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: test-config namespace: default labels: app: test product: test db: test data: application.instanceLabelKey: argocd.argoproj.io/instance oidc.config: | name: Okta issuer: https://mycompany.okta.com clientID: newclientid clientSecret: newsecret requestedScopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;, &quot;groups&quot;] requestedIDTokenClaims: {&quot;groups&quot;: {&quot;essential&quot;: true} </code></pre> <p>kubernetes version : 1.22 Helm version : version.BuildInfo{Version:&quot;v3.7.1&quot;, GitCommit:&quot;1d11fcb5d3f3bf00dbe6fe31b8412839a96b3dc4&quot;, GitTreeState:&quot;clean&quot;, GoVersion:&quot;go1.16.9&quot;}</p>
<p>I have created a kubernetes cluster using Vagrant. I created a Nginx pod and a Cluster IP service for it. I can curl both the pod and the service getting a successful result. I have now installed an Nginx Ingress Controller from: <a href="https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal-clusters" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal-clusters</a> and ran the following command: <code>kubectl create ingress nginxingress --rule=&quot;/nginx=nginx-service:80&quot; --annotation nginx.ingress.kubernetes.io/rewrite-target=/ --default-backend=nginx-service:80</code> and they both have been setup correctly as far as I see as there are no errors. But whenever I try to curl the path then it fails, the controller keeps throwing a 404 Not found. Some more information that might help:<br /> <strong>services</strong>:<br /> <a href="https://i.stack.imgur.com/B31wM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B31wM.png" alt="enter image description here" /></a> <strong>ingresses</strong>:<br /> <a href="https://i.stack.imgur.com/wsy8x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wsy8x.png" alt="enter image description here" /></a><br /> any help will be greatly appreciated</p>
<p>Try adding the ingress class annotation to the ingress configuration. <code>kubernetes.io/ingress.class: &quot;nginx&quot;</code></p> <p>use below YAML as reference and try to update the configuration.</p> <pre><code>apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-myserviceb annotations: kubernetes.io/ingress.class: &quot;nginx&quot; spec: rules: - host: myserviceb.foo.org http: paths: - path: /nginx pathType: Prefix backend: service: name: nginx-service port: number: 80 </code></pre>
<p>I can create a PostgresSQL deployment in Kubernetes with volumes with no problems. The question I have is how to create the database tables.</p> <p>I can easily exec in the pod and create the tables but I want it to be automatically createded.</p> <p>I don't want to build in into the docker image as a want a generic image.</p> <p>I have thought about a few options such as Kubernetes Batch Job only running once but not sure what the best approach is ?</p> <p>Thanks.</p>
<p>this may help (here I have added configmap, persistent volume, persistent volume-claim, and Postgres deployment yaml. This yaml will automatically create a table named <code>users</code> in the Postgres database inside the Postgres-container. Thanks</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: name: postgres-config labels: app: postgres data: Postgres_DB: postgresdb --- apiVersion: v1 kind: Secret metadata: name: postgres-secret data: Postgres_User: postgresadmin Postgres_Password: admin123 --- kind: PersistentVolume apiVersion: v1 metadata: name: postgres-pv-volume labels: type: local app: postgres spec: storageClassName: manual capacity: storage: 5Gi accessModes: - ReadWriteMany hostPath: path: &quot;/mnt/data&quot; --- kind: PersistentVolumeClaim apiVersion: v1 metadata: name: postgres-pv-claim labels: app: postgres spec: storageClassName: manual accessModes: - ReadWriteMany resources: requests: storage: 5Gi --- apiVersion: apps/v1 kind: Deployment metadata: name: postgres spec: replicas: 1 selector: matchLabels: app: postgres template: metadata: labels: app: postgres spec: containers: - name: postgres-container image: postgres:latest imagePullPolicy: &quot;IfNotPresent&quot; lifecycle: postStart: exec: command: [&quot;/bin/sh&quot;,&quot;-c&quot;,&quot;sleep 20 &amp;&amp; PGPASSWORD=$POSTGRES_PASSWORD psql -w -d $POSTGRES_DB -U $POSTGRES_USER -c 'CREATE TABLE IF NOT EXISTS users (userid SERIAL PRIMARY KEY,username TEXT,password TEXT,token TEXT,type TEXT);'&quot;] ports: - containerPort: 5432 env: - name: POSTGRES_DB valueFrom: configMapKeyRef: name: postgres-config key: Postgres_DB - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-secret key: Postgres_User - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: Postgres_Password volumeMounts: - mountPath: /var/lib/postgresql/data name: postgredb volumes: - name: postgredb persistentVolumeClaim: claimName: postgres-pv-claim </code></pre> <p>If you find this helpful, please mark it as answer.</p>
<p>I am running Node JS with Express JS in Kubernetes cluster as service using Deployment YML file with 2 replicas. I am using HELM for deployment.</p> <p>Now I am having the requirement to execute the scheduler to run a particular task at a given interval.</p> <p>If I am running it as single instance, I can implement within the same service, but since I am using replicas, the scheduler will be run in two different pods at same time.</p> <p>Is there a way to configure such that I can run the scheduler in a single pod and disable it in another pod of the same Node JS service?</p> <p>Or do I want to move as a separate Node JS service and maintain it?</p> <p>Can you please provide your suggestion?</p>
<p>In Kubernetes, you can find an Object named <a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/" rel="nofollow noreferrer">CronJob</a>.</p> <p>This will achieve a scheduler role, as a Linux cron would.</p> <p>You can use the same image as your express JS app, but start a different script that will exit with a code at the end.</p> <p>Example:</p> <p><code>node app.js</code> starts your express server</p> <p><code>node schedule.js</code> starts your cron task</p> <p>Best,</p>
<p>I'm trying to share a cephfs volumes between namespaces within k8s cluster. I'm using ceph-csi with cephfs.</p> <p>Followed <a href="https://github.com/ceph/ceph-csi/blob/devel/docs/static-pvc.md#cephfs-static-pvc" rel="nofollow noreferrer">https://github.com/ceph/ceph-csi/blob/devel/docs/static-pvc.md#cephfs-static-pvc</a> to create static pv+pvc in both namespaces. Works if I don't launch both pods on same node.</p> <p>If both pods on same node, Second pod get stuck with error:</p> <pre><code>MountVolume.SetUp failed for volume &quot;team-test-vol-pv&quot; : rpc error: code = Internal desc = failed to bind-mount /var/lib/kubelet/plugins/k ubernetes.io/csi/pv/team-test-vol-pv/globalmount to /var/lib/kubelet/pods/007fc605-7fa4-4dc6-890f-fc0dabe5740b/volumes/kubernetes.io~csi/team-test-vol-pv/mount: an error (exit status 32) occurred while running mount arg s: [-o bind,_netdev /var/lib/kubelet/plugins/kubernetes.io/csi/pv/team-test-vol-pv/globalmount /var/lib/kubelet/pods/007fc605-7fa4-4dc6-890f-fc0dabe5740b/volumes/kubernetes.io~csi/team-test-vol-pv/moun </code></pre> <p>Any ideas how to resolve this or how to use a single RWX volume in different NS?</p> <p>PV+PVC for team-x:</p> <pre><code>--- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: test-vol namespace: team-x spec: storageClassName: &quot;&quot; accessModes: - ReadWriteMany resources: requests: storage: 1Gi volumeMode: Filesystem # volumeName should be same as PV name volumeName: team-x-test-vol-pv --- apiVersion: v1 kind: PersistentVolume metadata: name: team-x-test-vol-pv spec: claimRef: namespace: team-x name: test-vol storageClassName: &quot;&quot; accessModes: - ReadWriteMany capacity: storage: 1Gi csi: driver: cephfs.csi.ceph.com nodeStageSecretRef: name: csi-cephfs-secret-hd namespace: ceph-csi volumeAttributes: &quot;clusterID&quot;: &quot;cd79ae11-1804-4c06-a97e-aeeb961b84b0&quot; &quot;fsName&quot;: &quot;cephfs&quot; &quot;staticVolume&quot;: &quot;true&quot; &quot;rootPath&quot;: /volumes/team/share/8b73d3bb-282e-4c32-b13a-97459419bd5b # volumeHandle can be anything, need not to be same # as PV name or volume name. keeping same for brevity volumeHandle: team-share persistentVolumeReclaimPolicy: Retain volumeMode: Filesystem </code></pre> <p>PV+PVC for team-y</p> <pre><code>--- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: test-vol namespace: team-y spec: storageClassName: &quot;&quot; accessModes: - ReadWriteMany resources: requests: storage: 1Gi volumeMode: Filesystem # volumeName should be same as PV name volumeName: team-y-test-vol-pv --- apiVersion: v1 kind: PersistentVolume metadata: name: team-y-test-vol-pv spec: claimRef: namespace: team-y name: test-vol storageClassName: &quot;&quot; accessModes: - ReadWriteMany capacity: storage: 1Gi csi: driver: cephfs.csi.ceph.com nodeStageSecretRef: name: csi-cephfs-secret-hd namespace: ceph-csi volumeAttributes: &quot;clusterID&quot;: &quot;cd79ae11-1804-4c06-a97e-aeeb961b84b0&quot; &quot;fsName&quot;: &quot;cephfs&quot; &quot;staticVolume&quot;: &quot;true&quot; &quot;rootPath&quot;: /volumes/team-y/share/8b73d3bb-282e-4c32-b13a-97459419bd5b # volumeHandle can be anything, need not to be same # as PV name or volume name. keeping same for brevity volumeHandle: team-share persistentVolumeReclaimPolicy: Retain volumeMode: Filesystem </code></pre>
<p>Having <code>volumeHandle: xyz</code> unique for each pv done the trick. Tested deploying 3xdaemonsets in 3 different namespaces.</p>
<p>Kubernetes (v1.10.8) installed on my cloud by kismatic (v1.12.0). How I can update kubernetes to the latest version with <code>kubeadm</code>?</p>
<p>With such version difference - we currently have <a href="https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.23.md#v1231" rel="nofollow noreferrer">v1.23</a> (<a href="https://kubernetes.io/releases/" rel="nofollow noreferrer">see official supported releases</a>) - I would consider creating the cluster from the beginning.</p> <p>If this is not possible, you should upgrade them step by step (from version to version). <a href="https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-upgrade/" rel="nofollow noreferrer">Here</a> you can find guide that will help to upgrade kubeadm clusters. A link to older versions you can find <a href="https://v1-19.docs.kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-upgrade/" rel="nofollow noreferrer">here</a>, but</p> <blockquote> <p><em><strong>NOTE</strong></em>: Kubernetes v1.19 documentation is no longer actively maintained. The version you are currently viewing is a static snapshot.</p> </blockquote> <p>However, you have to have in mind that upgrading through so many versions can cause other issues, so I recommend using the first option.</p>
<p>In <strong>kubernetes</strong>, if a pod go down for some reason, the admission controller will restart it.</p> <p>We call this mecanism self healing.</p> <p>I have never worked with <strong>docker-compose</strong>, but I wonder : is it the same ?</p>
<p>When deployed with <code>docker-compose</code> or now <code>docker compose</code> (with a space) you are deploying to a single node. You can define the service to automatically restart with a <a href="https://docs.docker.com/compose/compose-file/compose-file-v3/#restart_policy" rel="nofollow noreferrer">restart policy</a> that handles a crashing application. However, there are a few scenarios where externalities like the network or volumes are not in a good state which I've seen cause the definition to be considered invalid by docker at which point it stops attempting to restart the service.</p> <p>There's also Swarm Mode which is an orchestrator like Kubernetes, it can use the <code>docker-compose.yml</code> to define the target state, and it will continue to restart services to recover from an outage, and migrate them to another node when a node in the cluster goes down.</p>
<p>I am new to movetokube tool. I am struggling to understand how the move2kube collect command works. The <a href="https://move2kube.konveyor.io/" rel="nofollow noreferrer">web site</a> doesn't have any documentation on this command which is very surprising. I want to get all the applications installed in the Cloud Foundary cluster and I hope move2kube does this through move2kube collect command (or not?). I am not sure sure whether I have to execute the move2kube command on the Cloud Foundary cluster or K8 cluster. Please help!</p> <p>I am executing the following move2kube command on a CF cluster</p> <blockquote> <p>move2kube collect</p> </blockquote> <p>I see the following error</p> <pre><code>INFO[0000] Begin collection INFO[0000] [*collector.ClusterCollector] Begin collection WARN[0001] Error while fetching storage classes using command [/usr/local/bin/kubectl get sc -o yaml] ERRO[0001] API request for server-group list failed WARN[0001] Failed to retrieve preferred group information from cluster WARN[0001] Failed to collect using the API. Error: &quot;Get \&quot;https://cluster02.someserver.com:8443/api?timeout=32s\&quot;: failed to refresh token: oauth2: cannot fetch token: 401 \nResponse: {\&quot;error\&quot;:\&quot;unauthorized\&quot;,\&quot;error_description\&quot;:\&quot;Bad credentials\&quot;}&quot; . Falling back to using the CLI. ERRO[0001] Error while running kubectl api-resources: exit status 1 WARN[0001] Failed to collect using the CLI. Error: &quot;exit status 1&quot; WARN[0001] [*collector.ClusterCollector] failed. Error: &quot;exit status 1&quot; INFO[0001] [*collector.ImagesCollector] Begin collection INFO[0001] [*collector.ImagesCollector] Done INFO[0001] [*collector.CFContainerTypesCollector] Begin collection WARN[0002] Error while getting buildpacks : exit status 1 WARN[0002] Unable to collect buildpacks from cf instance : exit status 1 ERRO[0002] exit status 1 WARN[0002] Unable to find used buildpacks : exit status 1 INFO[0004] [*collector.CFContainerTypesCollector] Done INFO[0004] [*collector.CfAppsCollector] Begin collection ERRO[0004] exit status 1 WARN[0004] [*collector.CfAppsCollector] failed. Error: &quot;exit status 1&quot; INFO[0004] Collection done INFO[0004] Collect Output in [/home/mytest/move2kube/samples/m2k_collect]. Copy this directory into the source directory to be used for planning. </code></pre>
<p>From <a href="https://github.com/konveyor/move2kube/blob/main/USAGE.md#usage" rel="nofollow noreferrer">the move2kube GitHub page</a>:</p> <blockquote> <p><strong>Usage</strong></p> <p><strong>One step Simple approach</strong></p> <p><code>move2kube transform -s src</code></p> <p><strong>Two step involved approach</strong></p> <ol> <li><em>Plan</em> : Place source code in a directory say <code>src</code> and generate a plan. For example, you can use the <code>samples</code> directory. <code>move2kube plan -s src</code></li> <li><em>Transform</em> : In the same directory, invoke the below command. <code>move2kube transform</code></li> </ol> <p>Note: If information about any runtime instance say cloud foundry or kubernetes cluster needs to be collected use <code>move2kube collect</code>. You can place the collected data in the <code>src</code> directory used in the plan.</p> </blockquote> <p>And from <a href="https://ashokponkumar.medium.com/introducing-konveyor-move2kube-f3b28e78cd22" rel="nofollow noreferrer">the article <strong>Introducing Konveyor Move2Kube</strong> on Medium</a>:</p> <blockquote> <p><strong>Move2Kube Usage</strong></p> <p>Move2Kube takes as input the source artifacts and outputs the target deployment artifacts.</p> <p>Move2Kube accomplishes the above activities using a 3 step approach of</p> <ol> <li><em>Collect</em> : If runtime inspection is required, <code>move2kube collect</code> will analyse your runtime environment such as cloud foundry or kubernetes, extract the required metadata and output them as yaml files in <code>m2k_collect</code> folder.</li> </ol> <p>...</p> </blockquote>
<p>How does one go about setting resource limits in EMR on EKS? My driver pod is failing to launch because it is requesting more CPU than it is allowed. This doesn't make sense to me. I am running the getting started code from the docs below.</p> <p>I have added <code>--conf spark.driver.limit.cores=2</code> in order to try and make the limit higher than what is listed in the error message below. I got this idea from here <a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html#spark-properties" rel="nofollow noreferrer">https://spark.apache.org/docs/latest/running-on-kubernetes.html#spark-properties</a></p> <p>This cluster does have istio running in it. I am not sure if that would cause issues.</p> <p>Here is the code I am running to trigger the job</p> <pre><code>aws emr-containers start-job-run \ --virtual-cluster-id blahblah \ --name pi-4 \ --execution-role-arn arn:aws:iam::0000000000:role/blahblah_emr_eks_executor_role \ --release-label emr-6.4.0-latest \ --job-driver '{ &quot;sparkSubmitJobDriver&quot;: { &quot;entryPoint&quot;: &quot;s3://us-east-1.elasticmapreduce/emr-containers/samples/wordcount/scripts/wordcount.py&quot;, &quot;entryPointArguments&quot;: [&quot;s3://blahblah/wordcount_output&quot;], &quot;sparkSubmitParameters&quot;: &quot;--conf spark.executor.instances=2 --conf spark.executor.memory=2G --conf spark.executor.cores=2 --conf spark.driver.cores=1 --conf spark.driver.limit.cores=2&quot; } }' </code></pre> <p>This causes the <code>job-runner</code> container to fail with the following:</p> <hr /> <p>State: Terminated Reason: Error Message: Exception in thread &quot;main&quot; io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: POST at: <a href="https://kubernetes.default.svc/api/v1/namespaces/spark/pods" rel="nofollow noreferrer">https://kubernetes.default.svc/api/v1/namespaces/spark/pods</a>. Message: Pod &quot;spark-00000002vepbpmi2hkv-driver&quot; is invalid: spec.containers[2].resources.requests: Invalid value: &quot;1&quot;: must be less than or equal to cpu limit. Received status: Status(apiVersion=v1, code=422, details=StatusDetails(causes=[StatusCause(field=spec.containers[2].resources.requests, message=Invalid value: &quot;1&quot;: must be less than or equal to cpu limit, reason=FieldValueInvalid, additionalProperties={})], group=null, kind=Pod, name=spark-00000002vepbpmi2hkv-driver, retryAfterSeconds=null, uid=null, additionalProperties={}), kind=Status, message=Pod &quot;spark-00000002vepbpmi2hkv-driver&quot; is invalid: spec.containers[2].resources.requests: Invalid value: &quot;1&quot;: must be less than or equal to cpu limit, metadata=ListMeta(_continue=null, remainingItemCount=null, resourceVersion=null, selfLink=null, additionalProperties={}), reason=Invalid, status=Failure, additionalProperties={}). at io.fabric8.kubernetes.client.dsl.base.OperationSupport.requestFailure(OperationSupport.java:589)</p> <hr /> <p>Any ideas on how to proceed?</p>
<p>I was able to figure it out.</p> <pre><code>aws emr-containers start-job-run \ --virtual-cluster-id=blahblah \ --name=pi-4 \ --execution-role-arn=arn:aws:iam::blahblahaccount:role/balblah_role_name \ --release-label=emr-6.4.0-latest \ --job-driver='{ &quot;sparkSubmitJobDriver&quot;: { &quot;entryPoint&quot;: &quot;local:///usr/lib/spark/examples/src/main/python/pi.py&quot;, &quot;sparkSubmitParameters&quot;: &quot;--conf spark.executor.instances=1 --conf spark.executor.memory=2G --conf spark.executor.request.cores=1 --conf spark.kubernetes.executor.limit.cores=2 --conf spark.driver.request.cores=1 --conf spark.kubernetes.driver.limit.cores=2 } }' </code></pre> <p>It seems that the aws docs are wrong and that the configuration values are actually as follows.</p> <ul> <li><code>--conf spark.{driver|executor}.request.cores</code></li> <li><code>--conf spark.{driver|executor}.limit.cores</code></li> </ul> <p>However, the AWS docs has you pass in <code>--conf spark.driver.cores=1</code>. This value didn't seem to be acknowledged which I believe caused my error. The spark configuration docs below mention that <code>spark.driver.request.cores</code> have precedence over <code>spark.driver.cores</code>, which I think makes sense as the value was recognized when I passed that it.</p> <p><a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html#configuration" rel="nofollow noreferrer">https://spark.apache.org/docs/latest/running-on-kubernetes.html#configuration</a></p>
<p>I want to fetch the list (if any) of <code>kubernetes</code> nodes that <strong>do not</strong> contain a label.</p> <p>I have managed to do the opposite using <code>client-go</code></p> <pre><code> labelSelector := metav1.LabelSelector{ MatchLabels: map[string]string{ &quot;somelabel&quot;: &quot;somevalue&quot;, }, } labelMap, err := metav1.LabelSelectorAsMap(&amp;labelSelector) if err != nil { return false, errors.Wrap(err, &quot;error converting node label selector to map&quot;) } nodeListOptions := metav1.ListOptions{ LabelSelector: labels.SelectorFromSet(labelMap).String(), } nodes, err := clientset.CoreV1().Nodes().List(nodeListOptions) if err != nil { return false, errors.Wrap(err, &quot;error getting node list&quot;) } </code></pre> <p>What I want to achieve is to convert the following <code>kubectl</code> invocation</p> <pre><code>kubectl get ns --selector='!label_name' </code></pre> <p>into <code>client-go</code> code.</p> <p>Is this feasible?</p>
<p>I think one has to use the <code>Requirement</code> <a href="https://pkg.go.dev/k8s.io/apimachinery/pkg/labels#Requirement" rel="nofollow noreferrer">type</a> of the <code>apimachinery</code>'s <code>labels</code> package and create <code>Selector</code> <a href="https://pkg.go.dev/k8s.io/apimachinery/pkg/labels#Selector" rel="nofollow noreferrer">constructs</a> based on this.</p> <pre class="lang-golang prettyprint-override"><code>nodeReq, err := labels.NewRequirement(&quot;label_name&quot;, selection.DoesNotExist, []string{}) if err != nil { return false, errors.Wrap(err, &quot;error creating selector requirement&quot;) } selector := labels.NewSelector() selector = selector.Add(*nodeReq) if err != nil { return false, errors.Wrap(err, &quot;error converting node label selector to map&quot;) } nodeListOptions := metav1.ListOptions{ LabelSelector: selector.String(), } nodes, err := clientset.CoreV1().Nodes().List(nodeListOptions) </code></pre>
<p>Assuming I have two services: customerService and orderService. Both are Springboot applications contained in its own dockerfile.</p> <p>In production they should be managed using Kubernetes. So there could be mutliple instances of each service. As the services should be able to call each other via REST I want to use ServiceDiscovery to get the destination of a service instance of the respective other type (e.g. customerService wants to get host, port, etc. of a running orderService instance).</p> <p>I want to achieve this by using an injected DiscoveryClient in my Spring Boot services.</p> <p>I understand how this works in production as there is the Kubernetes cluster the DiscoveryClient communicates with.</p> <p>But how does this work in a local environment where there is no Kubernetes but only Docker running?</p>
<p>I think you should be looking into <strong>Kubernetes services</strong> instead of using an injected Discovery client.</p> <p>For Service discovery and load-balancing, you can use Services in Kubernetes. From Kubernetes documentation:</p> <blockquote> <p>An abstract way to expose an application running on a set of Pods as a network service. With Kubernetes, you don't need to modify your application to use an unfamiliar service discovery mechanism. Kubernetes gives Pods their own IP addresses and a single DNS name for a set of Pods and can load-balance across them.</p> </blockquote> <p>By this, you can also avoid the overhead of maintaining discovery server instances and their availability.</p> <p><em>How does this work in a local environment where there is no Kubernetes but only Docker running?</em></p> <p>You can use <strong>spring profiles for picking this URL based on your environment</strong>.</p> <p>For example, you'll have two spring configuration files (application-dev, application-prod) and in the dev file the URL for the second application would be localhost relative and in the prod file, the URL would be the DNS which you'll get as a part of Kubernetes service setup. So use the profile dev while running in local and prod while running in production(or an appropriate profile for your Kubernetes environment).</p>
<p>A graph is always better than the last sentences, so here is what I would like to do :</p> <p><a href="https://i.stack.imgur.com/A9eCa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A9eCa.png" alt="enter image description here" /></a></p> <p>To sum up:</p> <ul> <li>I want to have a Redis master instance outside (or inside, this is not relevant here) my K8S cluster</li> <li>I want to have a Redis slave instance <strong>per node</strong> replicating the master instance</li> <li>I want that when removing a node, the Redis slave pod gets unregistered from master</li> <li>I want that when adding a node, a Redis slave pod is added to the node and registered to the master</li> <li>I want all pods in one node to consume only the data of the local Redis slave (easy part I think)</li> </ul> <p>Why do I want such an architecture?</p> <ul> <li>I want to take advantage of Redis master/slave replication to avoid dealing with cache invalidation myself</li> <li>I want to have ultra-low latency calls to Redis cache, so having one slave per node is the best I can get (calling on local host network)</li> </ul> <p>Is it possible to automate such deployments, using Helm for instance? Are there domcumentation resources to make such an architecture with clean dynamic master/slave binding/unbinding?</p> <p>And most of all, is this architecture a good idea for what I want to do? Is there any alternative that could be as fast?</p>
<p>i remember we had a discussion on this topic previously <a href="https://stackoverflow.com/questions/70257094/redis-master-slave-on-gcp-memorystore">here</a>, no worries adding more here.</p> <p>Read more about the Redis helm chart : <a href="https://github.com/bitnami/charts/tree/master/bitnami/redis#choose-between-redis-helm-chart-and-redis-cluster-helm-chart" rel="nofollow noreferrer">https://github.com/bitnami/charts/tree/master/bitnami/redis#choose-between-redis-helm-chart-and-redis-cluster-helm-chart</a></p> <blockquote> <p>You should also be asking the question of how my application will be connecting to POD on same Node without using the service of Redis.</p> </blockquote> <p>For that, you can use the `environment variables and expose them to <strong>application</strong> <strong>POD</strong>.</p> <p>Something like :</p> <pre><code>env: - name: HOST_IP valueFrom: fieldRef: fieldPath: status.hostIP </code></pre> <p>It will give you the value of <strong>Node IP</strong> on which the <strong>POD</strong> is running, then you can use that IP to connect to <strong>DeamonSet</strong> (Redis slave if you are running).</p> <p>You can read more at : <a href="https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/</a></p> <blockquote> <p>Is it possible to automate such deployments, using Helm for instance?</p> </blockquote> <p>Yes, you can write down your own Helm chart and deploy the generated <strong>YAML</strong> manifest.</p> <blockquote> <p>And most of all, is this architecture a good idea for what I want to do? Is there any alternative that could be as fast?</p> </blockquote> <p>If you think then it is a good idea, as per my consideration this could create the <strong>$$$</strong> issue &amp; higher cluster resources usage.</p> <p>What if you are running the 200 nodes on each you will be running the slave of Redis ? Which might consume resources on each node and add cost to your <strong>infra</strong>.</p> <p><strong>OR</strong></p> <p>if you are planning for <strong>specific deployment</strong></p> <p>Your above suggestion is also good, but still, if you are planning to use the <strong>Redis</strong> with <strong>only Specific</strong> <strong>deployment</strong> you can use the sidecar pattern also and connect multiple Redis together using configuration.</p> <pre><code>apiVersion: v1 kind: Service metadata: name: web labels: app: web spec: ports: - port: 80 name: redis targetPort: 5000 selector: app: web type: LoadBalancer --- apiVersion: apps/v1 kind: Deployment metadata: name: web spec: selector: matchLabels: app: web replicas: 3 template: metadata: labels: app: web spec: containers: - name: redis image: redis ports: - containerPort: 6379 name: redis protocol: TCP - name: web-app image: web-app env: - name: &quot;REDIS_HOST&quot; value: &quot;localhost&quot; </code></pre>
<p>I have a monorepo nodejs/react app that I want to deploy to GKE using Helm charts. I added two Dockerfiles one for the frontend and the other for the back.</p> <p>I'm using Helm Charts to deploy my microservices to the Kubernetes cluster but this time I don't know how to configure it so that I can deploy both back and front simultaneously to GKE.</p> <p>Should I configure a values.yaml file for each service and keep the other templates as they are (ingress, service, deployment, hpa) or should I work on each service independently?</p>
<p>Posting this as an answer for better visibility since it's a good solution:</p> <p><a href="https://stackoverflow.com/questions/70436517/deploy-both-front-and-backend-using-helm-charts#comment124510627_70436517">David suggested</a> that you can</p> <blockquote> <p>probably put both parts into the same Helm chart, probably with different <code>templates/*.yaml</code> files for the front-and back-end parts.</p> <p>If you had a good argument that the two parts are separate (maybe different development teams work on them and you have a good public API contract) it's fine to deploy them separately</p> </blockquote>
<p>I wouldd to create a persistent volume on my kubernetes (gcp) cluster and use it in my django app as , for example, media folder. On my kubernetes side i do:</p> <p>First create a volumes claim:</p> <pre><code>apiVersion: v1 kind: PersistentVolumeClaim metadata: name: pvc-zeus namespace: ctest spec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi </code></pre> <p>, then in my deployments.yaml i create a volume and associate to the pod:</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: django namespace: ctest labels: app: django spec: replicas: 3 selector: matchLabels: app: django template: metadata: labels: app: django spec: volumes: - name: cc-volume persistentVolumeClaim: claimName: pvc-zeus containers: - name: django image: gcr.io/direct-variety-3066123/cc-mirror volumeMounts: - mountPath: &quot;/app/test-files&quot; name: cc-volume ... </code></pre> <p>then in my django settings:</p> <pre><code>MEDIA_URL = '/test-files/' </code></pre> <p>Here my Dockerfile:</p> <pre><code>FROM python:3.8-slim ENV PROJECT_ROOT /app WORKDIR $PROJECT_ROOT COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . RUN chmod +x run.sh CMD python manage.py runserver --settings=settings.kube 0.0.0.0:8000 </code></pre> <p>when i apply volume claim on my cluster all was done (volume claim was created) but whe apply deployment.yaml no volume was created for the pods (also if i connect in bash to my pods, no folder test-files exist).</p> <p>How can i create a volume on my deployments pods and use it in my django app?</p> <p>So many thanks in advance</p>
<p>You need to have one of two Kubernetes objects in place in order to make a PVC: a <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/" rel="nofollow noreferrer">PersistentVolume</a>(PV) or a <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/" rel="nofollow noreferrer">StorageClass</a>(SC).</p> <p>As you showed, your PVC <strong>does not indicate a PV or a SC</strong> from which to create a volume.</p> <p>Usually, when you don't specify a PV or a SC in a PVC, a default SC will be used and you are not supposed to indicate the .resources in the PVC but in the default SC.</p> <p>Maybe, if you just want to work with default SC, you would want to check if your specific cluster has it active or whether you need to create/activate it.</p>
<p>I deployed prometheus and adapter. I want to get custom metrics, but can't find resource</p> <pre><code>$ kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1 Error from server (NotFound): the server could not find the requested resource $ kubectl get --raw /metrics Error from server (NotFound): the server could not find the requested resource $ kubectl get apiservice NAME SERVICE AVAILABLE AGE v1. Local True 32d v1.admissionregistration.k8s.io Local True 32d v1.apiextensions.k8s.io Local True 32d v1.apps Local True 32d v1.authentication.k8s.io Local True 32d v1.authorization.k8s.io Local True 32d v1.autoscaling Local True 32d v1.batch Local True 32d v1.certificates.k8s.io Local True 32d v1.coordination.k8s.io Local True 32d v1.discovery.k8s.io Local True 32d v1.events.k8s.io Local True 32d v1.monitoring.coreos.com Local True 3d17h v1.networking.k8s.io Local True 32d v1.node.k8s.io Local True 32d v1.policy Local True 32d v1.rbac.authorization.k8s.io Local True 32d v1.scheduling.k8s.io Local True 32d v1.storage.k8s.io Local True 32d v1alpha1.crd.k8s.amazonaws.com Local True 32d v1alpha1.kafka.strimzi.io Local True 28d v1alpha1.monitoring.coreos.com Local True 3d17h v1beta1.admissionregistration.k8s.io Local True 32d v1beta1.apiextensions.k8s.io Local True 32d v1beta1.authentication.k8s.io Local True 32d v1beta1.authorization.k8s.io Local True 32d v1beta1.batch Local True 32d v1beta1.certificates.k8s.io Local True 32d v1beta1.coordination.k8s.io Local True 32d v1beta1.custom.metrics.k8s.io monitoring/my-prometheus-adapter True 17m v1beta1.discovery.k8s.io Local True 32d v1beta1.events.k8s.io Local True 32d v1beta1.extensions Local True 32d v1beta1.flowcontrol.apiserver.k8s.io Local True 32d v1beta1.kafka.strimzi.io Local True 28d v1beta1.metrics.k8s.io kube-system/metrics-server True 25d v1beta1.networking.k8s.io Local True 32d v1beta1.node.k8s.io Local True 32d v1beta1.policy Local True 32d v1beta1.rbac.authorization.k8s.io Local True 32d v1beta1.scheduling.k8s.io Local True 32d v1beta1.storage.k8s.io Local True 32d v1beta1.vpcresources.k8s.aws Local True 32d v1beta2.kafka.strimzi.io Local True 28d v2beta1.autoscaling Local True 32d v2beta2.autoscaling Local True 32d </code></pre> <p>how can i get custom resource?</p>
<p>This is EKS related <a href="https://github.com/kubernetes-sigs/metrics-server/issues/45" rel="nofollow noreferrer">known issue</a>.</p> <p>To resolve it, you should <a href="https://github.com/kubernetes-sigs/metrics-server/issues/45#issuecomment-421345121" rel="nofollow noreferrer">update the kubernetes nodes security groups to allow ingress / incoming https connections from the EKS masters security group.</a></p> <p>Please check below resolved github issues.</p> <ul> <li><a href="https://github.com/kubernetes-sigs/metrics-server/issues/45" rel="nofollow noreferrer">Metrics server api not getting registered #45</a></li> <li><a href="https://github.com/kubernetes-sigs/metrics-server/issues/129" rel="nofollow noreferrer">[EKS] unable to fetch metrics from Kubelet #129</a></li> <li><a href="https://github.com/awslabs/amazon-eks-ami/issues/55" rel="nofollow noreferrer">Metrics Server not working #55</a></li> </ul>
<p>I have a aws <strong>EC2</strong> (EC2-A) and <strong>Amazon Managed Blockchain</strong> running in <strong>VPC (VPC-A)</strong></p> <ul> <li>This EC2-A instance has some files and certificates (required for executing transactions in the blockchain)</li> <li>EC2-A has EBS storage which can be mounted on only one EC2 instance at one time.</li> <li>Transactions can be only executed to the blockchain network from the EC2-A, since they're are in the same VPC-A.</li> </ul> <p>I have an aws <strong>EKS (Kubernetes cluster) running in VPC-B.</strong></p> <p>How can I <em>access the files and certificates of EC2-A from a pod in my k8s cluster.</em> Also I have another <strong>pod</strong> which will be blockchain client <strong>executing transactions in the blockchain network, which is in VPC-A.</strong></p> <p>Both these VPC-A and VPC-B are in the same aws account.</p>
<p>Mount a folder/files on an EC2 instance to a pod running in EKS is not supported. For your use case, you can easily share folder/files using EFS if not S3. If you are only allow to do pod to EC2 communication, you need a way for these resources to reach each other either by public IP if not VPC peering. Then you can run sftp, scp... any kind of off the shelf file sharing software you knew best for file exchange.</p>
<p>I'm new with Kubernetes and Azure. I want to Deply my application and I am floowing the microsoft tutorial about kubernetes. At first I have created the resouce group and ACR instance. When I try to login in ACR console show this error: <code>Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?</code></p> <p>I'm using azure cli localy and I have docker running.</p>
<p>You can try below options to connect ACR :</p> <p>run az acr login first with the --expose-token parameter. This option exposes an access token instead of logging in through the Docker CLI.</p> <pre><code>az acr login --name &lt;acrName&gt; --expose-token </code></pre> <p>Output displays the access token, abbreviated here:</p> <pre><code>{ &quot;accessToken&quot;: &quot;eyJhbGciOiJSUzI1NiIs[...]24V7wA&quot;, &quot;loginServer&quot;: &quot;myregistry.azurecr.io&quot; } </code></pre> <p>For registry authentication, we recommend that you store the token credential in a safe location and follow recommended practices to manage docker login credentials. For example, store the token value in an environment variable:</p> <pre><code>TOKEN=$(az acr login --name &lt;acrName&gt; --expose-token --output tsv --query accessToken) </code></pre> <p>Then, run docker login, passing 00000000-0000-0000-0000-000000000000 as the username and using the access token as password:</p> <pre><code>docker login myregistry.azurecr.io --username 00000000-0000-0000-0000-000000000000 --password $TOKEN </code></pre> <p>you will get the below promt if you follow the above method :</p> <pre><code>WARNING! Using --password via the CLI is insecure. Use --password-stdin. Login Succeeded </code></pre>
<p>In Kubernetes configuration, for external service component we use:</p> <pre><code>type: LoadBalancer </code></pre> <p>If we have k8s cluster running inside a cloud provider like AWS, which provides it own loadbalancer, how does all this work then? Do we need to configure so that one of these loadbalancers is not active?</p>
<p>AWS now takes over the open source project: <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller" rel="nofollow noreferrer">https://kubernetes-sigs.github.io/aws-load-balancer-controller</a></p> <p>It works with EKS(easiest) clusters as well as <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.3/deploy/installation/" rel="nofollow noreferrer">non-EKS clusters</a>(need to install aws vpc cni etc to make <code>IP</code> target mode work, which is required if you have a peered VPC environment.)</p> <p>This is the official/native solution of managing AWS LB(aka ELBv2) resources(App ELB, Network ELB) using K8s. Kubernetes in-tree controller always reconciles <code>Service</code> object with <code>type: LoadBalancer</code></p> <p>Once configured correctly, AWS LB controller will manage the following 2 types of LBs:</p> <ol> <li>Application LB, via Kubernetes <code>Ingress</code> object. It operates on L7 and provides features related to HTTP</li> <li>Network LB, via Kubernetes <code>Service</code> object with <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.3/guide/service/nlb/" rel="nofollow noreferrer">correct annotations</a>. It operates on L4 and provides less features but claimed MUCH higher throughput.</li> </ol> <p>To my knowledge, this works best when used with <code>external-dns</code> together -- it automatically updates your Route53 record with your LB A records thus makes the whole service discovery solution k8s-y.</p> <p>Also in general, should prevent usage of classic ELB, as it's marked as deprecated by AWS.</p>
<p>I accidentally was checking if my pod had the right <code>ServiceAccount</code> and its Bindings. Out of curiosity I wanted to check if the token created from this service account is bound with the certain <code>ClusterRole</code> and <code>ClusterRoleBinding</code> which are read only. I tried few things from <a href="https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/#without-kubectl-proxy" rel="nofollow noreferrer">Kubernetes Documentation</a>, and I am afraid my understanding is somewhat wrong. Please help me to understand this correctly.</p> <p>I used existing <code>ClusterRole</code> <code>view</code> and associated to my service account <code>my-sa</code> as <code>ClusterRoleBinding</code>.</p> <pre><code>APISERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}') SECRET_NAME=$(kubectl get serviceaccount my-sa -o jsonpath='{.secrets[0].name}') TOKEN=$(kubectl get secret $SECRET_NAME -o jsonpath='{.data.token}' | base64 --decode) </code></pre> <p>Then I use the <code>TOKEN</code> to talk to <code>APISERVER</code> for creating a pod in test namespace</p> <pre><code>curl -X POST $APISERVER/api/v1/namespaces/test/pods\?fieldManager=kubectl-run -d '{&quot;kind&quot;:&quot;Pod&quot;, &quot;apiVersion&quot;:&quot;v1&quot;, &quot;metadata&quot;: { &quot;name&quot;:&quot;nginx&quot;, &quot;creationTimestamp&quot;:null, &quot;labels&quot;:{&quot;run&quot;:&quot;nginx&quot;} }, &quot;spec&quot;: { &quot;containers&quot;: [ { &quot;name&quot;:&quot;nginx&quot;, &quot;image&quot;:&quot;nginx&quot;, &quot;resources&quot;:{} } ], &quot;restartPolicy&quot;:&quot;Always&quot;, &quot;dnsPolicy&quot;:&quot;ClusterFirst&quot; }, &quot;status&quot;:{} }' --header &quot;Content-Type: application/json&quot; --header &quot;Authorization: Bearer $TOKEN&quot; --header &quot;Accept: application/json, */*&quot; --insecure </code></pre> <p>What Happened</p> <ol> <li>This created a successful pod and this token moreoever can create anything.</li> <li>I even tried to use the <code>default ServiceAccount</code> from the <code>default</code> namespace and the behavior is same</li> </ol> <p>My Understanding.</p> <ol> <li>This token was associated with the <code>ClusterRole</code> of <code>View</code> hence it should not have allowed the token to create any resource.</li> <li>Isnt this a loophole because if I am able to get the ServiceAccount Token from a client code and pass it outside the cluster?</li> </ol> <p>My Setup: Docker Desktop Kubernetes.</p> <p>Please help me in understanding what is incorrect in this. I am unable to understand the scope of the <code>ServiceAccount</code> token. I tried to google on this but I couldnt find it. Probably I did not have the right set of words to find it.</p> <p>EDIT-1:</p> <p>Describing ClusterRole View.</p> <pre><code> Name: view Labels: kubernetes.io/bootstrapping=rbac-defaults rbac.authorization.k8s.io/aggregate-to-edit=true Annotations: rbac.authorization.kubernetes.io/autoupdate: true PolicyRule: Resources Non-Resource URLs Resource Names Verbs --------- ----------------- -------------- ----- bindings [] [] [get list watch] configmaps [] [] [get list watch] endpoints [] [] [get list watch] events [] [] [get list watch] limitranges [] [] [get list watch] namespaces/status [] [] [get list watch] namespaces [] [] [get list watch] persistentvolumeclaims/status [] [] [get list watch] persistentvolumeclaims [] [] [get list watch] pods/log [] [] [get list watch] pods/status [] [] [get list watch] pods [] [] [get list watch] replicationcontrollers/scale [] [] [get list watch] replicationcontrollers/status [] [] [get list watch] replicationcontrollers [] [] [get list watch] resourcequotas/status [] [] [get list watch] resourcequotas [] [] [get list watch] serviceaccounts [] [] [get list watch] services/status [] [] [get list watch] services [] [] [get list watch] controllerrevisions.apps [] [] [get list watch] daemonsets.apps/status [] [] [get list watch] daemonsets.apps [] [] [get list watch] deployments.apps/scale [] [] [get list watch] deployments.apps/status [] [] [get list watch] deployments.apps [] [] [get list watch] replicasets.apps/scale [] [] [get list watch] replicasets.apps/status [] [] [get list watch] replicasets.apps [] [] [get list watch] statefulsets.apps/scale [] [] [get list watch] statefulsets.apps/status [] [] [get list watch] statefulsets.apps [] [] [get list watch] horizontalpodautoscalers.autoscaling/status [] [] [get list watch] horizontalpodautoscalers.autoscaling [] [] [get list watch] cronjobs.batch/status [] [] [get list watch] cronjobs.batch [] [] [get list watch] jobs.batch/status [] [] [get list watch] jobs.batch [] [] [get list watch] daemonsets.extensions/status [] [] [get list watch] daemonsets.extensions [] [] [get list watch] deployments.extensions/scale [] [] [get list watch] deployments.extensions/status [] [] [get list watch] deployments.extensions [] [] [get list watch] ingresses.extensions/status [] [] [get list watch] ingresses.extensions [] [] [get list watch] networkpolicies.extensions [] [] [get list watch] replicasets.extensions/scale [] [] [get list watch] replicasets.extensions/status [] [] [get list watch] replicasets.extensions [] [] [get list watch] replicationcontrollers.extensions/scale [] [] [get list watch] ingresses.networking.k8s.io/status [] [] [get list watch] ingresses.networking.k8s.io [] [] [get list watch] networkpolicies.networking.k8s.io [] [] [get list watch] poddisruptionbudgets.policy/status [] [] [get list watch] poddisruptionbudgets.policy [] [] [get list watch] </code></pre>
<p>Summary of <a href="https://github.com/docker/for-mac/issues/3694" rel="nofollow noreferrer">issue</a> from <a href="https://www.portainer.io/blog/docker-desktop-kubernetes-not-enforcing-rbac-rules" rel="nofollow noreferrer">Neil Cresswell on portainer.io</a></p> <p>By default, Docker Desktop and their embedded Kubernetes offering does <strong>NOT</strong> enforce any RBAC rules. It will let you create RBAC rules, but it wont enforce them.</p> <p><strong>ALL</strong> service accounts automatically receive <strong>cluster-admin</strong> role <strong>BY DEFAULT</strong>.</p> <p>The article says this can be easily fixed by running <code>kubectl delete clusterrolebinding docker-for-desktop-binding</code> and it will start enforcing RBAC rules.</p> <p>You can also <a href="https://github.com/docker/for-mac/issues/4774#issuecomment-658128960" rel="nofollow noreferrer">patch this issue</a> on your own deploys by running:</p> <pre><code>kubectl apply -f - &lt;&lt;EOF apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: docker-for-desktop-binding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:serviceaccounts:kube-system EOF </code></pre>
<p><strong>Cannot install the helm chart but when I use raw file generated by helm, I am able to install via kubectl apply.</strong></p> <p>Following error is displayed when i use <code>helm install myChart . --debug</code></p> <pre><code>Error: cannot re-use a name that is still in use helm.go:88: [debug] cannot re-use a name that is still in use helm.sh/helm/v3/pkg/action.(*Install).availableName helm.sh/helm/v3/pkg/action/install.go:442 helm.sh/helm/v3/pkg/action.(*Install).Run helm.sh/helm/v3/pkg/action/install.go:185 main.runInstall helm.sh/helm/v3/cmd/helm/install.go:242 main.newInstallCmd.func2 helm.sh/helm/v3/cmd/helm/install.go:120 github.com/spf13/cobra.(*Command).execute github.com/spf13/cobra@v1.1.3/command.go:852 github.com/spf13/cobra.(*Command).ExecuteC github.com/spf13/cobra@v1.1.3/command.go:960 github.com/spf13/cobra.(*Command).Execute github.com/spf13/cobra@v1.1.3/command.go:897 main.main helm.sh/helm/v3/cmd/helm/helm.go:87 runtime.main runtime/proc.go:225 runtime.goexit runtime/asm_amd64.s:1371 </code></pre> <p>Installing raw file generated by helm with the following command works great but when I run <code>helm install myChart .</code> it gives the above error</p> <pre><code>helm install myChart . --dry-run &gt; myChart.yaml kubectl apply -f myChart.yaml </code></pre>
<p>Use upgrade instead install:</p> <pre><code>helm upgrade -i myChart . </code></pre> <p>The <code>-i</code> flag install the release if it doesn't exist.</p>