prompt stringlengths 65 38.7k | response stringlengths 41 29.1k |
|---|---|
<p>I am trying to set some values in server.xml using environment variables. From this <a href="https://stackoverflow.com/questions/67214216/how-to-set-org-apache-tomcat-util-digester-environmentpropertysource-in-tomcat">how to set org.apache.tomcat.util.digester.EnvironmentPropertySource in tomcat</a>, I create setenv.sh file in /tomcat/bin with this:</p>
<pre><code>CATALINA_OPTS="$CATALINA_OPTS -Dorg.apache.tomcat.util.digester.PROPERTY_SOURCE=org.apache.tomcat.util.digester.EnvironmentPropertySource"
</code></pre>
<p>When I run tomcat, I get this exception:</p>
<pre><code>org.apache.tomcat.util.digester.Digester.<clinit> Unable to load property source[org.apache.tomcat.util.digester.EnvironmentPropertySource].
</code></pre>
<p>I am really new to tomcat, so I have no idea what it means. I am not sure even if it is related to the <code>setenv.sh</code>. I don't see the same exception without <code>setenv.sh</code> file. I tried to research on this topic, but not many information was found.</p>
<p>Can anyone please answer why this is happening?</p>
<p>EDIT: here is my whole stack trace from the log file</p>
<pre><code>26-Apr-2021 19:32:44.857 SEVERE [main] org.apache.tomcat.util.digester.Digester.<clinit> Unable to load property source[org.apache.tomcat.util.digester.EnvironmentPropertySource].
java.lang.ClassNotFoundException: org.apache.tomcat.util.digester.EnvironmentPropertySource
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.tomcat.util.digester.Digester.<clinit>(Digester.java:97)
at org.apache.catalina.startup.Catalina.createStartDigester(Catalina.java:272)
at org.apache.catalina.startup.Catalina.load(Catalina.java:528)
at org.apache.catalina.startup.Catalina.load(Catalina.java:644)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:311)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:494)
26-Apr-2021 19:32:44.859 SEVERE [main] org.apache.tomcat.util.digester.Digester.<clinit> Unable to load property source[org.apache.tomcat.util.digester.EnvironmentPropertySource].
java.lang.ClassNotFoundException: org.apache.tomcat.util.digester.EnvironmentPropertySource
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.tomcat.util.digester.Digester.<clinit>(Digester.java:97)
at org.apache.catalina.startup.Catalina.createStartDigester(Catalina.java:272)
at org.apache.catalina.startup.Catalina.load(Catalina.java:528)
at org.apache.catalina.startup.Catalina.load(Catalina.java:644)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:311)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:494)
</code></pre>
| <p>The <code>org.apache.tomcat.util.digester.EnvironmentPropertySource</code> class is available since <a href="https://tomcat.apache.org/tomcat-7.0-doc/changelog.html#Tomcat_7.0.101_(violetagg)" rel="nofollow noreferrer">Tomcat 7.0.108</a>, <a href="https://tomcat.apache.org/tomcat-8.5-doc/changelog.html#Tomcat_8.5.52_(markt)" rel="nofollow noreferrer">Tomcat 8.5.65</a> and <a href="https://tomcat.apache.org/tomcat-9.0-doc/changelog.html#Tomcat_9.0.32_(markt)" rel="nofollow noreferrer">Tomcat 9.0.45</a>. You must be running an older release.</p>
|
<p>I am trying to run a pod where the default limit of my <strong>GKE AutoPilot Cluster is 500m vCPU</strong>.. But I want to run all my pods by 250m vCPU only. I tried the command <code>kubectl run pod-0 --requests="cpu=150m" --restart=Never --image=example/only</code></p>
<p>But I get a warning: <code>Flag --requests has been deprecated, has no effect and will be removed in the future</code>. Then when I describe my pod, it sets <code>500m</code>. I would like to know option to set resource limits with just plainly <code>kubectl run pod</code></p>
| <p>Since kubectl v1.21 All generators are depricated.</p>
<p>Github issue: <a href="https://github.com/kubernetes/kubernetes/issues/93100" rel="nofollow noreferrer">Remove generators from kubectl commands</a> quote:</p>
<blockquote>
<p>kubectl command are going to get rid of the dependency to the
generators, and ultimately remove them entirely. <strong>The main goal is to
simplyfy the use of kubectl command</strong>. This is already done in kubectl
run, see <a href="https://github.com/kubernetes/kubernetes/pull/87077" rel="nofollow noreferrer">#87077</a> and <a href="https://github.com/kubernetes/kubernetes/pull/68132" rel="nofollow noreferrer">#68132</a>.</p>
</blockquote>
<p>So it looks like <code>--limits</code> and <code>--requests</code> flags won't longer be available in the future.</p>
<p>Here is the PR that did it: <a href="https://github.com/kubernetes/kubernetes/pull/99732" rel="nofollow noreferrer">Drop deprecated run flags and deprecate unused ones</a>.</p>
|
<p>I have ingress yaml like below which makes ingress to proxy HTTPS to HTTP connection. I'm confused how can I make this same ingress to process also HTTP to HTTP connection. Meaning I want it to use the same rule for both incoming HTTP or HTTPS. Removing <code>tls</code> portion makes it work with HTTP but adding it stops HTTP and makes it HTTPS only. Is it limitation of Kubernetes which prevents both HTTP and HTTPS routing in the same ingress controller?</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress
annotations:
kubernetes.io/ingress.class: azure/application-gateway
spec:
tls:
- hosts:
- "*.mydomain.com"
secretName: aks-ingress-tls
rules:
- host: "*.mydomain.net"
http:
paths:
- pathType: Prefix
path: "/"
backend:
service:
name: frontend-service
port:
number: 80
</code></pre>
| <p>You should redirect the HTTP request to your HTTPS listener. The requests hitting your Azure LB 80/443 listeners will be handled in the same way.</p>
<p>Due to Azure App gateway <a href="https://github.com/Azure/application-gateway-kubernetes-ingress/issues/1001" rel="nofollow noreferrer">limitation</a>, you cannot use a wildcard host in your ingress rules and you have to use workarounds.</p>
<p>See: <a href="https://azure.github.io/application-gateway-kubernetes-ingress/annotations/#ssl-redirect" rel="nofollow noreferrer">https://azure.github.io/application-gateway-kubernetes-ingress/annotations/#ssl-redirect</a></p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress
annotations:
kubernetes.io/ingress.class: azure/application-gateway
appgw.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls:
- hosts:
- "*.mydomain.com"
secretName: aks-ingress-tls
rules:
- host: "www.mydomain.com"
http:
paths:
- pathType: Prefix
path: "/"
backend:
service:
name: frontend-service
port:
number: 80
</code></pre>
|
<p>Playing around with K8 and ingress in local minikube setup. Creating ingress from yaml file in networking.k8s.io/v1 api version fails. See below output.
Executing</p>
<pre><code>> kubectl apply -f ingress.yaml
</code></pre>
<p>returns</p>
<pre><code>Error from server (InternalError): error when creating "ingress.yaml": Internal error occurred: failed calling webhook "validate.nginx.ingress.kubernetes.io": an error on the server ("") has prevented the request from succeeding
</code></pre>
<p>in local minikube environment with hyperkit as vm driver.</p>
<p>Here is the <code>ingress.yaml</code> file:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: mongodb-express-ingress
namespace: hello-world
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: mongodb-express.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: mongodb-express-service-internal
port:
number: 8081
</code></pre>
<p>Here is the mongodb-express deployment file:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: mongodb-express
namespace: hello-world
labels:
app: mongodb-express
spec:
replicas: 1
selector:
matchLabels:
app: mongodb-express
template:
metadata:
labels:
app: mongodb-express
spec:
containers:
- name: mongodb-express
image: mongo-express
ports:
- containerPort: 8081
env:
- name: ME_CONFIG_MONGODB_ADMINUSERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: mongodb-root-username
- name: ME_CONFIG_MONGODB_ADMINPASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: mongodb-root-password
- name: ME_CONFIG_MONGODB_SERVER
valueFrom:
configMapKeyRef:
name: mongodb-configmap
key: mongodb_url
---
apiVersion: v1
kind: Service
metadata:
name: mongodb-express-service-external
namespace: hello-world
spec:
selector:
app: mongodb-express
type: LoadBalancer
ports:
- protocol: TCP
port: 8081
targetPort: 8081
nodePort: 30000
---
apiVersion: v1
kind: Service
metadata:
name: mongodb-express-service-internal
namespace: hello-world
spec:
selector:
app: mongodb-express
ports:
- protocol: TCP
port: 8081
targetPort: 8081
</code></pre>
<p>Some more information:</p>
<pre><code>> kubectl version
Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.7", GitCommit:"1dd5338295409edcfff11505e7bb246f0d325d15", GitTreeState:"clean", BuildDate:"2021-01-13T13:23:52Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.2", GitCommit:"faecb196815e248d3ecfb03c680a4507229c2a56", GitTreeState:"clean", BuildDate:"2021-01-13T13:20:00Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
> minikube version
minikube version: v1.19.0
commit: 15cede53bdc5fe242228853e737333b09d4336b5
> kubectl get all -n hello-world
NAME READY STATUS RESTARTS AGE
pod/mongodb-68d675ddd7-p4fh7 1/1 Running 0 3h29m
pod/mongodb-express-6586846c4c-5nfg7 1/1 Running 6 3h29m
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/mongodb-express-service-external LoadBalancer 10.106.185.132 <pending> 8081:30000/TCP 3h29m
service/mongodb-express-service-internal ClusterIP 10.103.122.120 <none> 8081/TCP 3h3m
service/mongodb-service ClusterIP 10.96.197.136 <none> 27017/TCP 3h29m
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/mongodb 1/1 1 1 3h29m
deployment.apps/mongodb-express 1/1 1 1 3h29m
NAME DESIRED CURRENT READY AGE
replicaset.apps/mongodb-68d675ddd7 1 1 1 3h29m
replicaset.apps/mongodb-express-6586846c4c 1 1 1 3h29m
> minikube addons enable ingress
▪ Using image k8s.gcr.io/ingress-nginx/controller:v0.44.0
▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
🔎 Verifying ingress addon...
🌟 The 'ingress' addon is enabled
> kubectl get all -n ingress-nginx
NAME READY STATUS RESTARTS AGE
pod/ingress-nginx-admission-create-2bn8h 0/1 Completed 0 4h4m
pod/ingress-nginx-admission-patch-vsdqn 0/1 Completed 0 4h4m
pod/ingress-nginx-controller-5d88495688-n6f67 1/1 Running 0 4h4m
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/ingress-nginx-controller NodePort 10.111.176.223 <none> 80:32740/TCP,443:30636/TCP 4h4m
service/ingress-nginx-controller-admission ClusterIP 10.97.107.77 <none> 443/TCP 4h4m
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/ingress-nginx-controller 1/1 1 1 4h4m
NAME DESIRED CURRENT READY AGE
replicaset.apps/ingress-nginx-controller-5d88495688 1 1 1 4h4m
NAME COMPLETIONS DURATION AGE
job.batch/ingress-nginx-admission-create 1/1 7s 4h4m
job.batch/ingress-nginx-admission-patch 1/1 9s 4h4m
</code></pre>
<hr />
<p>However, it works for the beta api version, i.e.</p>
<pre><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: mongodb-express-ingress-deprecated
namespace: hello-world
spec:
rules:
- host: mongodb-express.local
http:
paths:
- path: /
backend:
serviceName: mongodb-express-service-internal
servicePort: 8081
</code></pre>
<p>Any help very much appreciated.</p>
| <p>I had the same issue. I successfully fixed it using:</p>
<p><code>kubectl delete -A ValidatingWebhookConfiguration ingress-nginx-admission</code></p>
<p>then apply the yaml files:</p>
<p><code>kubectl apply -f ingress_file.yaml</code></p>
|
<p>I have helm charts created for a microservice that I have built and everything is working as expected. Now, I have created a new k8s namespace and I want to try to deploy the same helm charts as my old namespace. Although, I have just one value that I need it different while everything else remain the same.</p>
<p>Do I have to create another values.yaml for the new namespace and copy everything over and update the one field I want updated ? Or is there any other way ? I do not want to use the --set method of passing updates to the command line.</p>
| <p>David suggested the right way. You can use different <code>values.yaml</code> where you can specify the namespace you want to deploy the chart:</p>
<pre><code>$ helm install -f another-namespace-values.yaml <my-release> .
</code></pre>
<p>It's also entirely possible to launch helm chart with multiple values.
For more reading please check <a href="https://helm.sh/docs/chart_template_guide/values_files/" rel="nofollow noreferrer">values</a> section of helm docs.</p>
|
<p>We are running a Java application in a Kubernetes cluster. The application itself doesn't have high demand for RAM, but I've noticed that it always consumes 1GB.</p>
<pre><code>kubectl top pods
NAME CPU(cores) MEMORY(bytes)
my-application-c0ffee 100m 1127Mi
my-application-c0ffee 100m 1109Mi
</code></pre>
<p>When I checked <code>jcmd <pid> GC.heap_info</code> inside the container, I got the following:</p>
<pre><code>def new generation total 89216K, used 12090K [0x00000000bc200000, 0x00000000c22c0000, 0x00000000d2c00000)
...
tenured generation total 197620K, used 151615K [0x00000000d2c00000, 0x00000000decfd000, 0x0000000100000000)
...
Metaspace used 146466K, capacity 152184K, committed 152576K, reserved 1183744K
class space used 18171K, capacity 19099K, committed 19200K, reserved 1048576K
</code></pre>
<p>As I understood, by default Java reserves 1GB of <em>virtual</em> memory size for storing Class information (in order to reference it in a compressed manner using 32 bit references this memory block should be reserved beforehand). When running outside of a container that's not a big deal, because this memory is not actually <em>committed</em>. It's only an address space that is <em>reserved</em>.</p>
<p>But it seems to be completely different situation in case of running inside container, where <em>reserved</em> memory becomes <em>committed</em>.</p>
<p>Does this mean that Java running in a container will by default consume at least 1GB of RAM?
And is there any other way to deal with that besides explicitly setting <code>-XX:CompressedClassSpaceSize</code>?</p>
| <blockquote>
<p>in case of running inside container, where reserved memory becomes committed</p>
</blockquote>
<p>No, reserved memory does not "become committed". The Virtual Size and the Resident Set Size are different metrics, whether in a container or not. What sits in the physical memory is RSS.</p>
<p><code>kubectl top</code> does not show you the RSS, but rather so-called "working set", which does not always match the real memory usage.</p>
<blockquote>
<p>Does this mean that Java running in a container will by default consume at least 1GB of RAM?</p>
</blockquote>
<p>No.</p>
<blockquote>
<p>is there any other way to deal with that</p>
</blockquote>
<p>It depends on your goals. If you'd like to see the actual container memory statistics, look at <code>/sys/fs/cgroup/memory/.../memory.stats</code> and <code>memory.usage_in_bytes</code>. Or if you use docker, run <code>docker stats</code>.</p>
<p>If you'd like to decrease the process' virtual memory instead, turn off <code>-XX:-UseCompressedClassPointers</code>.</p>
|
<p>I have the following Ingress configuration:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: http-ingress
spec:
rules:
- host: example-adress.com
http:
paths:
- path: /apple
pathType: Prefix
backend:
service:
name: apple-service
port:
number: 80
- path: /banana
pathType: Prefix
backend:
service:
name: banana-service
port:
number: 80
tls:
- hosts:
- example-adress.com
secretName: testsecret-tls
</code></pre>
<p>And i also created the Secret:</p>
<pre><code>apiVersion: v1
kind: Secret
metadata:
name: testsecret-tls
namespace: default
data:
tls.crt: path to .crt
tls.key: Zpath to .key
type: kubernetes.io/tls
</code></pre>
<p>But when i connect to one of my services and check the certificate it says that it uses a cert created by Kubernetes Ingress Controller Fake certificate.
When i run microk8s kubectl describe ingress i get the following output:</p>
<pre><code>Name: http-ingress
Namespace: default
Address: 127.0.0.1
Default backend: default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
TLS:
testsecret-tls terminates example-adress.com
Rules:
Host Path Backends
---- ---- --------
example-adress.com
/apple apple-service:80 (10.1.55.17:5678)
/banana banana-service:80 (10.1.55.10:5678)
Annotations: <none>
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal CREATE 28m nginx-ingress-controller Ingress default/http-ingress
Normal UPDATE 20m (x2 over 28m) nginx-ingress-controller Ingress default/http-ingress
</code></pre>
<p>What do i need to change to make my Ingress use my Cert instead of generating a new one everytime?</p>
| <p>Posting this out of comment as it works.</p>
<p>Based on your tls secret yaml, you tried to add certificate and private key using paths, which is not supported currently (<a href="https://kubernetes.io/docs/concepts/configuration/secret/#tls-secrets" rel="nofollow noreferrer">reference</a>)
Fragment from reference:</p>
<blockquote>
<p>When using this type of Secret, the <code>tls.key</code> and the <code>tls.crt</code> key must be provided in the <code>data</code> (or <code>stringData</code>) field of the Secret configuration, although the API server doesn't actually validate the values for each key.</p>
</blockquote>
<p>Therefore there are two suggestions how to move forward:</p>
<ul>
<li>Add base64 encrypted values for key and certificate to tls secret</li>
<li>Allow kubernetes do it for you with the following command:
<code>kubectl create secret tls testsecret-tls --cert=tls.cert --key=tls.key</code></li>
</ul>
|
<p>We have a service in our cluster that we call via ssh (test environment etc.). In this container we have different environment variables when we connect with ssh or we connect with kubectl.</p>
<p>Can someone explain me what else is set here with the kubectl exec command?</p>
<p>As an example a small excerpt from both environments.</p>
<p><strong>kubectl exec: (printenv | grep KU)</strong></p>
<pre><code>KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT_443_TCP=tcp://10.4.0.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_ADDR=10.4.0.1
KUBERNETES_SERVICE_HOST=10.4.0.1
KUBERNETES_PORT=tcp://10.4.0.1:443
KUBERNETES_PORT_443_TCP_PORT=443
</code></pre>
<p><strong>ssh into the same container: (printenv | grep KU)</strong></p>
<pre><code>dev-xxxxx:~$ printenv | grep KU
dev-xxxxx:~$
</code></pre>
| <p>The <code>kubectl exec</code> command allows you to remotely run arbitrary commands inside an existing container of a pod. <code>kubectl exec</code> isn’t much different from using <code>SSH</code> to execute commands on a remote system. <code>SSH</code> and <code>kubectl</code> should both work well with 99% of CLI applications. The only difference I could find when it comes to environment variables is that:</p>
<ul>
<li><p><code>kubectl</code> will always set the environment variables provided to the container at startup</p>
</li>
<li><p><code>SSH</code> relies mostly on the system login shell configuration (but can also accept user’s environment via <a href="https://superuser.com/questions/48783/how-can-i-pass-an-environment-variable-through-an-ssh-command">PermitUserEnvironment or SendEnv/AcceptEnv</a>)</p>
</li>
</ul>
<p>Answering your question:</p>
<blockquote>
<p>Can someone explain me what else is set here with the kubectl exec
command?</p>
</blockquote>
<p>They should result with the same output (assuming that you have typed both commands correctly and execute them on the same container).</p>
<p>Below you will find some useful resources regarding the <code>kubectl exec</code> command:</p>
<ul>
<li><p><a href="https://kubernetes.io/docs/tasks/debug-application-cluster/get-shell-running-container/" rel="nofollow noreferrer">Get a Shell to a Running Container</a></p>
</li>
<li><p><a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#exec" rel="nofollow noreferrer">kubectl-commands#exec docs</a></p>
</li>
<li><p><a href="https://erkanerol.github.io/post/how-kubectl-exec-works/" rel="nofollow noreferrer">How does 'kubectl exec' work?</a></p>
</li>
</ul>
<p><strong>EDIT:</strong></p>
<p>If you wish to learn some more regarding the differences between <code>kubectl exec</code> and <code>SSH</code> I recommend <a href="https://goteleport.com/blog/ssh-vs-kubectl/" rel="nofollow noreferrer">this article</a>. It covers the topics of:</p>
<ul>
<li><p>Authn/z</p>
</li>
<li><p>Shell UX</p>
</li>
<li><p>Non-shell features, and</p>
</li>
<li><p>Performance</p>
</li>
</ul>
|
<p>I am configuring a statefulset deploying 2 Jira DataCenter nodes. The statefulset results in 2 pods. Everything seems fine until the 2 pods try to connect to eachother. They do this with their <strong>short hostname</strong> being <em>jira-0</em> and <em>jira-1</em>.</p>
<p>The jira-1 pod reports <em>UnknownHostException</em> when connecting to jira-0. The hostname can not be resolved.</p>
<p>I read about adding a <strong>headless service</strong> which I didn't have yet. After adding that I can resolve the FQDN but still no luck for the short name.</p>
<p>Then I read this page: <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/" rel="nofollow noreferrer">DNS for Services and Pods</a> and added:</p>
<pre><code> dnsConfig:
searches:
- jira.default.svc.cluster.local
</code></pre>
<p>That solves my issue but I think it shouldn't be necessary to add this?</p>
<p>Some extra info:</p>
<ul>
<li>Cluster on AKS with CoreDNS</li>
<li>Kubernetes v1.19.9</li>
<li>Network plugin: Kubenet</li>
<li>Network policy: none</li>
</ul>
<p>My full yaml file:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: jira
labels:
app: jira
spec:
clusterIP: None
selector:
app: jira
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: jira
spec:
serviceName: jira
replicas: 0
selector:
matchLabels:
app: jira
template:
metadata:
labels:
app: jira
spec:
containers:
- name: jira
image: atlassian/jira-software:8.12.2-jdk11
readinessProbe:
httpGet:
path: /jira/status
port: 8080
initialDelaySeconds: 120
periodSeconds: 10
livenessProbe:
httpGet:
path: /jira/
port: 8080
initialDelaySeconds: 600
periodSeconds: 10
envFrom:
– configMapRef:
name: jira-config
ports:
- containerPort: 8080
dnsConfig:
searches:
- jira.default.svc.cluster.local
</code></pre>
| <blockquote>
<p>That solves my issue but I think it shouldn't be necessary to add this?</p>
</blockquote>
<p>From the <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" rel="nofollow noreferrer">StatefulSet documentation</a>:</p>
<blockquote>
<p>StatefulSets currently require a Headless Service to be responsible for the network identity of the Pods. <strong>You are responsible for creating this Service.</strong></p>
</blockquote>
<blockquote>
<p>The example above will create three Pods named web-0,web-1,web-2. A StatefulSet can use a Headless Service to control the domain of its Pods.</p>
</blockquote>
<p>The pod-identity is will be subdomain to the <em>governing service</em>, eg. in your case it will be e.g:</p>
<pre><code>jira-0.jira.default.svc.cluster.local
jira-1.jira.default.svc.cluster.local
</code></pre>
|
<p>When JVM crashes with <code>OutOfMemoryError</code> there are some options to store a dump:</p>
<pre><code>-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=./java_pid<pid>.hprof
</code></pre>
<p>but what does it happen in kubernetes cluster after crashing? It seems kubernetes will clean up everything related to the pod crushed? How can I save it?</p>
| <p>just mount it as a volume.</p>
<pre><code>volumeMounts:
- name: heap-dumps
mountPath: /dumps
volumes:
- name: heap-dumps
emptyDir: {}
</code></pre>
<p><a href="https://danlebrero.com/2018/11/20/how-to-do-java-jvm-heapdump-in-kubernetes/" rel="nofollow noreferrer">How to do a java heap dump in K8s</a></p>
|
<p>Running a k8 cronjob on an endpoint. Test works like a charm locally and even when I <code>sleep infinity</code> at the end of my entrypoint then curl inside the container. However once the cron kicks off I get some funky error:</p>
<pre><code>[ec2-user@ip-10-122-8-121 device-purge]$ kubectl logs appgate-device-cron-job-1618411080-29lgt -n device-purge
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 52.61.245.214:444
</code></pre>
<p>docker-entrypoint.sh</p>
<pre><code>#! /bin/sh
export api_vs_hd=$API_VS_HD
export controller_ip=$CONTROLLER_IP
export password=$PASSWORD
export uuid=$UUID
export token=$TOKEN
# should be logged in after token export
# Test API call: list users
curl -k -H "Content-Type: application/json" \
-H "$api_vs_hd" \
-H "Authorization: Bearer $token" \
-X GET \
https://$controller_ip:444/admin/license/users
# test
# sleep infinity
</code></pre>
<p>Dockerfile</p>
<pre><code>FROM harbor/privateop9/python38:latest
# Use root user for packages installation
USER root
# Install packages
RUN yum update -y && yum upgrade -y
# Install curl
RUN yum install curl -y \
&& curl --version
# Install zip/unzip/gunzip
RUN yum install zip unzip -y \
&& yum install gzip -y
# Install wget
RUN yum install wget -y
# Install jq
RUN wget -O jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
RUN chmod +x ./jq
RUN cp jq /usr/bin
# Install aws cli
RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
RUN unzip awscliv2.zip
RUN ./aws/install
## set working directory
WORKDIR /home/app
# Add user
RUN groupadd --system user && adduser --system user --no-create-home --gid user
RUN chown -R user:user /home/app && chmod -R 777 /home/app
# Make sure that your shell script file is in the same folder as your dockerfile while running the docker build command as the below command will copy the file to the /home/root/ folder for execution
# COPY . /home/root/
COPY ./docker-entrypoint.sh /home/app
RUN chmod +x docker-entrypoint.sh
# Switch to non-root user
USER user
# Run service
ENTRYPOINT ["/home/app/docker-entrypoint.sh"]
</code></pre>
<p>Cronjob.yaml</p>
<pre><code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: device-cron-job
namespace: device-purge
spec:
#Cron Time is set according to server time, ensure server time zone and set accordingly.
schedule: "*/2 * * * *" # test
jobTemplate:
spec:
template:
spec:
imagePullSecrets:
- name: appgate-cron
containers:
- name: device-cron-pod
image: harbor/privateop9/python38:device-purge
env:
- name: API_VS_HD
value: "Accept:application/vnd.appgate.peer-v13+json"
- name: CONTROLLER_IP
value: "value"
- name: UUID
value: "value"
- name: TOKEN
value: >-
curl -H "Content-Type: application/json" -H "${api_vs_hd}" --request POST
--data "{\"providerName\":\"local\",\"username\":\"admin\",\"password\":\"$password\",\"deviceId\":\"$uuid\"}"
https://$controller_ip:444/admin/login --insecure | jq -r '.token'
- name: PASSWORD
valueFrom:
secretKeyRef:
name: password
key: password
imagePullPolicy: Always
restartPolicy: OnFailure
backoffLimit: 3
</code></pre>
<p>Please help! I am running out of ideas....</p>
| <p>The issue with my post was on the server itself due to some firewall with the IP whitelisting set up on the AWS cloud account. After that problem was addressed by the security team on the account I was able to pass the blocker.</p>
|
<p>I'm using the pre-packaged Kubernetes cluster that comes with docker desktop. I'm on a windows machine, running the Kubernetes on a Ubuntu-18.04 VM using WSL 2. On my Kubernetes cluster I run:</p>
<pre><code>istioctl install --set profile=demo --set values.global.jwtPolicy=third-party-jwt
</code></pre>
<p>But I get the message:</p>
<pre><code>Detected that your cluster does not support third party JWT authentication. Falling back to less secure first party JWT. See https://istio.io/v1.9/docs/ops/best-practices/security/#configure-third-party-service-account-tokens for details.
</code></pre>
<p>After that, it freezes on this until it times out:</p>
<pre><code>Processing resources for Istiod. Waiting for Deployment/istio-system/istiod
</code></pre>
<p>Is there a way of enabling third party JWT in my cluster?</p>
| <p>In the error message that you've received there is a link that points to the documentation on that specific issue:</p>
<ul>
<li><em><a href="https://istio.io/latest/docs/ops/best-practices/security/#configure-third-party-service-account-tokens" rel="nofollow noreferrer">Istio.io: Latest: Docs: Ops: Best practices: Security: Configure third party service account tokens</a></em></li>
</ul>
<p>Citing the official documentation:</p>
<blockquote>
<h3>Configure third party service account tokens</h3>
<p>To authenticate with the Istio control plane, the Istio proxy will use a Service Account token. Kubernetes supports two forms of these tokens:</p>
<p>Third party tokens, which have a scoped audience and expiration.
First party tokens, which have no expiration and are mounted into all pods.
Because the properties of the first party token are less secure, Istio will default to using third party tokens. However, this feature is not enabled on all Kubernetes platforms.</p>
<p>If you are using istioctl to install, support will be automatically detected. This can be done manually as well, and configured by passing <code>--set values.global.jwtPolicy=third-party-jwt</code> or <code>--set values.global.jwtPolicy=first-party-jwt</code>.</p>
<p>To determine if your cluster supports third party tokens, look for the TokenRequest API. If this returns no response, then the feature is not supported:</p>
<p><code>$ kubectl get --raw /api/v1 | jq '.resources[] | select(.name | index("serviceaccounts/token"))'</code></p>
<pre><code>{
"name": "serviceaccounts/token",
"singularName": "",
"namespaced": true,
"group": "authentication.k8s.io",
"version": "v1",
"kind": "TokenRequest",
"verbs": [
"create"
]
}
</code></pre>
<p>While most cloud providers support this feature now, many local development tools and custom installations may not prior to Kubernetes 1.20. To enable this feature, please refer to the <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#service-account-token-volume-projection" rel="nofollow noreferrer">Kubernetes documentation</a>.</p>
</blockquote>
<hr />
<p>I'm not sure if this feature is supported by Kubernetes (<code>1.19.7</code>) created with Docker Desktop but Kubernetes documentation shows a way how you could enable it:</p>
<blockquote>
<h3>Service Account Token Volume Projection</h3>
<p><strong>FEATURE STATE:</strong> Kubernetes v1.20 [stable]</p>
<p><strong>Note:</strong></p>
<p>To enable and use token request projection, you must specify each of the following command line arguments to kube-apiserver:</p>
<pre><code>--service-account-issuer
--service-account-key-file
--service-account-signing-key-file
--api-audiences
</code></pre>
</blockquote>
<p>You can edit your <code>kubeapi-server</code> manifest in a Docker Desktop with Kubernetes in a somewhat hacky way. You can read more about it by following this answer (which I am the author of):</p>
<ul>
<li><em><a href="https://stackoverflow.com/questions/64758012/location-of-kubernetes-config-directory-with-docker-desktop-on-windows/64774052#64774052">Stackoverflow.com: Questions: Location of Kubernetes config directory with Docker Desktop on Windows</a></em></li>
</ul>
<hr />
<h3>Workaround</h3>
<p>As you are using Docker on your host, you could also consider using <code>minikube</code> with its <code>--driver=docker</code>. It supports third party JWT tokens as described in the Istio documentation (it produces the response from the <code>$ kubectl get --raw ...</code> command).</p>
<blockquote>
<p>A side note!</p>
<p>I've tested this on a <code>minikube</code> version <code>1.19.0</code> and Kubernetes version <code>1.20.2</code>.</p>
</blockquote>
|
<p>I'm trying to submit my Pyspark application to a Kubernetes cluster (Minikube) using spark-submit:</p>
<pre><code>./bin/spark-submit \
--master k8s://https://192.168.64.4:8443 \
--deploy-mode cluster \
--packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.0.1 \
--conf spark.kubernetes.container.image='pyspark:dev' \
--conf spark.kubernetes.container.image.pullPolicy='Never' \
local:///main.py
</code></pre>
<p>The application try to reach a Kafka instance deployed inside the cluster, so I specified the jar dependency:</p>
<pre><code>--packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.0.1
</code></pre>
<p>The container image I'm using is based on the one I've built with the utility script. I've packed all my python dependencies that my app need inside it.</p>
<p>The driver correctly deploy and get the Kafka package (I can provide the logs if needed) and launch the executor in a new pod.</p>
<p>But then the executor pod crash:</p>
<pre><code>ERROR Executor: Exception in task 0.0 in stage 1.0 (TID 1)
java.lang.ClassNotFoundException: org.apache.spark.sql.kafka010.KafkaBatchInputPartition
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:68)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1986)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1850)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2160)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1667)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2405)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2329)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2187)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1667)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2405)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2329)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2187)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1667)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:503)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:461)
at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:76)
at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:115)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:407)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
</code></pre>
<p>So I did my investigations on the executor pod and found that the jar is not present (as stated in the stack trace) in the $SPARK_CLASSPATH folder (which is set to ':/opt/spark/jars/*')</p>
<p>Do I need to also get and include the dependency in the spark jars folder when building the docker image? (I thought the '--packages' option would also make the executor retrieve the specified jar)</p>
| <p>Did you start out with the official Dockerfile (kubernetes/dockerfiles/spark/bindings/python/Dockerfile) as described in the <a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html#docker-images" rel="nofollow noreferrer">Docker images section</a> of the documentation?
You also need to specify an upload location on a Hadoop-compatible filesystem and make sure that the specified Ivy home and cache directories have the correct permissions, as described in the <a href="https://spark.apache.org/docs/latest/running-on-kubernetes.html#dependency-management" rel="nofollow noreferrer">Dependency Management section</a>.</p>
<p>Example from the docs:</p>
<pre><code>...
--packages com.amazonaws:aws-java-sdk:1.7.4,org.apache.hadoop:hadoop-aws:2.7.6
--conf spark.kubernetes.file.upload.path=s3a://<s3-bucket>/path
--conf spark.hadoop.fs.s3a.access.key=...
--conf spark.hadoop.fs.s3a.impl=org.apache.hadoop.fs.s3a.S3AFileSystem
--conf spark.hadoop.fs.s3a.fast.upload=true
--conf spark.hadoop.fs.s3a.secret.key=....
--conf spark.driver.extraJavaOptions="-Divy.cache.dir=/tmp -Divy.home=/tmp"
...
</code></pre>
|
<p>I am trying to configure Prometheus using Helm in Kubernetes and I have tried to execute the command as below and the deployment was successful.</p>
<pre><code>$ helm install prometheus prometheus-community/prometheus --namespace prometheus --set
nodeSelector.nodetype=infra
NAME: prometheus
LAST DEPLOYED: Tue Apr 27 22:47:20 2021
NAMESPACE: prometheus
STATUS: deployed
</code></pre>
<p>However, when I try to describe the pods created, I am unable to see the nodeSelector value as "nodetype=infra". Can someone please point me out as to where I am missing out.</p>
<pre><code>$ kubectl get pods -n prometheus
NAME READY STATUS RESTARTS AGE
prometheus-alertmanager-7f86c968db-vln2x 2/2 Running 0 61m
prometheus-kube-state-metrics-6bfcd6f648-6cdbw 1/1 Running 0 61m
prometheus-node-exporter-7q9lh 1/1 Running 0 61m
prometheus-pushgateway-54576f7765-6kjt5 1/1 Running 0 61m
prometheus-server-7c9b8dbfcd-9x48b 2/2 Running 0 61m
$ kubectl describe pod prometheus-alertmanager-7f86c968db-vln2x -n prometheus
Name: prometheus-alertmanager-6bc84b9455-4g9mw
Namespace: prometheus
Priority: 0
..
QoS Class: BestEffort
Node-Selectors: <none> --> This is the field I'm expecting to have "nodetype=infra"
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
</code></pre>
| <p>You need to configure the nodeSelector for each component</p>
<pre class="lang-yaml prettyprint-override"><code>alertmanager:
nodeSelector:
nodetype: infra
nodeExporter:
nodeSelector:
nodetype: infra
server:
nodeSelector:
nodetype: infra
pushgateway:
nodeSelector:
nodetype: infra
</code></pre>
<p>You can fin all the values <a href="https://github.com/prometheus-community/helm-charts/blob/main/charts/prometheus/values.yaml" rel="noreferrer">here</a></p>
|
<p>According to the Kubernetes docs a cluster can have up to 5000 nodes. Imagine I have then node0 with 1CPU, node1 with 2CPU, etc.</p>
<p>Let's say I have a single-core, synchronous process which I want to run instances of. Am I then limited by the smallest node in a heterogeneous cluster of nodes? If not, can I enforce choosing the node largest CPU (which would then limit me to the single node) or smallest CPU (which would then allow seamless and consistent parallel execution) or will Kubernetes do it in the background?</p>
| <blockquote>
<p>Am I then limited by the smallest node in a heterogeneous cluster of nodes? If not, can I enforce choosing the node largest CPU (which would then limit me to the single node) or smallest CPU (which would then allow seamless and consistent parallel execution) or will Kubernetes do it in the background?</p>
</blockquote>
<p>The scheduler does not have insight about what instances you use. So it will schedule the app to any node.</p>
<p>You can use <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/#example-use-cases" rel="nofollow noreferrer">Taints and Tolerations</a> to classify the nodes and then you can declare to what kind of nodes you want your app to run on by setting <em>tolerations</em>. Or alternatively use <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector" rel="nofollow noreferrer">nodeSelector</a> and labels on nodes.</p>
|
<p>We are running Postgres in Kubernetes. Our Prometheus pod monitoring always shows that Postgres fills up the entire pods memory in a shared or cached state.</p>
<pre><code>free -h
total used free shared buff/cache available
Mem: 62G 1.7G 13G 11G 47G 48G
ps -u postgres o pid= | sed 's#.*#/proc/&/smaps#' | sed 's/ //g#/proc/&/smaps#' | \
xargs grep -s ^Pss: | awk '{A+=$2} END{print "PSS: " A}'
PSS: 13220013 kb
ps -u postgres o pid,rss:8,cmd | awk 'NR>1 {A+=$2} {print} END{print "RSS: " A}' | tail -1
RSS: 38794236 kb
</code></pre>
<p>Correct me if I am wrong, but since the memory displayed in <code>top</code> and <code>ps</code>(RSS/RES) is shared memory, this means that Posgres isnt using that memory, its only reserved for when it needs it and other processes can also use that memory. Some <a href="https://www.depesz.com/2012/06/09/how-much-ram-is-postgresql-using/" rel="nofollow noreferrer">articles</a> say that one needs to <code>cat /proc/<PID>/smaps</code> and check the PSS to find the actual memory usage of Postgres.</p>
<p>We recently got OOM errors, but we where unable to pick it up in our monitoring. Due to the fact that our pod memory monitoring is always displaying 90% usage as its only monitoring the RSS/RES memory which is includes the shared/cached memory as well. So we didnt see any increase in RAM when the OOM errors happened and our database went down. The error was caused by a new query we introduced to our backend which used large amounts of memory per query.</p>
<p>We have prometheus-postgres-exporter installed giving us good Postgres metrics, but this didnt show us that we had queries using large amounts memory, but maybe our Grafana graph is missing that graph?</p>
<p>Because we are running Postgres in Kubernetes exporting the PSS memory is a hassle. So it feels like I am missing something.</p>
<p>So how does one monitor the memory usage of Postgres ? How does one pick up on queries using too much memory or pick up on postgres using too much memory due to load?</p>
| <p>I recommend that you disable memory overcommit by setting <code>vm.overcommit_memory = 2</code> in <code>/etc/sysctl.conf</code> and running <code>sysctl -p</code>. Don't forget to set <code>vm.overcommit_ratio</code> appropriately, based on the RAM and swap that you have.</p>
<p>Than should keep the OOM killer at bay.</p>
<p>Then you can examine <code>/proc/meminfo</code> to find if you are getting tight on memory:</p>
<ul>
<li><p><code>CommitLimit</code> shows how much memory the kernel is willing to hand out</p>
</li>
<li><p><code>Committed_AS</code> shows how much memory is allocated by processes</p>
</li>
</ul>
<p>Look at the <a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/filesystems/proc.rst?id=HEAD#n1068" rel="nofollow noreferrer">kernel documentation</a> for details.</p>
|
<p>I have pod with this settings:</p>
<pre><code>Node-Selectors: <none>
Tolerations: node.kubernetes.io/memory-pressure:NoSchedule
node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 60s
role_va
</code></pre>
<p>The pod is scheduled into this node:</p>
<pre><code>Labels: balancer=true
beta.kubernetes.io/arch=amd64
beta.kubernetes.io/os=linux
cpu_avx2=true
cpu_avx512f=true
kubernetes.io/hostname=p20b-sr3-r5-k8s-node4
master=true
worker=true
Annotations: node.alpha.kubernetes.io/ttl=0
volumes.kubernetes.io/controller-managed-attach-detach=true
Taints: <none>
</code></pre>
<p>Please, help me understand why.
If I'm not mistaken the pod with toleration "role_va" must be scheduled <strong>only</strong> to node that has this taint.
In my case the node doesn't have this taint but the pod is scheduled into this node whatever. Why?</p>
| <p>As Malgorzata said, Taints and Tolerations are only useful for the nodes to accept a certain kind of pods. E.g. a node with "blue" taint can only accept pods with "blue" toleration. However, it does not mean that the pod with "blue" toleration would end up only in the node with "blue" taint. The Kube-Scheduler may pick up any other node that does not have a taint (and hence no preference of a pod type).</p>
<p>Below are two possible ways to achieve your requirements.</p>
<ol>
<li><p>Apply the node with a taint and pod with that toleration. And also declare node affinity for the pod, which is a preference of a pod to get schedule on a particular node. These two configurations together would make sure that your pod would get scheduled on the specific node. And the node will only have the pods with a specific toleration.</p>
</li>
<li><p>If you have three nodes, apply "blue" taint on one of them and "red" taint on the rest of the nodes. That will force the pod with "blue" toleration only one choice to go on the node with "blue" taint. Because the other nodes have "red" taint and the pod does not have "red" toleration.</p>
</li>
</ol>
|
<p>I have Kubernetes Cluster where deployed and scaled Jenkins,
below podTemplate yaml file which I run in Jenkins pipeline:</p>
<pre><code>podTemplate(yaml: """
apiVersion: v1
kind: Pod
spec:
containers:
- name: docker
image: docker/compose
command: ['cat']
tty: true
volumeMounts:
- name: dockersock
mountPath: /var/run/docker.sock
volumes:
- name: dockersock
hostPath:
path: /var/run/docker.sock
"""
) {
def image = "image/name"
node(POD_LABEL) {
stage('Build and run Docker image') {
git branch: 'test',
credentialsId: 'github-credentials',
url: 'https://github.com/project/project.git'
container('docker') {
sh "docker-compose up -d --build"
}
}
}
}
</code></pre>
<p>I have got an error:</p>
<pre><code>[Pipeline] sh
+ docker-compose up -d --build
The ENV variable is not set. Defaulting to a blank string.
[Pipeline] }
</code></pre>
<p>Which is best practice to set env vars during the this kind of deployments?</p>
<p><em><strong>Update:</strong></em>
yes, it's working outside of Jenkins,
I have listed env var files in docker compose yaml file:</p>
<pre><code>...
context: ./validator
ports:
- '${VALIDATOR_PROD_ONE_PORT}:${VALIDATOR_PROD_ONE_PORT}'
volumes:
- ./validator/logs_1:/usr/src/app/logs
***env_file: .env.validator.test***
...
</code></pre>
<p>Of course I cat set env var in Jenkins pipeline before executing docker-compose build like this, for example:</p>
<pre><code>container('docker') {
***sh ' echo "someEnvVar=value" > .env.validator.test'***
sh "docker-compose up -d --build"
}
</code></pre>
<p>This way also working, but not beautiful (:</p>
| <p>You should be able to set environment variables on your stage as following:</p>
<pre><code> stage('Build and run Docker image') {
environment {
SOME_ENV_VAR = "SOME_VAL"
}
git branch: 'test',
credentialsId: 'github-credentials',
url: 'https://github.com/project/project.git'
container('docker') {
sh "docker-compose up -d --build"
}
}
</code></pre>
<p>This would essentially set shell Environment variables, which should precede over those in .env file.</p>
|
<p>I'm using helm3.
My kubernetes deployment get crashed on 43 line of code below.</p>
<p>Error in console: error converting YAML to JSON: mapping values are not allowed in this context</p>
<p>yaml lint says this:
<strong>(): found unexpected ':' while scanning a plain scalar at line 43 column 19</strong></p>
<p>Whats wrong with that line?</p>
<p>wrong one:</p>
<pre><code>- image: {{ printf "%s/%s:%s" .Values.dockerRegistry .Values.dockerImage .Values.version }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ template "deploy_name" . }}
namespace: {{ .Release.Namespace }}
spec:
replicas: {{ .Values.replicas.min }}
revisionHistoryLimit: 3
selector:
matchLabels:
app: {{ .Release.Name }}
template:
metadata:
labels:
app: {{ .Release.Name }}
team: {{ .Values.meta.team }}
env: {{ .Values.env }}
version: {{ .Values.version }}
revision: {{ .Release.Revision | quote }}
json_logs: "true"
commit_hash: {{ .Values.commitHash }}
annotations:
prometheus.io/port: {{ .Values.ports.application | quote }}
prometheus.io/path: {{ .Values.prometheus.path | quote }}
prometheus.io/scrape: {{ .Values.prometheus.scrape | quote }}
prometheus.io/scheme: {{ .Values.prometheus.scheme | quote }}
host/url: {{ .Values.url | quote }}
host.net/owner: {{ .Values.meta.owner | quote }}
host.net/system: {{ .Values.meta.team | quote }}
sidecar.istio.io/rewriteAppHTTPProbers: "true"
spec:
imagePullSecrets:
- name: gitlab
hostAliases:
- ip: 0.0.0.0
hostnames:
- host
- host
- ip: 0.0.0.0
hostnames:
- host
containers:
- image: {{ printf "%s/%s:%s" .Values.dockerRegistry .Values.dockerImage .Values.version }}
imagePullPolicy: Always
name: website
ports:
- containerPort: {{ .Values.ports.application }}
envFrom:
- configMapRef:
name: {{ template "config_map_name" . }}
- secretRef:
name: {{ template "secret_name" . }}
resources:
limits:
cpu: 2
memory: 4Gi
requests:
cpu: 350m
memory: 2Gi
livenessProbe:
httpGet:
path: /healthz
port: {{ .Values.ports.application }}
initialDelaySeconds: 20
periodSeconds: 3
failureThreshold: 10
readinessProbe:
httpGet:
path: /readyz
port: {{ .Values.ports.application }}
initialDelaySeconds: 20
periodSeconds: 3
</code></pre>
| <p>so my solution is:</p>
<pre><code>- image: '{{.Values.dockerRegistry}}/{{.Values.dockerImage}}:{{.Values.version}}'
</code></pre>
<p>The problem was about printf function and colon symbol within</p>
<pre><code>"%s/%s:%s"
</code></pre>
|
<p>I've tried to change the default proxy_timeout(600s) to 3600s for tcp services in k8s maintained nginx-ingress.But its not working.</p>
<p>I have exec the nginx-controller pods and got the following in nginx.conf.</p>
<pre><code># TCP services
server {
preread_by_lua_block {
ngx.var.proxy_upstream_name="tcp-test-test-db-test-lb-dev-7687";
}
listen 7687;
proxy_timeout 600s;
proxy_pass upstream_balancer;
}
</code></pre>
<p>i have used following configmap and found not working.I'm getting still 600s timeout.</p>
<pre><code>apiVersion: v1
kind: ConfigMap
metadata:
name: tcp-services
namespace: ingress-nginx
annotations:
ingress.kubernetes.io/proxyTimeout: 3600s
ingress.kubernetes.io/proxy-stream-timeout: 3600s
ingress.kubernetes.io/proxy-connect-timeout: 3600s
ingress.kubernetes.io/proxy-read-timeout: 3600s
ingress.kubernetes.io/proxy-send-timeout: 3600s
ingress.kubernetes.io/proxy_timeout: 3600s
data:
7687: "test-test-db/test-lb-dev:7687"
8687: "test-test-db/test-lb-test:8687"
</code></pre>
<p>Anyone please help me to short this issue out.</p>
| <p>Annotations does not work in tcp-services for updating <code>proxy_timeout</code> parameter in nginx.
You need to update the configmap <code>ingress-nginx-controller</code> and add the <code>proxy-stream-timeout: "3600s"</code> under <code>data</code>. (A sample below)</p>
<pre><code>apiVersion: v1
kind: ConfigMap
metadata:
name: ingress-nginx-controller
namespace: ingress-nginx
labels:
app.kubernetes.io/name: ingress-nginx
app.kubernetes.io/part-of: ingress-nginx
data:
proxy-connect-timeout: "10"
proxy-read-timeout: "120"
proxy-send-timeout: "120"
proxy-stream-timeout: "3600s"
</code></pre>
|
<p>I have deployed ECK (using helm) on my k8s cluster and i am attempting to install elasticsearch following the docs. <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html" rel="noreferrer">https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html</a></p>
<p>I have externally exposed service/elasticsearch-prod-es-http so that i can connect to it from outside of my k8s cluster. However as you can see when i try to connect to it either from curl or the browser i receive an error "502 Bad Gateway" error.</p>
<pre><code>curl elasticsearch.dev.acme.com
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
</body>
</html>
</code></pre>
<p>Upon checking the pod (elasticsearch-prod-es-default-0) i can see the following message repeated.</p>
<blockquote>
<p>{"type": "server", "timestamp": "2021-04-27T13:12:20,048Z", "level": "WARN", "component": "o.e.x.s.t.n.SecurityNetty4HttpServerTransport", "cluster.name": "elasticsearch-prod", "node.name": "elasticsearch-prod-es-default-0", "message": "received plaintext http traffic on an https channel, closing connection Netty4HttpChannel{localAddress=/10.0.5.81:9200, remoteAddress=/10.0.3.50:46380}", "cluster.uuid": "t0mRfv7kREGQhXW9DVM3Vw", "node.id": "nCyAItDmSqGZRa3lApsC6g" }</p>
</blockquote>
<p><strong>Can you help me understand why this is occuring and how to fix it?</strong></p>
<p>I suspect it has something to do with my TLS configuration because when i disable TLS, im able to connect to it externally without issues. However in a production environment i think keeping TLS enabled is important?</p>
<p>FYI i am able to port-forward the service and connect to it with curl using the -k flag.</p>
<p><strong>What i have tried</strong></p>
<ol>
<li>I have tried adding my domain to the section as described here <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-http-settings-tls-sans.html#k8s-elasticsearch-http-service-san" rel="noreferrer">https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-http-settings-tls-sans.html#k8s-elasticsearch-http-service-san</a></li>
<li>I have tried using openssl to generate a self signed certificate but that did not work. Trying to connect locally returns the following error message.</li>
</ol>
<blockquote>
<p>curl -u "elastic:$PASSWORD" "https://localhost:9200"
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: <a href="https://curl.haxx.se/docs/sslcerts.html" rel="noreferrer">https://curl.haxx.se/docs/sslcerts.html</a>
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.</p>
</blockquote>
<ol start="3">
<li>I have tried generating a certificate using the tool <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.9/configuring-tls.html#tls-transport" rel="noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/7.9/configuring-tls.html#tls-transport</a></li>
</ol>
<blockquote>
<p>bin/elasticsearch-certutil ca
bin/elasticsearch-certutil cert --ca elastic-stack-ca.12 --pem</p>
</blockquote>
<p>Then using the .crt and .key generated i created a kubectl secret <code>elastic-tls-cert</code>. But again curling localhost without -k gave the following error:</p>
<blockquote>
<p>curl --cacert cacert.pem -u "elastic:$PASSWORD" -XGET "https://localhost:9200"
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: <a href="https://curl.haxx.se/docs/sslcerts.html" rel="noreferrer">https://curl.haxx.se/docs/sslcerts.html</a>
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.</p>
</blockquote>
<p><strong>elasticsearch.yml</strong></p>
<pre><code># This sample sets up an Elasticsearch cluster with 3 nodes.
apiVersion: elasticsearch.k8s.elastic.co/v1
kind: Elasticsearch
metadata:
name: elasticsearch-prod
namespace: elastic-system
spec:
version: 7.12.0
nodeSets:
- name: default
config:
# most Elasticsearch configuration parameters are possible to set, e.g: node.attr.attr_name: attr_value
node.roles: ["master", "data", "ingest", "ml"]
# this allows ES to run on nodes even if their vm.max_map_count has not been increased, at a performance cost
node.store.allow_mmap: false
xpack.security.enabled: true
podTemplate:
metadata:
labels:
# additional labels for pods
foo: bar
spec:
nodeSelector:
acme/node-type: ops
# this changes the kernel setting on the node to allow ES to use mmap
# if you uncomment this init container you will likely also want to remove the
# "node.store.allow_mmap: false" setting above
# initContainers:
# - name: sysctl
# securityContext:
# privileged: true
# command: ['sh', '-c', 'sysctl -w vm.max_map_count=262144']
###
# uncomment the line below if you are using a service mesh such as linkerd2 that uses service account tokens for pod identification.
# automountServiceAccountToken: true
containers:
- name: elasticsearch
# specify resource limits and requests
resources:
limits:
memory: 4Gi
cpu: 1
env:
- name: ES_JAVA_OPTS
value: "-Xms2g -Xmx2g"
count: 3
# # request 2Gi of persistent data storage for pods in this topology element
volumeClaimTemplates:
- metadata:
name: elasticsearch-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 250Gi
storageClassName: elasticsearch
# # inject secure settings into Elasticsearch nodes from k8s secrets references
# secureSettings:
# - secretName: ref-to-secret
# - secretName: another-ref-to-secret
# # expose only a subset of the secret keys (optional)
# entries:
# - key: value1
# path: newkey # project a key to a specific path (optional)
http:
service:
spec:
# expose this cluster Service with a LoadBalancer
type: NodePort
# tls:
# selfSignedCertificate:
# add a list of SANs into the self-signed HTTP certificate
subjectAltNames:
# - ip: 192.168.1.2
# - ip: 192.168.1.3
# - dns: elasticsearch.dev.acme.com
# - dns: localhost
# certificate:
# # provide your own certificate
# secretName: elastic-tls-cert
</code></pre>
<p><strong>kubectl version</strong></p>
<pre><code>Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.4", GitCommit:"e87da0bd6e03ec3fea7933c4b5263d151aafd07c", GitTreeState:"clean", BuildDate:"2021-02-18T16:12:00Z", GoVersion:"go1.15.8", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"19+", GitVersion:"v1.19.6-eks-49a6c0", GitCommit:"49a6c0bf091506e7bafcdb1b142351b69363355a", GitTreeState:"clean", BuildDate:"2020-12-23T22:10:21Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
</code></pre>
<p><strong>helm list</strong></p>
<pre><code> NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION
elastic-operator elastic-system 1 2021-04-26 11:18:02.286692269 +0100 BST deployed eck-operator-1.5.0 1.5.0
</code></pre>
<p><strong>resources</strong></p>
<pre><code>pod/elastic-operator-0 1/1 Running 0 4h58m 10.0.5.142 ip-10-0-5-71.us-east-2.compute.internal <none> <none>
pod/elasticsearch-prod-es-default-0 1/1 Running 0 9m5s 10.0.5.81 ip-10-0-5-71.us-east-2.compute.internal <none> <none>
pod/elasticsearch-prod-es-default-1 1/1 Running 0 9m5s 10.0.1.128 ip-10-0-1-207.us-east-2.compute.internal <none> <none>
pod/elasticsearch-prod-es-default-2 1/1 Running 0 9m5s 10.0.5.60 ip-10-0-5-71.us-east-2.compute.internal <none> <none>
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
service/elastic-operator-webhook ClusterIP 172.20.218.208 <none> 443/TCP 26h app.kubernetes.io/instance=elastic-operator,app.kubernetes.io/name=elastic-operator
service/elasticsearch-prod-es-default ClusterIP None <none> 9200/TCP 9m5s common.k8s.elastic.co/type=elasticsearch,elasticsearch.k8s.elastic.co/cluster-name=elasticsearch-prod,elasticsearch.k8s.elastic.co/statefulset-name=elasticsearch-prod-es-default
service/elasticsearch-prod-es-http NodePort 172.20.229.173 <none> 9200:30604/TCP 9m6s common.k8s.elastic.co/type=elasticsearch,elasticsearch.k8s.elastic.co/cluster-name=elasticsearch-prod
service/elasticsearch-prod-es-transport ClusterIP None <none> 9300/TCP 9m6s common.k8s.elastic.co/type=elasticsearch,elasticsearch.k8s.elastic.co/cluster-name=elasticsearch-prod
</code></pre>
<p><strong>aws alb ingress controller</strong></p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: elastic-ingress
namespace: elastic-system
annotations:
kubernetes.io/ingress.class: alb
alb.ingress.kubernetes.io/group.name: "<redacted>"
alb.ingress.kubernetes.io/scheme: internet-facing
alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80,"HTTPS": 443}]'
alb.ingress.kubernetes.io/certificate-arn: <redacted>
alb.ingress.kubernetes.io/tags: Environment=prod,Team=dev
alb.ingress.kubernetes.io/healthcheck-path: /health
alb.ingress.kubernetes.io/healthcheck-interval-seconds: '300'
alb.ingress.kubernetes.io/load-balancer-attributes: access_logs.s3.enabled=true,access_logs.s3.bucket=acme-aws-ingress-logs,access_logs.s3.prefix=dev-ingress
spec:
rules:
- host: elasticsearch.dev.acme.com
http:
paths:
- path: /*
pathType: Prefix
backend:
service:
name: elasticsearch-prod-es-http
port:
number: 9200
# - host: kibana.dev.acme.com
# http:
# paths:
# - path: /*
# pathType: Prefix
# backend:
# service:
# name: kibana-prod-kb-http
# port:
# number: 5601
</code></pre>
| <p>If anyone comes across this problem in the future, make sure your ingress is properly configured. The error message suggests that its a misconfiguration with the ingress.</p>
<pre><code>received plaintext http traffic on an https channel, closing connection
</code></pre>
<p>In my case i am using <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/" rel="nofollow noreferrer">aws-load-balancer-controller</a>. I had to attach a annotation to my ingress that forces the connection to be HTTPS rather than HTTP.</p>
<pre><code>alb.ingress.kubernetes.io/backend-protocol: "HTTPS"
</code></pre>
<p>For my case this problem was fixed by setting the above annotation to my ingress file and it has nothing to do with setting up a custom/private TLS certificate.</p>
|
<p>How can I use Mike Farah's YQ v4 to update a field that has special characters.</p>
<p>e.g. manipulating below:</p>
<pre><code> containers:
- name: flyway
image: xx.dkr.ecr.eu-west-1.amazonaws.com/testimage:60
</code></pre>
<p>Errors for attempts:</p>
<pre><code>$ yq e ".spec.template.spec.containers[0].image=xx.dkr.ecr.eu-west-1.amazonaws.com/testimage:61" flyway.yaml
Error: Bad expression, please check expression syntax
$ yq e ".spec.template.spec.containers[0].image=xx\.dkr\.ecr\.eu-west-1\.amazonaws\.com\/testimage:61" flyway.yaml
Error: Parsing expression: Lexer error: could not match text starting at 1:53 failing at 1:54.
unmatched text: "\\"
#########
$ echo $image
xx.dkr.ecr.eu-west-1.amazonaws.com/testimage:61
$ yq e ".spec.template.spec.containers[0].image=$image" flyway.yaml
Error: Bad expression, please check expression syntax
</code></pre>
<p>Didnt find any documents explaining any escape characters for special character.</p>
| <p>Found this documentation:
<a href="https://mikefarah.gitbook.io/yq/operators/env-variable-operators" rel="nofollow noreferrer">https://mikefarah.gitbook.io/yq/operators/env-variable-operators</a></p>
<p>This worked for me:</p>
<pre><code>$ echo $image
xx.dkr.ecr.eu-west-1.amazonaws.com/testimage:61
$ myenv=$image yq e '.spec.template.spec.containers[0].image=env(myenv)' flyway.yaml
<<removed contents for brevity >>
spec:
containers:
- name: flyway
image: xx.dkr.ecr.eu-west-1.amazonaws.com/testimage:61
</code></pre>
|
<p>I wanna run a microservice which use DB. DB need to deploy in the same kubernetes cluster as well using PVC/PV. What is the kubernetes service name/command to use to implement such logic:</p>
<ol>
<li>Deploy the DB instance</li>
<li>If 1 is successful, then deploy the microservice, else return to 1 and try (if 100 times fail - then stop and alarm)</li>
<li>If 2 is successful, use work with it, autoscale if needed (autoscale kubernetes option)</li>
</ol>
<p>I concern mostly about 1-2: the service cannot work without the DB, but at the same time need to be in different pods ( or am I wrong and it's better to put 2 containers: DB and service at the same pod?)</p>
| <p>I would say you should add <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#init-containers-in-use" rel="nofollow noreferrer">initContainer</a> to your microservice, which would search for the DB service, and whenever it's gonna be ready, then the microservice will be started.</p>
<p>e.g.</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox:1.28
command: ['sh', '-c', 'echo The app is running! && sleep 3600']
initContainers:
- name: init-mydb
image: busybox:1.28
command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"]
</code></pre>
<p>As for the command simply use the <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#apply" rel="nofollow noreferrer">kubectl apply</a> with your yamls (with initContainer configured in your application).</p>
<p>If you want to do that in more automative way you can think about using <a href="https://fluxcd.io/" rel="nofollow noreferrer">fluxCD</a>/<a href="https://argoproj.github.io/argo-cd/" rel="nofollow noreferrer">argoCD</a>.</p>
<hr />
<p>As for the question from comments, <code>containers that run before the main container runs and the main container must be in the same pod?</code></p>
<p>Yes, they have to be in the same pod. As the init container is going to work unless, f.e. the database service will be avaliable, then the main container is gonna start. There is great example with that in above initContainer documentation.</p>
|
<p>I can't figure out whats wrong with my role binding. I keep getting this error while trying to get metrics for my pod.</p>
<p><code>"pods.metrics.k8s.io "my-pod-name" is forbidden: User "system:serviceaccount:default:default" cannot get resource "pods" in API group "metrics.k8s.io" in the namespace "default""</code></p>
<p>Here is the Cluster role yaml file</p>
<pre><code>kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: ["", "metrics.k8s.io"] # "" indicates the core API group
resources: ["pods"]
verbs: ["get", "watch", "list"]
</code></pre>
<p>Then I ran this command</p>
<pre><code>kubectl create clusterrolebinding pod-reader \
--clusterrole=pod-reader \
--serviceaccount=default:default
</code></pre>
| <p>ClusterRole & ClusterRolebinding are non-namespaced resources. So, remove the namespace line from your YAML file.</p>
<p>Alternatively, use Role & RoleBinding if you want to scope to a namespace.</p>
|
<p>I try to deploy wordpress/mysql in kubernetes.
I want mysql and wordpress to use different volumes. I'm trying to write nfs for wordpress and hostpath for mysql.</p>
<p>But wordpress and mysql are not connected. I don't know why. I'd appreciate your help.</p>
<p>here's my code:
Mysql.yaml</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: mysql
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:5.7
ports:
- containerPort: 3306
protocol: TCP
env:
- name: MYSQL_ROOT_PASSWORD
value: qwer1234
volumeMounts:
- name: mysql-volume
mountPath: /var/lib/mysql
volumes:
- name: mysql-volume
persistentVolumeClaim:
claimName: mysql-pvc
---
apiVersion: v1
kind: Service
metadata:
name: mysql-svc
labels:
app: mysql
spec:
type: ClusterIP
selector:
app: mysql
ports:
- protocol: TCP
port: 3306
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
volumeName: mysql-pv
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: mysql-pv
spec:
capacity:
storage: 5Gi
accessModes:
- ReadWriteOnce
hostPath:
path: /vol/mysql
</code></pre>
<hr />
<p>wordpress.yaml</p>
<pre><code>apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: wordpress
labels:
app: wordpress
spec:
replicas: 2
selector:
matchLabels:
app: wordpress
template:
metadata:
labels:
app: wordpress
spec:
containers:
- image: wordpress
name: wordpress
env:
- name: WORDPRESS_DB_HOST
value: mysql:3306
- name: WORDPRESS_DB_PASSWORD
value: P@ssw0rd
volumeMounts:
- mountPath: /nfs-volume/html
name: wordpress-pv
ports:
- protocol: TCP
containerPort: 80
volumes:
- name: wordpress-pv
persistentVolumeClaim:
claimName: wordpress-pvc
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: wordpress-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 5Gi
volumeName: wordpress-pv
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: wordpress-pv
spec:
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
persistentVolumeReclaimPolicy: Retain
nfs:
server: 192.168.201.11
path: /nfs-volume
---
apiVersion: v1
kind: Service
metadata:
name: wordpress-svc
labels:
app: wordpress
spec:
type: LoadBalancer
selector:
app: wordpress
ports:
- protocol: TCP
port: 80
</code></pre>
| <p>you have provided the port number at last in environment variable</p>
<p>please try with out it</p>
<pre><code>env:
- name: WORDPRESS_DB_HOST
value: mysql:3306
</code></pre>
<p>instead use this</p>
<pre><code>env:
- name: WORDPRESS_DB_HOST
value: MySQL
</code></pre>
<p>you can check the example at : <a href="https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/" rel="nofollow noreferrer">https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/</a></p>
<p>if you read the documentation of Docker image they are also providing the host name without the port as value.</p>
<p>also in Wordpress environment you have to pass the MySQL password which you are passing wrong</p>
<pre><code>- name: WORDPRESS_DB_PASSWORD
value: P@ssw0rd
</code></pre>
<p>instead it should be</p>
<pre><code>- name: WORDPRESS_DB_PASSWORD
value: qwer1234
</code></pre>
|
<p><strong>Context:</strong>
I am using Linux and Windows nodes in a Kubernetes cluster. Depending on the OS where a pod is deployed, I need to use a specific image.</p>
<p><strong>Question:</strong>
Is there a way to express this in a Kubernetes yaml files: "if this label exist on the pod you are deploying, then use this image. Otherwise, use this other image.".</p>
<p><strong>Other options considered:</strong></p>
<ul>
<li>Have two copies of the same yaml but each configured with a OS-specific image with a nodeSelector in each yaml targeting either Linux or Windows nodes. This is not ideal as we need to keep both yaml files in sync if we need to change something in one.</li>
<li>Helm charts. I guess that would solve the issue of having to maintain two similar yaml files by using templates. But still, it seems overkill for what I need if there is an easy way to do it in yaml.</li>
</ul>
| <p>The proper way to do this is to build "multi-arch" images, e.g. so that your container image contains binaries for multiple architectures. See e.g. <a href="https://cloud.google.com/kubernetes-engine/docs/tutorials/building-windows-multi-arch-images" rel="nofollow noreferrer">Building Windows Server multi-arch images</a> and <a href="https://www.docker.com/blog/multi-arch-build-and-images-the-simple-way/" rel="nofollow noreferrer">Docker: Multi-arch build and images, the simple way</a> - but it still seem to be an "experimental feature". A drawback with this is that the images will end up to be bigger, this is not so welcome if you want good elasticity (e.g. be able to quickly scale up with more pods) - this is especially true for windows images.</p>
<p>Alternatively, you need to use a separate <code>Deployment</code> for each architecture and use different <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/" rel="nofollow noreferrer">Taints and Tolerations</a> on the nodes and the pods.</p>
<p>You can keep this relatively clean by using <a href="https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/" rel="nofollow noreferrer">kubectl kustomize</a> and only override a small part of the manifests.</p>
|
<p>I am abit confused on the kubernetes nginx virtual subroute. <a href="https://docs.nginx.com/nginx-ingress-controller/configuration/virtualserver-and-virtualserverroute-resources/#virtualserverroute-subroute" rel="nofollow noreferrer">https://docs.nginx.com/nginx-ingress-controller/configuration/virtualserver-and-virtualserverroute-resources/#virtualserverroute-subroute</a></p>
<blockquote>
<p>"In the case of a prefix, the path must start with the same path as the path of the route of the VirtualServer that references this resource"</p>
</blockquote>
<pre><code>path: /coffee
action:
path: coffee
</code></pre>
<p>will the /coffee be passed to the app?</p>
<p>because when I try to deploy the virtualserver with the route it doesn't work (exmaple below)</p>
<pre><code>path: /one
action:
path: hellok8s
</code></pre>
<p>however, this route that I am using previously is working</p>
<pre><code>path: /
action:
path: hellok8s
</code></pre>
<p>So taking for example, if I have an app-1 and app-2... Should I differentiate them through the host or through a sub-path?</p>
<ul>
<li>app-1: helloworld.test.com</li>
<li>app-2: helloworld2.test.com</li>
</ul>
<p>or is there way that I can differentiate them through path like below?</p>
<ul>
<li>app-1: helloworld.test.com/appone</li>
<li>app-2: helloworld.test.com/apptwo</li>
</ul>
<p>--- edit</p>
<pre><code>apiVersion: k8s.nginx.org/v1
kind: VirtualServer
metadata:
name: hellok8s-app-vs
spec:
host: helloworld.moonshot.com
tls:
secret: nginx-tls-secret
# basedOn: scheme
redirect:
enable: true
code: 301
upstream:
- name: hellok8s
service: hellok8s-service
port: 8080
routes:
- path: /one
action:
proxy:
upstream: hellok8s
rewritePath: /
</code></pre>
| <p>So the path is the URL which will be exposed by the Nginx to world outside. What happens to that path internally depends on the action's sub attributes, some examples:</p>
<p>Here the <code>/coffee</code> is what end user sees but the request is sent to root of coffee service. So if the coffee would be a service in K8S running at 8080, the request will land at <code>coffee:8080</code></p>
<pre><code>path: /coffee
action:
pass: coffee
</code></pre>
<p>But there are more <a href="https://docs.nginx.com/nginx-ingress-controller/configuration/virtualserver-and-virtualserverroute-resources/#action" rel="nofollow noreferrer">actions</a>. And let's say you use the <a href="https://docs.nginx.com/nginx-ingress-controller/configuration/virtualserver-and-virtualserverroute-resources/#action-proxy" rel="nofollow noreferrer"><code>action.proxy</code></a> then you can define at a lot more granular level what should happen with path. So in below example, we are forwarding to the <code>coffee</code> service but the request path is being re-written to <code>filtercoffee</code></p>
<pre><code>proxy:
upstream: coffee
rewritePath: /filtercoffee
</code></pre>
<p>You can also use redirect, return in action's pass directive, but you must <a href="https://docs.nginx.com/nginx-ingress-controller/configuration/virtualserver-and-virtualserverroute-resources/#action" rel="nofollow noreferrer">use one of the four listed here</a></p>
|
<p>I want to get the list of the nodes and their status in Kubernetes via the go client. I am using
<code>clientset.CoreV1().Nodes().List(metav1.ListOptions{})</code>
and I am able to get the list of nodes and some information such as node lables but I cannot find the <code>status.phase</code> there (for pods that give me the status).</p>
<p>I searched and I found <code>NodeCondition</code> (<a href="https://github.com/kubernetes/api/blob/9b64426eca51a74faa7cc9bd732a533d339c69c2/core/v1/types.go#L4911" rel="nofollow noreferrer">https://github.com/kubernetes/api/blob/9b64426eca51a74faa7cc9bd732a533d339c69c2/core/v1/types.go#L4911</a>) but I cannot find any documentation regarding how to use it and I couldn't make it work myself. Can someone please let me know how I can get the status of Nodes via the client?</p>
| <p>You can access it through <code>node.Status.Condition</code></p>
<pre><code>nodes, _ := client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
for _, node := range nodes.Items {
fmt.Printf("%s\n", node.Name)
for _, condition := range node.Status.Conditions {
fmt.Printf("\t%s: %s\n", condition.Type, condition.Status)
}
}
</code></pre>
<p>Prints:</p>
<pre><code>dev-master-01
NetworkUnavailable: False
MemoryPressure: False
DiskPressure: False
PIDPressure: False
Ready: True
dev-master-02
NetworkUnavailable: False
MemoryPressure: False
DiskPressure: False
PIDPressure: False
Ready: True
dev-master-03
NetworkUnavailable: False
MemoryPressure: False
DiskPressure: False
PIDPressure: False
Ready: True
</code></pre>
|
<p>I am trying to setup an <a href="https://kubernetes.github.io/ingress-nginx/" rel="nofollow noreferrer">nginx kubernetes ingress</a>. I am able to serve http and websockets content on different routes at the moment.</p>
<p>However I am not able to add GRPC routes on the same host. Adding this annotation <code>nginx.ingress.kubernetes.io/backend-protocol: "GRPC"</code> breaks the existing routes.</p>
<p>My java GRPC client exits with
<code>Caused by: io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2Exception: First received frame was not SETTINGS. Hex dump for first 5 bytes: 485454502f</code>
According to <a href="https://github.com/grpc/grpc-java/issues/2905" rel="nofollow noreferrer">https://github.com/grpc/grpc-java/issues/2905</a> this means the request is seen as HTTP</p>
<p>Is there a way to have http/websocket/grpc routes on the same host using the nginx kubernetes ingress? Alternatively, is there another ingress with which this would work?</p>
| <p>As you want the annotation <code>nginx.ingress.kubernetes.io/backend-protocol: "GRPC"</code> to apply only on certain routes of your host, you could declare two Ingress definitions. The first one for all HTTP routes, the second one for GRPC routes.</p>
<p>The Nginx Ingress Controller will pick all the Ingress definitions (with the expected <code>IngressClass</code>) and will use them to compose the <code>nginx.conf</code>. This behaviour is perfect to have the possibility of having paths which requires different tunings in the annotations, like rewrite targets or, in your case, different backend protocols.</p>
<p>In particular, from the Nginx Controller documentation:</p>
<blockquote>
<p>Multiple Ingresses can define different annotations. These definitions
are not shared between Ingresses.</p>
</blockquote>
<p>You can check all the steps which are used to build the <code>nginx.conf</code> in the docs: <a href="https://kubernetes.github.io/ingress-nginx/how-it-works/#building-the-nginx-model" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/how-it-works/#building-the-nginx-model</a></p>
|
<p>I have an application deployed on Kubernetes (Google cloud). For the deployment to function, it needs to return a 200 status response to "/healthz" and "/". I have this set up on my Express server as a route returning a response like so:</p>
<pre><code>app.use('/healthz', ((_req, res) => {
logGeneral.info("Health Status check called.");
res.sendStatus(200);
}));
</code></pre>
<p>But I don't know how to do the same for my frontend which is running on Next.js / React. Commands such as res.send are not supported.</p>
<p>Anyone know?</p>
<p>Thanks.</p>
| <p>Using an API route is the correct answer. Create a new file in /pages/api called healthcheck.js with this content:</p>
<pre><code>export default function handler(req, res) {
res.status(200).json({ "status": "ok" })
}
</code></pre>
<p>The endpoint will be at (hostname)/api/healthcheck</p>
|
<p>Trying to add insecure registry to containerd config as below:</p>
<pre><code>[plugins."io.containerd.grpc.v1.cri".cni]
bin_dir = "/opt/cni/bin"
conf_dir = "/etc/cni/net.d"
max_conf_num = 1
conf_template = ""
[plugins."io.containerd.grpc.v1.cri".registry]
[plugins."io.containerd.grpc.v1.cri".registry.mirrors]
[plugins."io.containerd.grpc.v1.cri".registry.mirrors."docker.io"]
endpoint = ["https://registry-1.docker.io"]
[plugin."io.containerd.grpc.v1.cri".registry.mirrors."test.http-registry.io"]
endpoint = ["http://v048011.dom600.lab:5000"]
</code></pre>
<p>Even after adding it to <code>config.toml</code>, when pulling image from the insecure registry, it fails:</p>
<pre><code>sudo ctr image pull v048011.dom600.lab:5000:5000/myjenkins:latest
ctr: failed to resolve reference "v048011.dom600.lab:5000/myjenkins:latest": failed to do request: Head https://v048011.dom600.lab:5000:5000/v2/myjenkins/manifests/latest: http: server gave HTTP response to HTTPS client
</code></pre>
<p>In <code>docker</code> we could just add the <code>insecure registry</code> to <code>daemon.json</code> file and docker would pull images from it, how can i achieve the same in <code>containerd</code> ?
Replacing docker as runtime in k8s cluster.</p>
| <p><code>ctr</code> <strong>does not</strong> read the <code>/etc/containerd/config.toml</code> config file, this config is used by cri, which means <code>kubectl</code> or <code>crictl</code> would use it.</p>
<p>The error log <code>http: server gave HTTP response to HTTPS client</code>, shows that the registry is using http, but <code>ctr</code> is trying to connect it using https. So if you want to pull the image from http, you should add the param <code>--plain-http</code> with <code>ctr</code> like this:</p>
<pre><code>$ ctr i pull --plain-http <image>
</code></pre>
<p>The registry config doc is <a href="https://github.com/containerd/containerd/blob/master/docs/cri/registry.md" rel="noreferrer">here</a>.</p>
<p>You should be able to pull the image with <code>crictl</code>, remember to restart containerd.</p>
<pre><code>$ sudo crictl -r /run/containerd/containerd.sock pull <image>
# or config runntime once for all
$ sudo crictl config runtime-endpoint /run/containerd/containerd.sock
$ sudo crictl pull <image>
</code></pre>
<p>Config example:</p>
<pre><code># /etc/containerd/config.toml
# change <IP>:5000 to your registry url
[plugins."io.containerd.grpc.v1.cri".registry]
[plugins."io.containerd.grpc.v1.cri".registry.mirrors]
[plugins."io.containerd.grpc.v1.cri".registry.mirrors."<IP>:5000"]
endpoint = ["http://<IP>:5000"]
[plugins."io.containerd.grpc.v1.cri".registry.configs]
[plugins."io.containerd.grpc.v1.cri".registry.configs."<IP>:5000".tls]
insecure_skip_verify = true
</code></pre>
<p>Restart the service after configuration modification.</p>
<pre class="lang-bash prettyprint-override"><code>$ sudo systemctl restart containerd
</code></pre>
|
<p>I am trying to add the two flags below to apiserver in the /etc/kubernetes/manifests/kube-apiserver.yaml file:</p>
<pre><code>spec:
containers:
- command:
- kube-apiserver
- --enable-admission-plugins=NodeRestriction,PodNodeSelector
- --admission-control-config-file=/vagrant/admission-control.yaml
[...]
</code></pre>
<p>I am not mounting a volume or mount point for the /vagrant/admission-control.yaml file. It is completely accessible from the node master, since it is shared by the VM created by vagrant:</p>
<pre><code>vagrant@master-1:~$ cat /vagrant/admission-control.yaml
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodNodeSelector
path: /vagrant/podnodeselector.yaml
vagrant@master-1:~$
</code></pre>
<p>Kubernetes version:</p>
<pre><code>vagrant@master-1:~$ kubectl version
Client Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.0", GitCommit:"cb303e613a121a29364f75cc67d3d580833a7479", GitTreeState:"clean", BuildDate:"2021-04-08T16:31:21Z", GoVersion:"go1.16.1", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.0", GitCommit:"cb303e613a121a29364f75cc67d3d580833a7479", GitTreeState:"clean", BuildDate:"2021-04-08T16:25:06Z", GoVersion:"go1.16.1", Compiler:"gc", Platform:"linux/amd64"}
</code></pre>
<p>Link to the /etc/kubernetes/manifests/kube-apiserver.yaml file being used by the running cluster <a href="https://drive.google.com/file/d/1NajGU-ANFVV-PalLnvEcaX_d8pncF3j9/view?usp=sharing" rel="nofollow noreferrer">Here</a></p>
<pre><code>vagrant@master-1:~$ kubectl delete pods kube-apiserver-master-1 -n kube-system
pod "kube-apiserver-master-1" deleted
</code></pre>
<p>Unfortunately "kubectl describe pods kube-apiserver-master-1 -n kube-system" only informs that the pod has been recreated. Flags do not appear as desired. No errors reported.</p>
<p>Any suggestion will be helpful,</p>
<p>Thank you.</p>
<p>NOTES:</p>
<ol>
<li>I also tried to make a patch on the apiserver's configmap.
The patch is applied, but it does not take effect in the new
running pod.</li>
<li>I also tried to pass the two flags in a file via kubeadm
init --config, but there is little documentation on how to put these
two flags and all the other ones of the apiserver that I need in a configuration file in order to reinstall the master node.</li>
</ol>
<p><strong>UPDATE:</strong></p>
<p>I hope that be useful for everyone facing the same issue...</p>
<p>After 2 days of searching the internet, and lots and lots of tests, I only managed to make it work with the procedure below:</p>
<pre><code>sudo tee ${KUBEADM_INIT_CONFIG_FILE} <<EOF
apiVersion: kubeadm.k8s.io/v1beta2
kind: InitConfiguration
localAPIEndpoint:
advertiseAddress: "${INTERNAL_IP}"
bindPort: 6443
---
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
kubernetesVersion: ${KUBERNETES_VERSION}
controlPlaneEndpoint: "${LOADBALANCER_ADDRESS}:6443"
networking:
podSubnet: "10.244.0.0/16"
apiServer:
extraArgs:
advertise-address: ${INTERNAL_IP}
enable-admission-plugins: NodeRestriction,PodNodeSelector
admission-control-config-file: ${ADMISSION_CONTROL_CONFIG_FILE}
extraVolumes:
- name: admission-file
hostPath: ${ADMISSION_CONTROL_CONFIG_FILE}
mountPath: ${ADMISSION_CONTROL_CONFIG_FILE}
readOnly: true
- name: podnodeselector-file
hostPath: ${PODNODESELECTOR_CONFIG_FILE}
mountPath: ${PODNODESELECTOR_CONFIG_FILE}
readOnly: true
EOF
sudo kubeadm init phase control-plane apiserver --config=${KUBEADM_INIT_CONFIG_FILE}
</code></pre>
| <p>You need to create a <code>hostPath</code> volume mount like below</p>
<pre><code>volumeMounts:
- mountPath: /vagrant
name: admission
readOnly: true
...
volumes:
- hostPath:
path: /vagrant
type: DirectoryOrCreate
name: admission
</code></pre>
|
<p>I'm using 0.14.2 Terraform version. I'm trying to deploy an EKS cluster with two nodes with this code:</p>
<pre><code>resource "aws_eks_cluster" "cluster" {
enabled_cluster_log_types = []
name = var.cluster_name
role_arn = aws_iam_role.cluster.arn
version = var.eks_version
vpc_config {
subnet_ids = flatten([ aws_subnet.private.*.id, aws_subnet.public.*.id ])
security_group_ids = []
endpoint_private_access = "true"
endpoint_public_access = "true"
}
tags = var.tags[terraform.workspace]
depends_on = [
aws_iam_role_policy_attachment.cluster_AmazonEKSClusterPolicy,
aws_iam_role_policy_attachment.cluster_AmazonEKSServicePolicy,
aws_cloudwatch_log_group.cluster
]
}
resource "aws_launch_configuration" "eks-managenodes" {
for_each = local.ob
name_prefix = "${var.cluster_name}-launch-${each.value}"
image_id = "ami-038341f2c72928ada"
instance_type = "t3.medium"
user_data = <<-EOF
#!/bin/bash
set -o xtrace
/etc/eks/bootstrap.sh ${var.cluster_name}
EOF
root_block_device {
delete_on_termination = true
volume_size = 30
volume_type = "gp2"
}
lifecycle {
create_before_destroy = true
}
}
resource "aws_autoscaling_group" "eks-asg" {
for_each = local.ob
desired_capacity = 1
launch_configuration = aws_launch_configuration.eks-managenodes[each.value].id
max_size = 1
min_size = 1
name = "${var.cluster_name}-node-${each.value}"
vpc_zone_identifier = aws_subnet.private.*.id
tag {
key = "Name"
value = "eks-manage-node-${each.value}"
propagate_at_launch = true
}
tag {
key = "kubernetes.io/cluster/${var.cluster_name}"
value = "owned"
propagate_at_launch = true
}
depends_on = [
aws_launch_configuration.eks-managenodes,
aws_eks_cluster.cluster
]
}
</code></pre>
<p>Then, the cluster deploy fine, the ASG and the EC2 instances deploy fine, but the problem is that these instances doesn't attach to the corresponding cluster and I don't find the problem..</p>
<p>Any idea?
Thanks</p>
| <p>Nodes can fail to join a cluster for a variety of reasons.</p>
<ol>
<li>a failure during cloud-init may be preventing them from registering with the cluster control plane.</li>
<li>there may be IAM authentication failures.</li>
</ol>
<p>Debugging steps:</p>
<ol>
<li><p>Ssh into a node and check <code>/var/log/cloud-init.log</code> and <code>/var/log/cloud-init-output.log</code> to ensure that it completed without error.</p>
</li>
<li><p>verify that <code>kubelet</code> and <code>aws-node</code> processes are running on the ec2 nodes. Both should show up in <code>ps</code></p>
</li>
<li><p>check that <code>/etc/eks/bootstrap.sh</code> exists. Try invoking it as root with the arguments <code>/etc/eks/bootstrap.sh --apiserver-endpoint '${endpoint}' --b64-cluster-ca '${cluster_ca_data}' '${cluster_name}'</code> using the variables sourced from the EKS overview page in the AWS ui.</p>
</li>
<li><p>check the <code>aws-auth</code> config map in <code>kube-system</code> and verify the ec2 role is mapped like this:</p>
</li>
</ol>
<pre><code> mapRoles: |
- rolearn: arn:aws:iam::<account id>:role/<node role>
username: system:node:{{EC2PrivateDNSName}}
groups:
- system:bootstrappers
- system:nodes
</code></pre>
<p>as without this the node will not be able to authenticate to the cluster.</p>
<p>When in doubt, try the newest version of the EKS ami for your cluster's kubernetes version - some AMIs are broken.</p>
|
<p>I have a Service on GKE of type LoadBalancer that points to a GKE deployment running nginx. My nginx has all of the timeouts set to 10 minutes, yet HTTP/HTTPS requests that have to wait on processing before receiving a response get cutoff with 500 errors after 30 seconds. My settings:</p>
<pre><code>http {
proxy_read_timeout 600s;
proxy_connect_timeout 600s;
keepalive_timeout 600s;
send_timeout 600s;
}
</code></pre>
<p>Apparently there are default settings of 30 seconds in the LoadBalancer somewhere.</p>
<p>After pouring through documentation, I've only found a step-through at Google that outlines setting an Ingress with back-end service Load Balancer with a timeout but can't find how to do that on a Service that's Type=LoadBalancer for use with GKE. I've also reviewed all of the Kubernetes documentation for versions 1.7+ (we're on 1.8.7-gke.1) and nothing about setting a timeout. Is there a setting I can add to my yaml file to do this?</p>
<p>If it helps I found the following for AWS, which appears to be what I would need to have on GKE:</p>
<pre><code> annotations:
service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout: "60"
</code></pre>
| <p>As of April 2021 you can do this via GKE/GCE configuration. <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/ingress-features#create_backendconfig" rel="nofollow noreferrer">Here</a> are the instructions.
Essentially you create a <code>BackendConfig</code> resource similar to this:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
name: my-backendconfig
spec:
timeoutSec: 40
connectionDraining:
drainingTimeoutSec: 60
</code></pre>
<p>(<code>kubectl apply -f my-backendconfig.yaml</code>)</p>
<p>and then connect it to your GKE service resource with an annotation:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
name: my-service
labels:
purpose: bsc-config-demo
annotations:
cloud.google.com/backend-config: '{"ports": {"80":"my-backendconfig"}}'
cloud.google.com/neg: '{"ingress": true}'
spec:
type: ClusterIP
selector:
purpose: bsc-config-demo
ports:
- port: 80
protocol: TCP
targetPort: 8080
</code></pre>
<p>(<code>kubectl apply -f my-service.yaml</code>)</p>
<p>If you prefer, the BackendConfig resource (and Service) can be placed in a namespace with a metadata namespace designation in your yaml.</p>
<pre class="lang-yaml prettyprint-override"><code>metadata:
namespace: my-namespace
</code></pre>
|
<p>In Docker a client container can refer to a server container by different names by using link aliasing:</p>
<pre><code>--link server-container:my_preferred_server
</code></pre>
<p>A second client can use its own choice of names</p>
<pre><code>-- link server-container:server
</code></pre>
<p>Can I achieve this in K8s preferably by adding different records in K8s's DNS?</p>
<p><strong>Note</strong> the solution we are using now is having the client containers not use a hardcoded name for the server container, but use the value of an env variable SERVER_HOSTNAME='server-container' and link without aliasing:</p>
<pre><code>--link server_container
</code></pre>
<p><strong>Edit:</strong> To answer to some of the questions got in the replies:<br>
* there is more than one client container, otherwise aliasing would have no purpose. Each client knows the server by a different name<br>
* the client and the server are not in the same pod </p>
| <p>I just had the same need and I was able to add an external Service, which points to the FQDN of the other service within the cluster:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: "my-alias"
spec:
type: ExternalName
externalName: "other-service.my-namespace.svc.cluster.local"
</code></pre>
<p>Now, I can access <code>other-service</code> as <code>my-alias</code> from within the cluster and namespace.</p>
|
<p>I have deployed postgresql pod on kubernetes pod, and want to know how can I access postgresql gui. I am not able to access it with ingress path, as I got to know ingress are meant for https purpose only whereas postgres follows TCP protocol. Any lead how can I access through GUI?</p>
<p>deployment.yaml</p>
<pre><code>---
apiVersion: "apps/v1"
kind: "Deployment"
metadata:
name: "postgresql-development"
namespace: "development"
spec:
selector:
matchLabels:
app: "postgresql-development"
replicas: 1
strategy:
type: "RollingUpdate"
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
minReadySeconds: 5
template:
metadata:
labels:
app: "postgresql-development"
tier: "mysql"
spec:
containers:
-
name: "postgresql-development"
image: "postgresql:12.6"
imagePullPolicy: "Always"
env:
-
name: "POSTGRES_USER"
value: "postgres"
ports:
-
containerPort: 5432
name: "postgres"
volumeMounts:
-
name: "postgresql-persistent-storage"
mountPath: "/var/lib/postgresql"
volumes:
-
name: "postgresql-persistent-storage"
persistentVolumeClaim:
claimName: "postgresql-pvc-development"
imagePullSecrets:
-
name: "postgresql"
</code></pre>
<p>service.yaml</p>
<pre><code>---
apiVersion: "v1"
kind: "Service"
metadata:
name: "postgresql-development"
namespace: "development"
labels:
app: "postgresql-development"
app.kubernetes.io/name: ingress-nginx
app.kubernetes.io/part-of: ingress-nginx
spec:
ports:
-
port: 59799
targetPort: 5432
protocol: TCP
selector:
app: "postgresql-development"
app.kubernetes.io/name: ingress-nginx
app.kubernetes.io/part-of: ingress-nginx
tier: mysql
</code></pre>
<p>ingress.yaml</p>
<pre><code>---
apiVersion: "networking.k8s.io/v1beta1"
kind: "Ingress"
metadata:
name: "postgresql-development-ingress"
namespace: "development"
annotations:
nginx.ingress.kubernetes.io/rewrite-target: "/$1"
spec:
rules:
-
host: "localhost"
http:
paths:
-
backend:
serviceName: "postgresql-development"
servicePort: 59799
path: "postgresql-development/(.*)"
</code></pre>
| <p>Ingress API are only for Layer 7 (HTTP). In your case you want to access Layer 4 (TCP).</p>
<p>To achieve you goal, you can:</p>
<ul>
<li>Use a <a href="https://kubernetes.io/docs/concepts/services-networking/service/#nodeport" rel="nofollow noreferrer">Nodeport</a> on your service</li>
<li>A Ingress Controller that handle TCP like <a href="https://doc.traefik.io/traefik/routing/providers/kubernetes-crd/#kind-ingressroutetcp" rel="nofollow noreferrer">Traefik</a> or <a href="https://kubernetes.github.io/ingress-nginx/user-guide/exposing-tcp-udp-services/" rel="nofollow noreferrer">Nginx</a></li>
<li>for local development, <a href="https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/" rel="nofollow noreferrer">Port Forward</a></li>
</ul>
|
<p>I have a postgres pod deployed on OpenShift and a PVC that I think that I correctly attached but I could be wrong. This is my PVC and it is correctly Bound -</p>
<pre><code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: xxxxx
</code></pre>
<p>I created the postgres pods with a <code>PGDATA</code> env set to <code>/var/lib/postgresql/pgdata</code> and mounted the PVC like so -</p>
<pre><code>oc set volume dc/postgres --add --name=postgres-pvc --type=persistentVolumeClaim \
--claim-name=postgres-pvc --mount-path=/var/lib/postgresql/pgdata --containers=postgres
</code></pre>
<p>I originally tried to attach the PVC to <code>/var/lib/postgresql/data</code> by overwriting the original container volume but it said there was issues with something like mounting directly to that <code>data</code> folder path so that's why I used the <code>pgdata</code> one.</p>
<pre><code>oc set volume dc/postgres --add --overwrite --name=postgres-volume-1 --type=persistentVolumeClaim \
--claim-name=postgres-pvc --mount-path=/var/lib/postgresql/data --containers=postgres
</code></pre>
<p>The error that I get now is when I try to scale up the pod/add a replica via the DC, it gives the following errors -</p>
<pre><code>Unable to attach or mount volumes: unmounted volumes=[postgres-pvc], unattached volumes=[postgres-volume-1 postgres-pvc postgres-token-h7jvr]: timed out waiting for the condition
</code></pre>
<p>and</p>
<pre><code>Error while attaching the device pv pvc-b87b49ff-2bce-495c-b17f-b45f51eab27b cannot be attached to the node xx.xx.xxx.xx. Error: PV pvc-b87b49ff-2bce-495c-b17f-b45f51eab27b is already attached to another node xx.xx.xxx.x and there are active pods [postgres-7-6p6sz] using that
</code></pre>
<p>Is it because I did an incorrect mount of my PVC? Or do I need to create a new PVC and then manually update the new pod to that newly created PVC?</p>
| <p>as you can see the error</p>
<blockquote>
<p>already attached to another node xx.xx.xxx.x and there are active pods [postgres-7-6p6sz] using that</p>
</blockquote>
<p>you are utilizing a block storage as pv which has <strong>accessModes</strong> of <code>ReadWriteOnce</code> that means at any given time volume could be attached to a single kubernetes node, on that node then, a pod can mount it.
now if you want to attach to another pod, you need to remove the existing pod which will make pv to unattach from previous node, reattach to the new node.</p>
<p>for further details <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/" rel="nofollow noreferrer">persistent-volumes/</a></p>
|
<p>While learning Kubernetes going by the book Kubernetes for developer, I am stuck at this point now.</p>
<p>I am trying to start Rabbitmq pod but but after lot of troubleshooting I have managed to get to this point but do not get clue where do I fix to get rid of the permission denied error.</p>
<pre><code># kubectl get pods
NAME READY STATUS RESTARTS AGE
rabbitmq-56c67d8d7d-s8vp5 0/1 CrashLoopBackOff 5 5m40s
</code></pre>
<p>if I look at the logs of this contianer thats where I found:</p>
<pre><code># kubectl logs rabbitmq-56c67d8d7d-s8vp5
21:22:58.49
21:22:58.50 Welcome to the Bitnami rabbitmq container
21:22:58.51 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-rabbitmq
21:22:58.51 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-rabbitmq/issues
21:22:58.52 Send us your feedback at containers@bitnami.com
21:22:58.52
21:22:58.52 INFO ==> ** Starting RabbitMQ setup **
21:22:58.54 INFO ==> Validating settings in RABBITMQ_* env vars..
21:22:58.56 INFO ==> Initializing RabbitMQ...
21:22:58.57 INFO ==> Generating random cookie
mkdir: cannot create directory ‘/bitnami/rabbitmq’: Permission denied
</code></pre>
<p>Here is my <strong>rabbitmq-deployment.yml</strong></p>
<pre><code>---
# EXPORT SERVICE INTERFACE
kind: Service
apiVersion: v1
metadata:
name: message-queue
labels:
app: rabbitmq
role: master
tier: queue
spec:
ports:
- port: 5672
targetPort: 5672
selector:
app: rabbitmq
role: master
tier: queue
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: rabbitmq-pv-claim
labels:
app: rabbitmq
spec:
storageClassName: manual
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: rabbitmq
spec:
replicas: 1
selector:
matchLabels:
app: rabbitmq
role: master
tier: queue
template:
metadata:
labels:
app: rabbitmq
role: master
tier: queue
spec:
nodeSelector:
boardType: x86vm
containers:
- name: rabbitmq
image: bitnami/rabbitmq:3.7
envFrom:
- configMapRef:
name: bitnami-rabbitmq-config
ports:
- name: queue
containerPort: 5672
- name: queue-mgmt
containerPort: 15672
livenessProbe:
exec:
command:
- rabbitmqctl
- status
initialDelaySeconds: 120
timeoutSeconds: 5
failureThreshold: 6
readinessProbe:
exec:
command:
- rabbitmqctl
- status
initialDelaySeconds: 10
timeoutSeconds: 3
periodSeconds: 5
volumeMounts:
- name: rabbitmq-storage
mountPath: /bitnami
volumes:
- name: rabbitmq-storage
persistentVolumeClaim:
claimName: rabbitmq-pv-claim
</code></pre>
<p>This is the <strong>rabbitmq-storage-class.yml</strong></p>
<pre><code>kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
name: rabbitmq-storage-class
labels:
app: rabbitmq
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
</code></pre>
<p>and <strong>persistant-volume.yml</strong></p>
<pre><code>apiVersion: v1
kind: PersistentVolume
metadata:
name: rabbitmq-pv-claim
labels:
app: rabbitmq
spec:
storageClassName: manual
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
hostPath:
path: /bitnami
</code></pre>
<p>Logs:</p>
<pre><code># kubectl describe pods rabbitmq-5f7f787479-fpg6g
Name: rabbitmq-5f7f787479-fpg6g
Namespace: default
Priority: 0
Node: kube-worker-vm2/192.168.1.36
Start Time: Mon, 03 May 2021 12:29:17 +0100
Labels: app=rabbitmq
pod-template-hash=5f7f787479
role=master
tier=queue
Annotations: cni.projectcalico.org/podIP: 192.168.222.4/32
cni.projectcalico.org/podIPs: 192.168.222.4/32
Status: Running
IP: 192.168.222.4
IPs:
IP: 192.168.222.4
Controlled By: ReplicaSet/rabbitmq-5f7f787479
Containers:
rabbitmq:
Container ID: docker://bbdbb9c5d4b6737519d3dcf4bdda242a7fe904f2336334afe686e9b204fd6d5c
Image: bitnami/rabbitmq:3.7
Image ID: docker-pullable://bitnami/rabbitmq@sha256:8b6057997b74ebc81e934dd6c94e9da745635faa2d79b382cfda27b9176e0e6d
Ports: 5672/TCP, 15672/TCP
Host Ports: 0/TCP, 0/TCP
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Error
Exit Code: 1
Started: Mon, 03 May 2021 12:30:48 +0100
Finished: Mon, 03 May 2021 12:30:48 +0100
Ready: False
Restart Count: 4
Liveness: exec [rabbitmqctl status] delay=120s timeout=5s period=10s #success=1 #failure=6
Readiness: exec [rabbitmqctl status] delay=10s timeout=3s period=5s #success=1 #failure=3
Environment Variables from:
bitnami-rabbitmq-config ConfigMap Optional: false
Environment: <none>
Mounts:
/bitnami from rabbitmq-storage (rw)
/var/run/secrets/kubernetes.io/serviceaccount from default-token-4qmxr (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
rabbitmq-storage:
Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
ClaimName: rabbitmq-pv-claim
ReadOnly: false
default-token-4qmxr:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-4qmxr
Optional: false
QoS Class: BestEffort
Node-Selectors: boardType=x86vm
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 2m20s default-scheduler Successfully assigned default/rabbitmq-5f7f787479-fpg6g to kube-worker-vm2
Normal Created 96s (x4 over 2m18s) kubelet Created container rabbitmq
Normal Started 95s (x4 over 2m17s) kubelet Started container rabbitmq
Warning
BackOff 65s (x12 over 2m16s) kubelet Back-off restarting failed container
Normal Pulled 50s (x5 over 2m18s) kubelet Container image "bitnami/rabbitmq:3.7" already present on machine
</code></pre>
| <p>When creating an image, the image creator often chooses to use a user other than root to run the process. This is the case for your image, and the user does not have write permissions on the <code>/bitnami</code> directory. You can verify this by commenting out the volume.</p>
<p>To fix the issue, you need to set a security contect for your pod: <a href="https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-pod" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-pod</a></p>
<p>Not sure about the exact syntax, but something like this should do the trick:</p>
<pre><code>spec:
securityContext:
fsGroup: 1001 # the userid that is used in the image
nodeSelector:
boardType: x86vm
containers:
- name: rabbitmq
image: bitnami/rabbitmq:3.7
envFrom:
- configMapRef:
name: bitnami-rabbitmq-config
</code></pre>
<p>This makes the directory writeable by the user in the image.</p>
<p>Another thing: A deployment is for stateless services by design. If you have state to keep, always use a statefulset. It's very similiar to a deployment from a configuration point of view, but Kubernetes treats it very differently. See <a href="https://www.youtube.com/watch?v=Vrxr-7rjkvM" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Vrxr-7rjkvM</a> for good explanation.</p>
|
<p>EDIT: I rewrote the question with a fully reproducible example.</p>
<p>I have a sample Django app with the base getting started <a href="https://docs.djangoproject.com/en/3.2/intro/tutorial01/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.2/intro/tutorial01/</a>, that is, there are two paths <code>/admin</code> and <code>/polls</code>.</p>
<p>If I deploy the app using NodePort, I can access both paths without issues. However, I haven't managed to do the same with Nginx ingress controller. I have tried several combinations of annotations and paths to no avail.</p>
<p>So, assume this yaml:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: django
name: django
spec:
selector:
matchLabels:
app: django
template:
metadata:
labels:
app: django
spec:
containers:
- image: "ay0o/django-ingress:latest"
name: django
# ---
# apiVersion: v1
# kind: Service
# metadata:
# name: django
# spec:
# ports:
# - nodePort: 31000
# port: 8000
# targetPort: 8000
# selector:
# app: django
# type: NodePort
---
apiVersion: v1
kind: Service
metadata:
name: django
spec:
ports:
- port: 8000
selector:
app: django
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: django
spec:
rules:
- http:
paths:
- path: /django
pathType: Prefix
backend:
service:
name: django
port:
number: 8000
</code></pre>
<p>when I use NodePort, <code>http://localhost:31000/admin</code> and <code>http://localhost:31000/polls</code> work fine.</p>
<p>when I use Ingress, <code>http://localhost/django</code> returns a 404 from django (because the path is neither admin nor polls), but <code>http://localhost/django/admin</code> and <code>http://localhost/django/polls</code> return a 404 from nginx, meaning the ingress is not properly routing.</p>
<p>so, what should I change so that <code>http://localhost/django/admin</code> and <code>http://localhost/django/polls</code> will not return 404?</p>
| <p>I have come to the conclusion that it's not possible to use path-based Ingress for a Django app, probably due to something related to Django's internals.</p>
<p>Every example out there uses host-based rules, and indeed, that just work. For example, the Ingress above can be changed to the following, and it will work.</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: django
spec:
rules:
- host: localhost
http:
paths:
- pathType: Prefix
path: "/"
backend:
service:
name: django
port:
number: 8000
</code></pre>
<p>If anyone come up with a solution using path-based routing, feel free to answer the question.</p>
|
<p>We have a GKE cluster with <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/node-auto-upgrades" rel="noreferrer">auto-upgrading nodes</a>. We recently noticed a node become unschedulable and eventually deleted that we suspect was being upgraded automatically for us. Is there a way to confirm (or otherwise) in Stackdriver that this was indeed the cause what was happening?</p>
| <p>You can use the following advanced logs queries with Cloud Logging (previously Stackdriver) to detect upgrades to <strong>node pools</strong>:</p>
<pre><code>protoPayload.methodName="google.container.internal.ClusterManagerInternal.UpdateClusterInternal"
resource.type="gke_nodepool"
</code></pre>
<p>and <strong>master</strong>:</p>
<pre><code>protoPayload.methodName="google.container.internal.ClusterManagerInternal.UpdateClusterInternal"
resource.type="gke_cluster"
</code></pre>
<p>Additionally, you can control when the update are applied with <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/maintenance-windows-and-exclusions" rel="noreferrer">Maintenance Windows</a> (like the user aurelius mentioned).</p>
|
<p>I'm trying to restart my kubernetes deployment via the kubernetes api using the
@kubernetes/client-node Library. I'm not using deployment scale because i only need one deployment (db and service container) per app.</p>
<p>I also tried to restart a single container inside the deployment via exec (/sbin/reboot or kill), but it seems to not work with the nodejs library because it fails to upgrade to websocket connection, what is needed by the kubernetes exec endpoint as it seems. The other idea was to restart the whole deployment by setting the scale to 0 and then 1 again. But I dont get it working via the nodejs library. I tried to find an example for that, but was not successful.</p>
<p>The rolling restart is not working for me, becuase my application doesnt support multiple instances.</p>
<p>i tried it like this to scale</p>
<pre><code>await k8sApi.patchNamespacedDeploymentScale(`mydeployment-name`, 'default', {
spec: { replicas: 0 },
});
await k8sApi.patchNamespacedDeploymentScale(`mydeployment-name`, 'default', {
spec: { replicas: 1 },
});
</code></pre>
<p>and to reboot the container i tried this</p>
<pre><code>await coreV1Api.connectPostNamespacedPodExec(
podName,
'default',
'/sbin/reboot',
'web',
false,
false,
false,
false
);
</code></pre>
<hr />
<p>Extra input:</p>
<p>When trying to use patchNamespacedDeployment i get the following error back by kubernetes api:</p>
<pre><code>statusCode: 415,
statusMessage: 'Unsupported Media Type',
</code></pre>
<p>And response body:</p>
<pre><code>V1Scale {
apiVersion: 'v1',
kind: 'Status',
metadata: V1ObjectMeta {
annotations: undefined,
clusterName: undefined,
creationTimestamp: undefined,
deletionGracePeriodSeconds: undefined,
deletionTimestamp: undefined,
finalizers: undefined,
generateName: undefined,
generation: undefined,
labels: undefined,
managedFields: undefined,
name: undefined,
namespace: undefined,
ownerReferences: undefined,
resourceVersion: undefined,
selfLink: undefined,
uid: undefined
},
spec: undefined,
status: V1ScaleStatus { replicas: undefined, selector: undefined }
</code></pre>
<p>when trying the exec approach i get the following response:</p>
<pre><code>kind: 'Status',
apiVersion: 'v1',
metadata: {},
status: 'Failure',
message: 'Upgrade request required',
reason: 'BadRequest',
code: 400
</code></pre>
<p>i already looked the upgrade request error up, and it seems like the library isnt aware of this, because the library was generated from function footprints or something, so it is not aware of websockets.</p>
| <p>Really seems like there is a bug in the node Kubernetes client library.
On PATCH requests it should set the content type to "application/json-patch+json" but instead it sends the content type as "application/json".
Thats why you get unsupported media type back by the api.</p>
<p>Furthermore you need to use the JSON Patch format for the body you send: <a href="http://jsonpatch.com" rel="noreferrer">http://jsonpatch.com</a></p>
<p>To manually set the content type you can pass custom headers to the function call.</p>
<p>This worked for me:</p>
<pre><code>const patch = [
{
op: 'replace',
path: '/spec/replicas',
value: 0,
},
];
await k8sApi.patchNamespacedDeployment(
`mydeployment-name`,
'default',
patch,
undefined,
undefined,
undefined,
undefined,
{ headers: { 'content-type': 'application/json-patch+json' } }
);
</code></pre>
<p>After some google searching I found that this problem is already existing since 2018: <a href="https://github.com/kubernetes-client/javascript/issues/19" rel="noreferrer">https://github.com/kubernetes-client/javascript/issues/19</a></p>
|
<p>I have a GKE/GCE ingress file which has 2 hosts.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: my-ingress
spec:
rules:
- host: myfirstdomain # <-------- override this via kustomize
http:
paths:
- path: /abc
backend:
serviceName: abc
servicePort: abc
- path: /def
backend:
serviceName: def
servicePort: def
- path: /ghi
backend:
serviceName: ghi
servicePort: ghi
- host: myseconddomain # <-------- override this via kustomize
http:
paths:
- backend:
serviceName: xyz
servicePort: xyz
</code></pre>
<p>I want to declare the <code>host</code> values via kustomize so that i can specify different <code>host</code> values for different environments.</p>
<p>My overlay patch file for dev environment looks like this:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: my-ingress
spec:
rules:
- host: dev1.example.com
- host: dev2.example.com
</code></pre>
<p>However, the output of running <code>kustomize build overlays/dev</code> looks like this:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: my-ingress
spec:
rules:
- host: dev1.example.com
- host: dev2.example.com
</code></pre>
<hr />
<h1>All other specs are lost.</h1>
<p>It ends up replacing the <strong>entire</strong> <code>host</code> blocks instead of replacing just the <code>host</code> lines.</p>
<p>How can i solve this? I am using:</p>
<ul>
<li><strong>kustomize</strong> version <code>v4.1.2</code></li>
<li><strong>kubectl</strong> version <code>v1.21.0</code></li>
</ul>
| <p>You can not do that using <strong><a href="https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/patchesstrategicmerge/" rel="noreferrer">strategic merge</a></strong> since the <code>spec.rules</code> is an array of items. You have to use <strong><a href="https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/patchesjson6902/" rel="noreferrer">json merge</a></strong> by providing the exact paths to be impacted.</p>
<p>You can create a separate patch file for json merge like below:</p>
<pre class="lang-yaml prettyprint-override"><code># overlays/dev/ingress-json-patch.yaml
- op: replace
path: /spec/rules/0/host
value: dev1.example.com
- op: replace
path: /spec/rules/1/host
value: dev2.example.com
</code></pre>
<p>Then refer to that patch file by adding the following into your <code>kustomization.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code># overlays/dev/kustomization.yaml
patchesJson6902:
- target:
group: extensions
version: v1beta1
kind: Ingress
name: my-ingress
path: overlays/dev/ingress-json-patch.yaml
</code></pre>
|
<p>I created a flask app to run in container.</p>
<p><strong>Dockerfile</strong></p>
<pre><code>FROM python:3.7
LABEL MAINTAINER="Anirban"
RUN mkdir /app
WORKDIR /app
COPY . /app/
RUN pip install -r requirements.txt
RUN python setup.py install
ENV PORT 5000
ENV SERVER_NAME "0.0.0.0:5000"
EXPOSE 5000
CMD [ "python", "userapp/app.py" ]
</code></pre>
<p>My application structure</p>
<pre><code>[project]
|
--userapp
| |
| --app.py
--Dockerfile
</code></pre>
<p>Flask configuration</p>
<pre><code>def initialize_app(flask_app):
flask_app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
flask_app.register_blueprint(user_endpoints.REQUEST_API)
flask_app.config['SERVER_NAME'] = os.environ.get('SERVER_NAME', settings.FLASK_SERVER_NAME)
if __name__ == "__main__":
initialize_app(app)
app.run(debug=os.environ.get('FLASK_DEBUG', settings.FLASK_DEBUG))
</code></pre>
<p>Deployment</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: userauthapp
labels:
app: userauthapp
spec:
replicas: 1
selector:
matchLabels:
app: userauthapp
template:
metadata:
labels:
app: userauthapp
spec:
containers:
- name: userauthapp
image: <my image>
ports:
- containerPort: 5000
imagePullPolicy: Always
</code></pre>
<p>Loadbalancer</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: userauthapp-lb-svc
spec:
selector:
app: userauthapp
ports:
- protocol: "TCP"
port: 8080
targetPort: 5000
type: LoadBalancer
</code></pre>
<p>When I deploy both of them on minikube, I can see them running as below:</p>
<pre><code>NAME READY STATUS RESTARTS AGE
pod/userauthapp-6cc76bd66b-vst5n 1/1 Running 0 38s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 267d
service/userauthapp-lb-svc LoadBalancer 10.107.117.254 <pending> 8080:31145/TCP 2s
</code></pre>
<p>But I cannot access them with: curl 10.107.117.254:8080/ (which is health check api) or curl 10.107.117.254:8080/swagger. Does any one have an idea what was wrong with it?</p>
| <p>I got the issue. As it runs on minikube, it would be minikube IP that I needed to hit. Below command gives the minikube IP:</p>
<pre><code>minikube ip
</code></pre>
<p>Below command returns IP and corresponding service port</p>
<pre><code>minikube service --url userauthapp-lb-svc
</code></pre>
|
<p>Any suggestions on how track of kubectl configs(~/.kube/config) which allows you to access the kubernetes clusters? I have clusters running on different environments(local/prod) where i connect to the <strong>same</strong> namespace where project is deployed on and whenever i need to connect to a particular cluster, i run the below to configure ( different commands on aws/gcp/ microk8s etc) and the configuration gets attached to ~/.kube/config. Is there any easy way to know where you are connected or track which config is being used? Its a disaster waiting to happen unless you do a explicit check.</p>
<pre><code>aws eks --region region update-kubeconfig --name cluster_name
</code></pre>
<p>Current method used:</p>
<ul>
<li>Either (cat ~/.kube/config) i check the to see what cluster im connecting to.</li>
<li>move the config to some other directory and move the config back once im done.</li>
<li>kubectl get nodes to see where I'm connected.</li>
</ul>
| <h4>Using kubectl</h4>
<p>Kubectl has built in support for <a href="https://v1-18.docs.kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#config" rel="nofollow noreferrer">managing contexts</a>. After you add a context in <code>~/.kube/config</code> file, manually or, via <code>aws eks update-kubeconfig</code>, you can use the <code>config</code> sub-command to switch between contexts.</p>
<p>To view all saved contexts and highlight the current one:</p>
<pre class="lang-sh prettyprint-override"><code>kubectl config get-contexts
</code></pre>
<p>To just view the current context:</p>
<pre class="lang-sh prettyprint-override"><code>kubectl config current-context
</code></pre>
<p>To switch to another context</p>
<pre class="lang-sh prettyprint-override"><code>kubectl config use-context <context-name>
</code></pre>
<p>To delete a context:</p>
<pre class="lang-sh prettyprint-override"><code>kubectl config delete-context <context-name>
</code></pre>
<h4>Specific configuration file</h4>
<p>Sometimes it might be the case that all the cluster connections cannot be in the same kube config file, but instead, user has separate kube config files per cluster.</p>
<p>To run <code>kubectl</code> with a specific configuration, one can use <code>--kubeconfig</code> argument:</p>
<pre class="lang-sh prettyprint-override"><code>kubectl --kubeconfig ./someConfig -n someNs get pods
</code></pre>
<h4>Shell Aliases</h4>
<p>And when running from Linux shell or windows powershell, one can also use "aliases".</p>
<p><strong>Linux Bash example:</strong></p>
<p>Use bash <code>alias</code> to define commands as aliases:</p>
<pre class="lang-sh prettyprint-override"><code># Define a kubectl alias for specific cluster
alias myCluster="kubectl --kubeconfig ./myClusterConfig"
# Define a kubectl alias for specific cluster and specific namespace
alias myClusterNs="kubectl --kubeconfig ./myClusterConfig -n myNamespace"
</code></pre>
<p>Usage:</p>
<pre class="lang-sh prettyprint-override"><code># Using cluster kubectl alias
myCluster -n myNamespace get pods
# Using cluster kubectl alias with namespace
myClusterNs get pods
</code></pre>
<p>The alias definitions can be saved to <code>~/.profile</code> for permanent usage.</p>
<p><strong>Windows Powershell example:</strong></p>
<p>In Windows Powershell, a function can be defined as follows:</p>
<pre><code>function myCluster { kubectl --kubeconfig .\myClusterConfig $args }
</code></pre>
<p>And used as:</p>
<pre><code>myCluster -n myNamespace get pods
</code></pre>
<p>More arguments like <code>-n <namespace></code> can also be specified in function definition before <code>$args</code>. Make sure to properly quote (") the arguments with special characters on windows.</p>
|
<p>I mean is there a one to one or many to one relationship between pod and PVC? Can I connect two or more pods to the same PVC(persistent volume claims) without deleting or disconnecting the earlier created pods?</p>
| <blockquote>
<p>Can I connect two or more pods to the same PVC(persistent volume claims) without deleting or disconnecting the earlier created pods?</p>
</blockquote>
<p>Yes, this works. But in practice this is a bit more complicated.</p>
<p>Persistent Volumes can be created with different <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes" rel="noreferrer">access modes</a>. Your storage system may limit what <em>access modes</em> you can use. E.g. the access mode <code>ReadWriteMany</code> is only available in some storage systems. The access mode <code>ReadWriteOnce</code> is most commonly available.</p>
<p>For multiple Pods accessing a Persistent Volume mounted with access mode <code>ReadWriteOnce</code>, they must be scheduled to the <strong>same node</strong> to concurrently access the volume.</p>
<p>For multiple Pods accessing a Persistent Volume mounted with access mode <code>ReadWriteMany</code> or <code>ReadOnlyMany</code>, the Pods can be scheduled to different nodes. But in a "cloud provider" environment, where you use multiple Availability Zones in a Region, your Persistent Volume is typically only accessible within <strong>one Availability Zone</strong>, so you must make sure that your Pods are scheduled to the same Availability Zone. Cloud providers typically offer Regional volumes as well, but they are more expensive and you need to use a specific <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/" rel="noreferrer">storage class</a> for this.</p>
|
<p>I have a <strong>Private AKS cluster</strong> deployed in a VNET on Azure. Once I deployed it, a private endpoint and a private DNS zone were created by default therefore making the cluster accessible from VM's which are part of the same VNET. (<em>I have a VM deployed in the same VNET as the AKS cluster and "kubectl" commands work in it.</em>)</p>
<p>My requirement is that I want to perform the "kubectl" commands from my local machine (connected to my home network) and also connected to the VPN which connects to the VNET.</p>
<p>My machine can talk to resources within the VNET but cannot seem to resolve the FQDN of the private cluster.</p>
<p>I read somewhere that having a DNS forwarder setup in the same VNET can help resolve the DNS queries made from the local machine which can then be resolved by Azure DNS. Is this the way to go about this? Or is there a better way to solve this problem?</p>
<p>It would really help if someone could give me an action plan to follow to solve this problem.</p>
| <p>The better way to perform the "kubectl" commands from your local machine to your private AKS cluster is to use <a href="https://learn.microsoft.com/en-us/azure/aks/private-clusters#aks-run-command-preview" rel="nofollow noreferrer">AKS Run Command (Preview)</a>. This feature allows you to remotely invoke commands in an AKS cluster through the AKS API. This feature provides an API that allows you to, for example, execute just-in-time commands from a remote laptop for a private cluster. Before using it, you need to enable the <code>RunCommandPreview</code> feature flag on your subscription and install <code>aks-preview</code> extension locally. However, there is a limitation that <strong>AKS-RunCommand does not work on clusters with AKS managed AAD and Private link enabled</strong>.</p>
<p>In this case, If you want to resolve the FQDN of the private cluster from your on-premise network, you could select to use either the hosts file locally(used for testing) or use your DNS forwarder to override the DNS resolution for a private link resource like <a href="https://learn.microsoft.com/en-us/azure/private-link/private-endpoint-dns#on-premises-workloads-using-a-dns-forwarder" rel="nofollow noreferrer">this</a>.</p>
<p>The DNS forwarder will be responsible for all the DNS queries via a server-level forwarder to the Azure-provided DNS <code>168.63.129.16</code>.You can provision IaaS Windows VM with DNS role or Linux VM with bind configured as a DNS forwarder. <a href="https://azure.microsoft.com/en-us/resources/templates/301-dns-forwarder/" rel="nofollow noreferrer">This template</a> shows how to create a DNS server that forwards queries to Azure's internal DNS servers for Linux VM. Refer to <a href="https://anktsrkr.github.io/post/resolve-azure-internal-dns-from-your-on-prem-network/" rel="nofollow noreferrer">this</a> for DNS forwarder on Windows VM.</p>
<p>If there is an internal DNS server in your on-premise network. The on-premises DNS solution needs to forward DNS traffic to Azure DNS via a conditional forwarder for your public DNS zones(e.g. <code>{region}.azmk8s.io</code>). The conditional forwarder references the DNS forwarder deployed in Azure. You could read <a href="https://bloggerz.cloud/2020/12/18/azure-private-link-and-dns/" rel="nofollow noreferrer">this blog</a> about DNS configuration sections for more details.</p>
|
<p>I have 3 ingress pointing to the same service. In my kubernetes pod, how can i find the hostname and from which subdomain request is coming . my backend code in golang server.<br />
when the request comes to any pod, i want to know from which subdomain(x,y,x) request has come to pod. Currently in the golang code it's giving hostname as pod ip address</p>
<pre><code>kind: Ingress
metadata:
annotations:
ingress.kubernetes.io/browser-xss-filter: 'true'
ingress.kubernetes.io/force-hsts: 'true'
ingress.kubernetes.io/hsts-include-subdomains: 'true'
ingress.kubernetes.io/hsts-max-age: '315360000'
name: test
namespace: test
spec:
rules:
- host: http://x.test.com
http:
paths:
- backend:
serviceName: test-service
servicePort: 8080
path: /
- host: http://y.test.com
http:
paths:
- backend:
serviceName: test-service
servicePort: 8080
path: /
- host: http://z.test.com
http:
paths:
- backend:
serviceName: test-service
servicePort: 8080
path: /
</code></pre>
<pre><code>func Subdomain( r *http.Request) {
host := r.URL.Host
host = strings.TrimSpace(host)
//Figure out if a subdomain exists in the host given.
host_parts := strings.Split(host, ".")
if len(host_parts) > 2 {
//The subdomain exists, we store it as the first element
//in a new array
subdomain := []string{host_parts[0]}
}
}
</code></pre>
| <p>Try to use the <code>X-Forwarded-Host</code> header added by the ingress controller</p>
|
<p>I am new in <code>AWS</code> and <code>EKS</code>. Everything is going well except I am not able to figure out How to expose the ingress IP/Domain for public usage?</p>
<p>I tested on <code>minikube</code> and using <code>minikube ip</code>, I was able to run the application. How should I do it in <code>AWS EKS</code>?</p>
<p>Here is my ingress service file</p>
<pre><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: platform-app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- http:
paths:
- path: /?(.*)
pathType: Prefix
backend:
serviceName: platform-app-api
servicePort: 80
</code></pre>
<p>Any hint? what am I doing wrong here?</p>
| <p>You have to install the ingress controller basically which handles and manages the ingress object.</p>
<p>there are multiple ingress controllers available in the market for the Kubernetes you can use one of as per need.</p>
<p><a href="https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/</a></p>
<p>so your whole traffic whole will be something like</p>
<pre><code>internet > ingress > ingress controller > Kubernetes service > pod > container
</code></pre>
<p>you are using the annotation of <strong>nginx</strong></p>
<p>for that controller is must need to be installed in cluster.</p>
<p>everything will be same just you need to install the controller using YAML or Helm chart no other configuration required.</p>
<p>you can read more at : <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-on-digitalocean-kubernetes-using-helm" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-on-digitalocean-kubernetes-using-helm</a></p>
<p>Official deployment documentation : <a href="https://kubernetes.github.io/ingress-nginx/deploy/" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/</a></p>
<p>how to install on AWS : <a href="https://kubernetes.github.io/ingress-nginx/deploy/#aws" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/#aws</a></p>
<p><strong>Note</strong> :</p>
<p>Once you will deploy the Ingress controller it will create one Kubernetes service with the type <strong>LoadBalancer</strong>.</p>
<p>you can check this using the <strong>Kubectl get svc -n </strong></p>
<p>Use that IP as the <strong>public IP</strong>. you can add this IP into the DNS and create the multiple subdomain and domain as per need.</p>
|
<p>This is the first time I deployed Cluster Autoscaler (CA) on EKS.</p>
<p>The CA configuration file contains Limits & Requests:</p>
<pre><code> Limits:
│ cpu: 100m
│ memory: 300Mi
│ Requests:
│ cpu: 100m
│ memory: 300Mi
</code></pre>
<p>My questions are the following:</p>
<ol>
<li>Does the Limits & Requests fields in the CA refers to the CA pod only?</li>
<li>If I deploy a pod (for example nginx) and I deploy it without specifying resources requests & limits in the pod's configuration, will the CA know how much resources nginx needs and allocate the proper amount?</li>
</ol>
| <p><a href="https://docs.aws.amazon.com/eks/latest/userguide/cluster-autoscaler.html" rel="nofollow noreferrer">Documentation</a> is your friend:</p>
<ol>
<li>The limits and requests fields in the Cluster Autoscaler (which will basically be a Deployment on k8s)
definition will be valid for each pod that will be spawned with this
definition, unless the pods themselves have limits and requests
defined.</li>
<li>Which brings us to your second question: if a pod is spawned based on a config file without
limits & resources, the defaults will be those specified for the master node.</li>
</ol>
|
<p>after watching a view videos on RBAC (role based access control) on kubernetes (of which <a href="https://www.youtube.com/watch?v=U67OwM-e9rQ" rel="nofollow noreferrer">this one</a> was the most transparent for me), I've followed the steps, however on k3s, not k8s as all the sources imply. From what I could gather (not working), the problem isn't with the actual role binding process, but rather the x509 user cert which isn't acknowledged from the API service</p>
<blockquote>
<p>$ kubectl get pods --kubeconfig userkubeconfig</p>
<p>error: You must be logged in to the server (Unauthorized)</p>
</blockquote>
<p>Also not documented on <a href="https://rancher.com/docs/k3s/latest/en/security/" rel="nofollow noreferrer">Rancher's wiki</a> on security for K3s (while documented for their k8s implementation)?, while described for <a href="https://rancher.com/docs/rancher/v2.x/en/admin-settings/rbac/" rel="nofollow noreferrer">rancher 2.x</a> itself, not sure if it's a problem with my implementation, or a k3s <-> k8s thing.</p>
<pre><code>$ kubectl version --short
Client Version: v1.20.5+k3s1
Server Version: v1.20.5+k3s1
</code></pre>
<hr />
<p><strong>With duplication of the process, my steps are as follows:</strong></p>
<ol>
<li>Get k3s ca certs</li>
</ol>
<p>This was described to be under <em>/etc/kubernetes/pki</em> (k8s), however based on <a href="https://www.reddit.com/r/kubernetes/comments/f69h3y/help_k3s_where_to_find_ca_certificate_files/" rel="nofollow noreferrer">this</a> seems to be at <em>/var/lib/rancher/k3s/server/tls/ (server-ca.crt & server-ca.key)</em>.</p>
<ol start="2">
<li>Gen user certs from ca certs</li>
</ol>
<pre><code>#generate user key
$ openssl genrsa -out user.key 2048
#generate signing request from ca
openssl req -new -key user.key -out user.csr -subj "/CN=user/O=rbac"
# generate user.crt from this
openssl x509 -req -in user.csr -CA server-ca.crt -CAkey server-ca.key -CAcreateserial -out user.crt -days 365
</code></pre>
<p>... all good:
<a href="https://i.stack.imgur.com/mBqwM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mBqwM.png" alt="enter image description here" /></a></p>
<ol start="3">
<li>Creating kubeConfig file for user, based on the certs:</li>
</ol>
<pre><code># Take user.crt and base64 encode to get encoded crt
cat user.crt | base64 -w0
# Take user.key and base64 encode to get encoded key
cat user.key | base64 -w0
</code></pre>
<ul>
<li>Created config file:</li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
clusters:
- cluster:
certificate-authority-data: <server-ca.crt base64-encoded>
server: https://<k3s masterIP>:6443
name: home-pi4
contexts:
- context:
cluster: home-pi4
user: user
namespace: rbac
name: user-homepi4
current-context: user-homepi4
kind: Config
preferences: {}
users:
- name: user
user:
client-certificate-data: <user.crt base64-encoded>
client-key-data: <user.key base64-encoded>
</code></pre>
<ol start="4">
<li>Setup role & roleBinding (within specified namespace 'rbac')</li>
</ol>
<ul>
<li>role</li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: user-rbac
namespace: rbac
rules:
- apiGroups:
- "*"
resources:
- pods
verbs:
- get
- list
</code></pre>
<ul>
<li>roleBinding</li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: user-rb
namespace: rbac
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: user-rbac
subjects:
apiGroup: rbac.authorization.k8s.io
kind: User
name: user
</code></pre>
<hr />
<p>After all of this, I get fun times of...</p>
<pre><code>$ kubectl get pods --kubeconfig userkubeconfig
error: You must be logged in to the server (Unauthorized)
</code></pre>
<p>Any suggestions please?</p>
<blockquote>
<p>Apparently this <a href="https://stackoverflow.com/questions/59940927/k3s-create-user-with-client-certificate">stackOverflow question</a> presented a solution to the problem, but following the github feed, it came more-or-less down to the same approach followed here (unless I'm missing something)?</p>
</blockquote>
| <p>As we can find in the <a href="https://kubernetes.io/docs/reference/access-authn-authz/certificate-signing-requests/#normal-user" rel="nofollow noreferrer">Kubernetes Certificate Signing Requests documentation</a>:</p>
<blockquote>
<p>A few steps are required in order to get a normal user to be able to authenticate and invoke an API.</p>
</blockquote>
<p><br>I will create an example to illustrate how you can get a normal user who is able to authenticate and invoke an API (I will use the user <code>john</code> as an example).</p>
<hr />
<p>First, create PKI private key and CSR:</p>
<pre><code># openssl genrsa -out john.key 2048
</code></pre>
<p><strong>NOTE:</strong> <code>CN</code> is the name of the user and <code>O</code> is the group that this user will belong to</p>
<pre><code># openssl req -new -key john.key -out john.csr -subj "/CN=john/O=group1"
# ls
john.csr john.key
</code></pre>
<p>Then create a <code>CertificateSigningRequest</code> and submit it to a Kubernetes Cluster via <code>kubectl</code>.</p>
<pre><code># cat <<EOF | kubectl apply -f -
> apiVersion: certificates.k8s.io/v1
> kind: CertificateSigningRequest
> metadata:
> name: john
> spec:
> groups:
> - system:authenticated
> request: $(cat john.csr | base64 | tr -d '\n')
> signerName: kubernetes.io/kube-apiserver-client
> usages:
> - client auth
> EOF
certificatesigningrequest.certificates.k8s.io/john created
# kubectl get csr
NAME AGE SIGNERNAME REQUESTOR CONDITION
john 39s kubernetes.io/kube-apiserver-client system:admin Pending
# kubectl certificate approve john
certificatesigningrequest.certificates.k8s.io/john approved
# kubectl get csr
NAME AGE SIGNERNAME REQUESTOR CONDITION
john 52s kubernetes.io/kube-apiserver-client system:admin Approved,Issued
</code></pre>
<p>Export the issued certificate from the <code>CertificateSigningRequest</code>:</p>
<pre><code># kubectl get csr john -o jsonpath='{.status.certificate}' | base64 -d > john.crt
# ls
john.crt john.csr john.key
</code></pre>
<p>With the certificate created, we can define the <code>Role</code> and <code>RoleBinding</code> for this user to access Kubernetes cluster resources. I will use the <code>Role</code> and <code>RoleBinding</code> similar to yours.</p>
<pre><code># cat role.yml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: john-role
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
# kubectl apply -f role.yml
role.rbac.authorization.k8s.io/john-role created
# cat rolebinding.yml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: john-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: john-role
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: john
# kubectl apply -f rolebinding.yml
rolebinding.rbac.authorization.k8s.io/john-binding created
</code></pre>
<p>The last step is to add this user into the kubeconfig file (see: <a href="https://kubernetes.io/docs/reference/access-authn-authz/certificate-signing-requests/#add-to-kubeconfig" rel="nofollow noreferrer">Add to kubeconfig</a>)</p>
<pre><code># kubectl config set-credentials john --client-key=john.key --client-certificate=john.crt --embed-certs=true
User "john" set.
# kubectl config set-context john --cluster=default --user=john
Context "john" created.
</code></pre>
<p>Finally, we can change the context to <code>john</code> and check if it works as expected.</p>
<pre><code># kubectl config use-context john
Switched to context "john".
# kubectl config current-context
john
# kubectl get pods
NAME READY STATUS RESTARTS AGE
web 1/1 Running 0 30m
# kubectl run web-2 --image=nginx
Error from server (Forbidden): pods is forbidden: User "john" cannot create resource "pods" in API group "" in the namespace "default"
</code></pre>
<p>As you can see, it works as expected (user <code>john</code> only has <code>get</code> and <code>list</code> permissions).</p>
|
<p>I have question about kubernetes ingress.</p>
<p>I want to use ingress with my Amazon account and/or private cloud and want to assign external IP.</p>
<p>It is possible to assign external ip for services :
<a href="http://kubernetes.io/docs/user-guide/services/#external-ips" rel="noreferrer">Services documentation - chapter external IP</a>
but cannot find a way to do that for Ingress : <a href="http://kubernetes.io/docs/user-guide/ingress/" rel="noreferrer">Ingress documentation</a>.</p>
<p>My question is direct especially to Kubernetes team.
Similar question was asked by Simon in this topic : <a href="https://stackoverflow.com/questions/37001557/how-to-force-ssl-for-kubernetes-ingress-on-gke">How to force SSL for Kubernetes Ingress on GKE 2</a>
but he asked about GKE while I am interested in private cloud, AWS.</p>
<p>Thank you in advance.</p>
<p>[UPDATE]</p>
<p>Guys found that my question may was answered already in <a href="https://stackoverflow.com/a/40164860/1342445">this</a> topic.
Actually answer that @anigosa put there is specific for GCloud.
His solution won't work in private cloud neither in AWS cloud. In my opinion the reason for that is that he use <code>type: LoadBalancer</code> (which cannot be used in private cloud) and use <code>loadBalancerIP property</code> which will works only on GCloud(for AWS it cause error : "Failed to create load balancer for service default/nginx-ingress-svc: LoadBalancerIP cannot be specified for AWS ELB
"). </p>
| <p>Looking at this <a href="https://github.com/kubernetes-sigs/aws-load-balancer-controller/issues/1867" rel="nofollow noreferrer">issue</a>, it seems you can define annotation on your service and map it to existing <a href="https://aws.amazon.com/premiumsupport/knowledge-center/intro-elastic-ip-addresses/#:%7E:text=An%20Elastic%20IP%20address%20is,Allocating%20an%20Elastic%20IP%20Address." rel="nofollow noreferrer">elastic ip</a>.
Something like that:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
name: my-service
annotations:
service.beta.kubernetes.io/aws-load-balancer-eip-allocations: <>
spec:
type: LoadBalancer
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 9376
</code></pre>
<p>Please note this will create ELB for this service, not ingress.</p>
<p>As an ingress is simply one service (=ELB) handling requests for many other services, it should be possible to do something similar for ingress, but I couldn't find any docs for it.</p>
|
<p>I have several apps of different shapes and purposes, each with their own <code>templates/</code> folder as generated by <code>helm create chart</code>. The templates within each App are sufficiently different to justify having them as one-offs. However, the <code>_helpers.tpl</code> is identical for all of them. I'd like to externalize/reuse this <code>_helpers.tpl</code> template so that I don't need a copy of it in every app.</p>
<p>What I have currently looks something like this:</p>
<pre><code>App1
|--app (random source code crap, irrelevant)
|--chart
|---templates
|------_helpers.tpl
|------ deployment.yaml
|------ other unique templates
App2
|--app (random source code crap, irrelevant)
|--chart
|---templates
|------_helpers.tpl
|------ deployment.yaml
|------ other unique templates
</code></pre>
<p>I'd like to centralize this <code>_helpers.tpl</code> so that I don't need to maintain N versions of it. I'm imagining something like this, but I'm open to whatever:</p>
<pre><code>Common
|--chart
|----templates
|------ _helpers.tpl (I live here now and was removed from the 2 Apps below)
App1
|-- app (random source code crap, irrelevant)
|-- chart
|--- templates
|------ deployment.yaml
|------ other unique templates
App2
|-- app (random source code crap, irrelevant)
|-- chart
|--- templates
|------ deployment.yaml
|------ other unique templates
</code></pre>
<p>I have tried doing this with a symlink pointing <code>AppN/chart/templates/_helper.tpl</code> to <code>Common/chart/templates/_helper.tpl</code> but that's clearly bad and I imagine there's a built-in way to do this that I'm just not finding.</p>
<p>Even if <code>AppN/chart/templates/_helpers.tpl</code> needs to exist only to read <code>../../_helpers.tpl</code>, that's good enough but I'm not sure how to approach that given the YAML-y/Go-y syntax.</p>
| <p>I wound up solving this by inverting my file structure into something like:</p>
<pre><code>Parent App
|--Chart.yaml // new
|--values.yaml // new
|--templates // new
|----_helpers.tpl // automagically gets referenced in charts/*/templates
|--apps (source code stuff, irrelevant)
|--charts
|----App1
|------Chart.yaml
|------values.yaml
|------templates
|--------deployment.yaml (and others)
|----App2
|------Chart.yaml
|------values.yaml
|------templates
|--------deployment.yaml (and others)
</code></pre>
<p>Which follows the "subchart" pattern outlined here more closely: <a href="https://helm.sh/docs/chart_template_guide/subcharts_and_globals/" rel="nofollow noreferrer">https://helm.sh/docs/chart_template_guide/subcharts_and_globals/</a></p>
<p>Even though these are independent charts, not dependencies on some parent chart like this structure would indicate, this is good enough for me.</p>
|
<p>I have deployed ingress-nginx helm chart ( 3.20.1 , <a href="https://github.com/kubernetes/ingress-nginx/tree/master/charts/ingress-nginx" rel="nofollow noreferrer">https://github.com/kubernetes/ingress-nginx/tree/master/charts/ingress-nginx</a> ) into k8s cluster.</p>
<p>Some of the Ingresses configured for applications use basic auth - which works as expected.
I.e. I can access some applications in the cluster without basic auth ( as configured )
and some applications require dedicated basic auth credentials ( as configured ).</p>
<p>But trying an unknown/unsupported URL/Path is handled awkward by default-backend.
Somehow the default backend is now requiring basic auth too ( as one of the ingress with basic-auth ) ?</p>
<p>How can I find out why/where this basic auth kicks in when it shouldn't ?
I do want default-backend to serve error pages for 404 without basic auth !</p>
<pre><code>$ kubectl -n ingress get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
ingress-nginx-controller LoadBalancer 10.0.235.5 xx.yy.zzz.zzz 80:31294/TCP,443:31732/TCP 39d
ingress-nginx-controller-admission ClusterIP 10.0.190.204 <none> 443/TCP 39d
ingress-nginx-controller-metrics ClusterIP 10.0.21.184 <none> 9913/TCP 12d
ingress-nginx-defaultbackend ClusterIP 10.0.109.195 <none> 80/TCP 39d
</code></pre>
<p>Currently deployed Ingresses:</p>
<pre><code>$ kubectl get ingress -A
Warning: extensions/v1beta1 Ingress is deprecated in v1.14+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress
NAMESPACE NAME CLASS HOSTS ADDRESS PORTS AGE
dev-app-a app-a <none> my-host.com xx.yy.zzz.zzz 80, 443 46d
dev-jaeger jaeger <none> my-host.com xx.yy.zzz.zzz 80, 443 47d
dev-app-b app-b <none> my-host.com xx.yy.zzz.zzz 80, 443 17d
dev-app-c app-c <none> my-host.com xx.yy.zzz.zzz 80, 443 12d
dev-app-d app-d <none> my-host.com xx.yy.zzz.zzz 80, 443 4d22h
prom prometheus-grafana <none> my-other-host.com xx.yy.zzz.zzz 80, 443 20d
prom prometheus-kube-prometheus-alertmanager <none> my-other-host.com xx.yy.zzz.zzz 80, 443 20d
prom prometheus-kube-prometheus-prometheus <none> my-other-host.com xx.yy.zzz.zzz 80, 443 20d
stage-app-a app-a <none> my-third-host.com xx.yy.zzz.zzz 80, 443 39d
stage-jaeger jaeger <none> my-third-host.com xx.yy.zzz.zzz 80, 443 39d
</code></pre>
<p>Ingress details:</p>
<pre><code>apiVersion: v1
items:
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
labels:
app.kubernetes.io/name: app-a
name: app-a
namespace: foo-app-a
spec:
rules:
- host: my-host.com
http:
paths:
- backend:
serviceName: app-a-http
servicePort: http
path: /abc/
pathType: ImplementationSpecific
tls:
- hosts:
- my-host.com
secretName: app-a-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/add-base-url: "true"
nginx.ingress.kubernetes.io/auth-realm: Authentication Required - Jaeger UI
nginx.ingress.kubernetes.io/auth-secret: jaeger-basic-auth
nginx.ingress.kubernetes.io/auth-type: basic
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
labels:
app.kubernetes.io/name: jaeger
name: jaeger
namespace: dev-jaeger
spec:
rules:
- host: my-host.com
http:
paths:
- backend:
serviceName: jaeger
servicePort: http-ui
path: /jaeger/
pathType: ImplementationSpecific
tls:
- hosts:
- my-host.com
secretName: jaeger-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
nginx.ingress.kubernetes.io/rewrite-target: /$1
labels:
app.kubernetes.io/name: app-b
name: app-b
namespace: dev-app-b
spec:
rules:
- host: my-host.com
http:
paths:
- backend:
serviceName: app-b
servicePort: http
path: /app-b/(.*)
pathType: ImplementationSpecific
tls:
- hosts:
- my-host.com
secretName: app-b-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
nginx.ingress.kubernetes.io/rewrite-target: /$1
labels:
app.kubernetes.io/name: app-c
name: app-c
namespace: dev-app-c
spec:
rules:
- host: my-host.com
http:
paths:
- backend:
serviceName: app-c
servicePort: http
path: /app-c/(.*)
pathType: ImplementationSpecific
tls:
- hosts:
- my-host.com
secretName: app-c-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
meta.helm.sh/release-name: prometheus
meta.helm.sh/release-namespace: prom
nginx.ingress.kubernetes.io/add-base-url: "true"
nginx.ingress.kubernetes.io/auth-realm: Authentication Required - Grafana UI
nginx.ingress.kubernetes.io/auth-secret: monitoring-basic-auth
nginx.ingress.kubernetes.io/auth-type: basic
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
labels:
app.kubernetes.io/instance: prometheus
app.kubernetes.io/managed-by: Helm
app.kubernetes.io/name: grafana
app.kubernetes.io/version: 7.4.2
helm.sh/chart: grafana-6.4.8
name: prometheus-grafana
namespace: prom
spec:
rules:
- host: my-other-host.com
http:
paths:
- backend:
serviceName: prometheus-grafana
servicePort: 80
path: /monitoring/grafana/
pathType: ImplementationSpecific
tls:
- hosts:
- my-other-host.com
secretName: prometheus-general-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
meta.helm.sh/release-name: prometheus
meta.helm.sh/release-namespace: prom
nginx.ingress.kubernetes.io/auth-realm: Authentication Required - AlertManager UI
nginx.ingress.kubernetes.io/auth-secret: monitoring-basic-auth
nginx.ingress.kubernetes.io/auth-type: basic
labels:
app: kube-prometheus-stack-alertmanager
app.kubernetes.io/managed-by: Helm
chart: kube-prometheus-stack-14.0.1
heritage: Helm
release: prometheus
name: prometheus-kube-prometheus-alertmanager
namespace: prom
spec:
rules:
- host: my-other-host.com
http:
paths:
- backend:
serviceName: prometheus-kube-prometheus-alertmanager
servicePort: 9093
path: /monitoring/alertmanager/
pathType: ImplementationSpecific
tls:
- hosts:
- my-other-host.com
secretName: prometheus-general-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
meta.helm.sh/release-name: prometheus
meta.helm.sh/release-namespace: prom
nginx.ingress.kubernetes.io/auth-realm: Authentication Required - Prometheus UI
nginx.ingress.kubernetes.io/auth-secret: monitoring-basic-auth
nginx.ingress.kubernetes.io/auth-type: basic
labels:
app: kube-prometheus-stack-prometheus
app.kubernetes.io/managed-by: Helm
chart: kube-prometheus-stack-14.0.1
heritage: Helm
release: prometheus
name: prometheus-kube-prometheus-prometheus
namespace: prom
spec:
rules:
- host: my-other-host.com
http:
paths:
- backend:
serviceName: prometheus-kube-prometheus-prometheus
servicePort: 9090
path: /monitoring/prometheus/
pathType: ImplementationSpecific
tls:
- hosts:
- my-other-host.com
secretName: prometheus-general-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
labels:
app.kubernetes.io/managed-by: terraform
app.kubernetes.io/name: app-a
name: app-a
namespace: stage-app-a
spec:
rules:
- host: my-third-host.com
http:
paths:
- backend:
serviceName: app-a-http
servicePort: http
path: /controller/
pathType: ImplementationSpecific
tls:
- hosts:
- my-third-host.com
secretName: app-a-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
- apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/add-base-url: "true"
nginx.ingress.kubernetes.io/auth-realm: Authentication Required - Jaeger UI
nginx.ingress.kubernetes.io/auth-secret: jaeger-basic-auth
nginx.ingress.kubernetes.io/auth-type: basic
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
labels:
app.kubernetes.io/name: jaeger
name: jaeger
namespace: stage-jaeger
spec:
rules:
- host: my-third-host.com
http:
paths:
- backend:
serviceName: jaeger
servicePort: http-ui
path: /jaeger/
pathType: ImplementationSpecific
tls:
- hosts:
- my-third-host.com
secretName: jaeger-tls
status:
loadBalancer:
ingress:
- ip: xx.xx.xx.xx
</code></pre>
<p>E.g. trying a simple curl on an unknown path ( where I would expect default backend to given 404 response ) returns data that is coming from my Prometheus endpoint being basic auth protected :</p>
<p>(The real hostname/ip has been obfuscated by me !)</p>
<pre><code>$ curl -v "https://my-other-host.com/bar"
* Trying xx.xx.xx.xx...
* TCP_NODELAY set
* Connected to my-other-host.com (xx.xx.xx.xx) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/cert.pem
CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: CN=my-other-host.com
* start date: Apr 6 14:28:20 2021 GMT
* expire date: Jul 5 14:28:20 2021 GMT
* subjectAltName: host "my-other-host.com" matched cert's "my-other-host.com"
* issuer: C=US; O=Let's Encrypt; CN=R3
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7fec1300d600)
> GET /bar HTTP/2
> Host: my-other-host.com
> User-Agent: curl/7.64.1
> Accept: */*
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 401
< date: Wed, 21 Apr 2021 15:37:24 GMT
< content-type: text/html
< content-length: 172
< www-authenticate: Basic realm="Authentication Required - Prometheus UI"
< strict-transport-security: max-age=15724800; includeSubDomains
<
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx</center>
</body>
</html>
* Connection #0 to host my-other-host.com left intact
* Closing connection 0
</code></pre>
<p>or similar when trying on the other host I'll get 401 from something that looks like my Jaeger endpoint instead of default-backend 404:</p>
<pre><code>$ curl -v "https://my-host.com/foo"
* Trying xx.xx.xx.xx...
* TCP_NODELAY set
* Connected to my-host.com (xx.xx.xx.xx) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/cert.pem
CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: CN=my-host.com
* start date: Mar 18 06:37:40 2021 GMT
* expire date: Jun 16 06:37:40 2021 GMT
* subjectAltName: host "my-host.com" matched cert's "my-host.com"
* issuer: C=US; O=Let's Encrypt; CN=R3
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7f968480d600)
> GET /foo HTTP/2
> Host: my-host.com
> User-Agent: curl/7.64.1
> Accept: */*
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 401
< date: Wed, 21 Apr 2021 15:59:21 GMT
< content-type: text/html
< content-length: 172
< www-authenticate: Basic realm="Authentication Required - Jaeger UI"
< strict-transport-security: max-age=15724800; includeSubDomains
<
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx</center>
</body>
</html>
* Connection #0 to host my-host.com left intact
* Closing connection 0
</code></pre>
| <p>Fixed ( or worked around the problem ) by explicitly adding an Ingress route for every host that gets served in the cluster:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
name: default-route-per-host
namespace: ingress
spec:
rules:
- host: my-host.com
http:
paths:
- backend:
service:
name: ingress-nginx-defaultbackend
port:
name: http
path: /
pathType: Prefix
- host: my-other-host.com
http:
paths:
- backend:
service:
name: ingress-nginx-defaultbackend
port:
name: http
path: /
pathType: Prefix
- host: my-third-host.com
http:
paths:
- backend:
service:
name: ingress-nginx-defaultbackend
port:
name: http
path: /
pathType: Prefix
</code></pre>
|
<p>I'm using Ubuntu 20.04.2 LTS. I installed microk8s 1.20.6 rev 2143 and experimenting with ingress. I must be missing something - but it doesn't work as I expect it to. I tracked the strange behavior down to the following configuration:</p>
<p>ingress.yaml:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ubuntu
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: my-ubuntu
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: nginx
port:
number: 80
- path: /nginx
pathType: Prefix
backend:
service:
name: nginx
port:
number: 80
</code></pre>
<p>nginx-service.yaml:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
ports:
- port: 80
name: http
- port: 443
name: https
type: ClusterIP
selector:
app: nginx
</code></pre>
<p>Now,</p>
<pre class="lang-sh prettyprint-override"><code>curl my-ubuntu/ # this returns Welcome page, as expected
curl my-ubuntu/nginx # this returns Welcome page, as expected
curl my-ubuntu/bad-page.html # this returns 404 Not Found, as expected
curl my-ubuntu/nginx/bad-page.html # this returns Welcome page. WHY?
</code></pre>
<p>Any request under my-ubuntu/nginx/* returns Welcome page, even when the url is correct and should have returned different content. Did I configure something wrong?</p>
<p>I was able to reproduce the same strange behavior using Docker for Windows + WSL2 + Ubuntu + ingress installed using:</p>
<pre class="lang-sh prettyprint-override"><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v0.41.2/deploy/static/provider/cloud/deploy.yaml
</code></pre>
<p><strong>EDIT</strong></p>
<p>nginx-deployment.yaml I used:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 1
revisionHistoryLimit: 0
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
</code></pre>
<p>When I try <code>/nginx/</code> instead of <code>/nginx</code> like @HarshManvar suggested, I get this behavior:</p>
<pre class="lang-sh prettyprint-override"><code>curl my-ubuntu/ # this returns Welcome page, as expected
curl my-ubuntu/bad-page.html # this returns 404 Not Found, as expected
curl my-ubuntu/nginx # this returns 404 Not Found
curl my-ubuntu/nginx/ # this returns Welcome page
curl my-ubuntu/nginx/bad-page.html # this returns Welcome page
</code></pre>
<p><a href="https://kubernetes.io/docs/concepts/services-networking/ingress/#simple-fanout" rel="nofollow noreferrer">Kubernetes Ingress documentation about Simple fanout</a> also does use <code>/nginx</code> pattern but not working as described above.</p>
| <p><a href="https://kubernetes.github.io/ingress-nginx/examples/rewrite/" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/examples/rewrite/</a> explains how to use <code>rewrite-target</code> annotation. I was able to make it work with the following ingress.yaml:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ubuntu
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: localhost
http:
paths:
- path: /(.*)
pathType: Prefix
backend:
service:
name: nginx
port:
number: 80
- path: /nginx($|/.*)
pathType: Prefix
backend:
service:
name: nginx
port:
number: 80
</code></pre>
<p>Each <code>path</code> defines regular expression with <code>( )</code>, which yields <code>$1</code>, <code>$2</code>, etc., aka. regex capture group variables. Now you put <code>rewrite-target</code> using those variables, and that will be the actual URL that is passed to the service's container that handles the request.</p>
<p>Maybe there is another way, but this is the only way I was able to make it work.</p>
|
<p>I'm applying aws-efs-csi driver like this on a kubernates cluster:</p>
<pre><code>kubectl apply -k "github.com/kubernetes-sigs/aws-efs-csi-driver/deploy/kubernetes/overlays/stable/?ref=release-1.0"
</code></pre>
<p>I need to edit the configuration file to add credentials for pulling docker images.</p>
<p>I couldn't find ways to edit via kubectl edit ..</p>
<p>This is the pod in the kube-system namespace:</p>
<pre><code># kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
...
kube-system efs-csi-node-xxssqr 3/3 Running 0 69d
...
</code></pre>
| <p>It’s a daemonset.</p>
<p><code>kubectl -n kube-system edit ds/efs-csi-node</code></p>
|
<p>I'm playing with the Elasticsearch operator Kubernetes and created two stateful sets (see <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-orchestration.html" rel="nofollow noreferrer">https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-orchestration.html</a>):</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: elasticsearch.k8s.elastic.co/v1
kind: Elasticsearch
metadata:
name: quickstart
spec:
version: 7.12.1
nodeSets:
- name: master-nodes
count: 3
config:
node.roles: ["master"]
volumeClaimTemplates:
- metadata:
name: elasticsearch-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: standard
- name: data-nodes
count: 3
config:
node.roles: ["data"]
volumeClaimTemplates:
- metadata:
name: elasticsearch-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: standard
</code></pre>
<p>The problem is that I cannot delete the stateful sets. After deletion, they're recreated automatically:</p>
<pre><code>my-PC:~$ kubectl get sts
NAME READY AGE
quickstart-es-data-nodes 0/0 14m
quickstart-es-master-nodes 0/0 18m
my-PC:~$ kubectl delete sts quickstart-es-data-nodes --force --grace-period=0
warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
statefulset.apps "quickstart-es-data-nodes" force deleted
my-PC:~$ kubectl get sts
NAME READY AGE
quickstart-es-data-nodes 0/3 3s
quickstart-es-master-nodes 0/0 18m
</code></pre>
<p>Before deletion I already scaled down the statefulset to 0 to ensure that all pods are terminated. But after deletion, the stateful is recreated (see quickstart-es-data-nodes).</p>
<p>So, anyone having any idea how I can delete the stateful sets without being recreated?</p>
| <p>it's due to the operator you are using for the Elasticsearch. Operator manage the <strong>statefulset</strong> and will update if you delete it.</p>
<blockquote>
<p>Behind the scenes, ECK translates each NodeSet specified in the
Elasticsearch resource into a StatefulSet in Kubernetes.</p>
</blockquote>
<p>if you read the documentation: <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-orchestration.html#k8s-statefulsets" rel="nofollow noreferrer">https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-orchestration.html#k8s-statefulsets</a></p>
<p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#on-delete" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#on-delete</a></p>
|
<p>I want to install several private python packages when I create an instance (AI platform).</p>
<p>I had the following startup script but it did not install what I needed (but also didnt show any errors):</p>
<p>startup_script.sh:</p>
<p><code>pip install my_custom_libraries</code></p>
<p>why does it not work and what do I need to do to make it work?</p>
| <p>you check the start up script logs at :</p>
<pre><code>Compute Engine > (Your Instance Name) > Logs > Serial port 1 (console)
</code></pre>
<p>also, I am not sure your install have by default python and pip installed ?</p>
<p>startup_script.sh:</p>
<pre><code>#! /bin/bash
apt-get update
apt-get install -yq git python python-pip
pip install --upgrade pip virtualenv
pip install my_custom_libraries
</code></pre>
<p>check your python and pip set at the proper path</p>
|
<p>We have configured Grafana <code>user</code> and <code>admin</code> roles using <code>Grafana.ini</code> which works great.</p>
<p>Now we want to provide some permission to user to
see <strong>specific dashboards</strong>, e.g. user X can see 5 dashboard and user Y can see 8 dashboards according to some configurations (permissions).</p>
<p>We were able to keep this config in Grafana UI but if the pod (K8S) is fail the details is deleted, we are using latest <a href="https://github.com/grafana/helm-charts" rel="nofollow noreferrer">prom helm</a> .</p>
<p>My question is how should we
store this data right, even if the pod is restarted?</p>
<p><a href="https://grafana.com/docs/grafana/latest/permissions/dashboard-folder-permissions/" rel="nofollow noreferrer">https://grafana.com/docs/grafana/latest/permissions/dashboard-folder-permissions/</a></p>
<p><a href="https://github.com/grafana/helm-charts" rel="nofollow noreferrer">https://github.com/grafana/helm-charts</a></p>
<p><a href="https://github.com/grafana/helm-charts/blob/main/charts/grafana/values.yaml#L253" rel="nofollow noreferrer">https://github.com/grafana/helm-charts/blob/main/charts/grafana/values.yaml#L253</a></p>
<p>Any solution/direction will be helpful as I believe that grafana store this data someware but not sure where ...</p>
<p>I found this link which is talking about the store of the users on database etc
<a href="https://grafana.com/docs/grafana/latest/administration/configuration/#database" rel="nofollow noreferrer">https://grafana.com/docs/grafana/latest/administration/configuration/#database</a></p>
<p>Not sure what is missing as the data should be kept in k8s volume...
If there is any other solution or a way to solve it please let me know.</p>
| <p>You need to deploy your Grafana instance with a persistent storage. Either:</p>
<ul>
<li>Keep using the built-in sqlite db - just ensure to use <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/" rel="nofollow noreferrer">PVC</a> to store it's data. The default path can be set using this <a href="https://grafana.com/docs/grafana/latest/administration/configuration/#data" rel="nofollow noreferrer">config property</a></li>
<li>Use external db, like SQL, and configure Grafana to talk with it. See the <a href="https://grafana.com/docs/grafana/latest/administration/configuration/#database" rel="nofollow noreferrer">database</a> config section for more details.</li>
</ul>
<p>Grafana persistency will be used to persist other settings as well, and also persist dashboards, alerts etc.
All settings can be set via the <code>grafana.ini</code> helm chart variable</p>
|
<p>I deployed istio/bookinfo on kubernetes, and I want to install stress on the microservice container to inject fault. However, When I use</p>
<pre><code>kubectl exec -it reviews-v1-f55d74d54-kpxr2 -c reviews --username=root -- /bin/bash
</code></pre>
<p>to log in the container, it show that the user is still default. and the command 'apt-get' got</p>
<pre><code>default@reviews-v2-6f4995984d-4752v:/$ apt-get update
Reading package lists... Done
E: List directory /var/lib/apt/lists/partial is missing. - Acquire (13: Permission denied)
</code></pre>
<p>I tried to use 'su root' but I don't know the answer.
I searched some answer say that I can use 'docker exec', it works but it is not convenient, so I want to know how to log in the container by use the command kubectl exec.</p>
| <p>This is not supported.</p>
<p>Source code suggests it's a TODO feature: <a href="https://github.com/kubernetes/kubectl/blob/a0af655b7abaf06983c99ad5a4dc8f02ae5eb3e5/pkg/cmd/exec/exec.go#L100" rel="noreferrer">kubernetes/kubectl/pkg/cmd/exec/exec.go</a></p>
<p>The <code>--username</code> flag explained by kubectl:</p>
<pre><code>➜ ~ kubectl options | grep user
--user='': The name of the kubeconfig user to use
--username='': Username for basic authentication to the API server
</code></pre>
<p>As you probably see, none of the user flags can change user/UID for exec.</p>
<p>All flags supported by exec command:</p>
<pre><code>➜ ~ kubectl exec --help
[...]
Options:
-c, --container='': Container name. If omitted, the first container in the pod will be chosen
-f, --filename=[]: to use to exec into the resource
--pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running
-i, --stdin=false: Pass stdin to the container
-t, --tty=false: Stdin is a TTY
</code></pre>
<p>Additionally, apt-get update is best to be run at build time, not at a run time.</p>
<p>It is a good practise to keep your containers immutable. For testing purpouses you should stick with docker exec because ther is no other known alternative.</p>
<p>Also, If you have a specific problem to solve, explain the problem, not the solution. <a href="https://xyproblem.info/" rel="noreferrer">xyproblem</a></p>
|
<p>Two years ago while I took CKA exam, I already have this question. At that time I only could do was to see k8s.io official documentation. Now just curious on generating pv / pvc / storageClass via pure kubectl cli. What I look for is similar to the similar logic as deployment, for example:</p>
<pre><code>$ kubectl create deploy test --image=nginx --port=80 --dry-run -o yaml
W0419 23:54:11.092265 76572 helpers.go:553] --dry-run is deprecated and can be replaced with --dry-run=client.
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
app: test
name: test
spec:
replicas: 1
selector:
matchLabels:
app: test
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
app: test
spec:
containers:
- image: nginx
name: nginx
ports:
- containerPort: 80
resources: {}
status: {}
</code></pre>
<p>Or similar logic to run a single pod:</p>
<pre><code>$ kubectl run test-pod --image=nginx --port=80 --dry-run -o yaml
W0419 23:56:29.174692 76654 helpers.go:553] --dry-run is deprecated and can be replaced with --dry-run=client.
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: test-pod
name: test-pod
spec:
containers:
- image: nginx
name: test-pod
ports:
- containerPort: 80
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}
</code></pre>
<p>So what should I type in order to generate pv / pvc / storageClass yaml? The current only declarative fastest way:</p>
<pre><code>cat <<EOF | kubectl create -f -
<PV / PVC / storageClass yaml goes here>
EOF
</code></pre>
<p>Edited: Please note that I look any fast way to generate correct pv / pvc / storageClass template without remembering specific syntax thru cli, and not necessary via kubectl.</p>
| <h2>TL;DR:</h2>
<p>Look, bookmark and build index your brain in all yaml files in this Github directory (content/en/examples/pods) before the exam. 100% legal according to CKA curriculum.</p>
<p><a href="https://github.com/kubernetes/website/tree/master/content/en/examples/pods/storage/pv-volume.yaml" rel="nofollow noreferrer">https://github.com/kubernetes/website/tree/master/content/en/examples/pods/storage/pv-volume.yaml</a></p>
<p>Then use this form during exam:</p>
<pre><code>kubectl create -f https://k8s.io/examples/pods/storage/pv-volume.yaml
</code></pre>
<p>In case you need edit and apply:</p>
<pre><code># curl
curl -sL https://k8s.io/examples/pods/storage/pv-volume.yaml -o /your/path/pv-volume.yaml
# wget
wget -O /your/path/pv-volume.yaml https://k8s.io/examples/pods/storage/pv-volume.yaml
vi /your/path/pv-volume.yaml
kubectl apply -f /your/path/pv-volume.yaml
</code></pre>
<h2>Story:</h2>
<p>Actually after look around for my own answer, there's an article floating around that suggest me to bookmark these 100% legal pages:</p>
<p><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/#create-a-persistentvolume" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/#create-a-persistentvolume</a></p>
<p><a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/#creating-a-cron-job" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/#creating-a-cron-job</a></p>
<p><a href="https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/</a></p>
<p>Note that:</p>
<pre><code>kubectl apply -f https://k8s.io/examples/pods/storage/pv-volume.yaml
</code></pre>
<ol>
<li>kubectl could create objects from URL</li>
<li>Where is the original <a href="https://k8s.io" rel="nofollow noreferrer">https://k8s.io</a> pointing to?</li>
<li>What else I could benefit from?</li>
</ol>
<p>Then after digging up the page above "pods/storage/pv-volume.yaml" code, the link points to:</p>
<p><a href="https://raw.githubusercontent.com/kubernetes/website/master/content/en/examples/pods/storage/pv-volume.yaml" rel="nofollow noreferrer">https://raw.githubusercontent.com/kubernetes/website/master/content/en/examples/pods/storage/pv-volume.yaml</a></p>
<p>Which direct to:</p>
<p><a href="https://github.com/kubernetes/website/tree/master/content/en/examples/pods" rel="nofollow noreferrer">https://github.com/kubernetes/website/tree/master/content/en/examples/pods</a></p>
<p>So <a href="https://k8s.io" rel="nofollow noreferrer">https://k8s.io</a> is a shorten uri as well as a http 301 redirect to <a href="https://github.com/kubernetes/website/tree/master/content/en" rel="nofollow noreferrer">https://github.com/kubernetes/website/tree/master/content/en</a> to help the exam candidate easy to produce (not copy-n-paste) in the exam terminal.</p>
|
<p>This might be simple, but I can't seem to figure out why a bash script mounted as a configmap cannot be ran as root:</p>
<pre><code>root@myPodId:/opt/nodejs-app# ls -alh /path/fileName
lrwxrwxrwx 1 root root 18 Sep 10 09:33 /path/fileName -> ..data/fileName
root@myPodId:/opt/nodejs-app# whoami
root
root@myPodId:/opt/nodejs-app# /bin/bash -c /path/fileName
/bin/bash: /path/fileName: Permission denied
</code></pre>
<p>I'm guessing, but I'd think that as with Docker, the root in the container isn't the actual root and works more like a pseudo-root account.</p>
<p>If that's the case, and the file cannot be ran this way, how would you include the script without having to re-create the Docker container every time the script changes?</p>
| <p>See here: <a href="https://github.com/kubernetes/kubernetes/issues/71356#issuecomment-441169334" rel="noreferrer">https://github.com/kubernetes/kubernetes/issues/71356#issuecomment-441169334</a></p>
<p>You need to set the defaultMode on the ConfigMap to the permissions you are asking for:</p>
<pre><code>volumes:
- name: test-script
configMap:
name: test-script
defaultMode: 0777
</code></pre>
|
<p>I have 2 EKS clusters, in 2 different AWS accounts and with, I might assume, different firewalls (which I don't have access to). The first one (Dev) is all right, however, with the same configuration, UAT cluster pods is struggling to resolve DNS. The Nodes can resolve and seems to be all right.</p>
<p>1) ping 8.8.8.8 works</p>
<pre><code>--- 8.8.8.8 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3003ms
</code></pre>
<p>2) I can ping the IP of google (and others), but not the actual dns names.</p>
<p>Our configuration:</p>
<ol>
<li>configured with Terraform.</li>
<li>The worker nodes and control plane SG are the same than the dev ones. I believe those are fine.</li>
<li>Added 53 TCP and 53 UDP on inbound + outbound NACl (just to be sure 53 was really open...). Added 53 TCP and 53 UDP outbound from Worker Nodes.</li>
<li>We are using <code>ami-059c6874350e63ca9</code> with 1.14 kubernetes version.</li>
</ol>
<p>I am unsure if the problem is a firewall somewhere, coredns, my configuration that needs to be updated or an "stupid mistake". Any help would be appreciated.</p>
| <p>Note that this issue may present itself in many forms (e.g. DNS not resolving is just one possible case). The <code>terraform-awk-eks</code> module exposes a terraform input to create the necessary security group rules that allow these inter worker-group/node-group communications: <code>worker_create_cluster_primary_security_group_rules</code>. More information in this <code>terraform-awk-eks</code> issue <a href="https://github.com/terraform-aws-modules/terraform-aws-eks/issues/1089" rel="nofollow noreferrer">https://github.com/terraform-aws-modules/terraform-aws-eks/issues/1089</a></p>
<p>When the input is enabled, terraform creates the following security group rules:</p>
<pre><code> # module.eks.module.eks.aws_security_group_rule.cluster_primary_ingress_workers[0] will be created
+ resource "aws_security_group_rule" "cluster_primary_ingress_workers" {
+ description = "Allow pods running on workers to send communication to cluster primary security group (e.g. Fargate pods)."
+ from_port = 0
+ id = (known after apply)
+ protocol = "-1"
+ security_group_id = "sg-03bb33d3318e4aa03"
+ self = false
+ source_security_group_id = "sg-0fffc4d49a499a1d8"
+ to_port = 65535
+ type = "ingress"
}
# module.eks.module.eks.aws_security_group_rule.workers_ingress_cluster_primary[0] will be created
+ resource "aws_security_group_rule" "workers_ingress_cluster_primary" {
+ description = "Allow pods running on workers to receive communication from cluster primary security group (e.g. Fargate pods)."
+ from_port = 0
+ id = (known after apply)
+ protocol = "-1"
+ security_group_id = "sg-0fffc4d49a499a1d8"
+ self = false
+ source_security_group_id = "sg-03bb33d3318e4aa03"
+ to_port = 65535
+ type = "ingress"
}
</code></pre>
|
<p>I am building my <em>docker</em> image and then deploy using <em>kubernetes</em>.</p>
<p>When I execute the command:</p>
<pre><code>kubectl get pods
NAME READY STATUS RESTARTS AGE
lmhfhfhf-def-abc 0/1 Error 0 2m
</code></pre>
<p>I am almost sure that, it's because of my code changes. How do I debug this pod to find out the logical error in my code.</p>
<p>Please Help.</p>
| <p>Welcome to the community @witti_minds</p>
<p>@user2830517 and @andD have generally answered it, however I'd like to add a bit more details and sources.</p>
<p>Your pod is crashed, however since it was scheduled, options used for running pods will work (<a href="https://kubernetes.io/docs/tasks/debug-application-cluster/debug-pod-replication-controller/#my-pod-is-crashing-or-otherwise-unhealthy" rel="nofollow noreferrer">k8s debug unhealthy pods</a>)</p>
<p>First you should get all information about your pod by running a following command, this will give you all information about your pod (<a href="https://kubernetes.io/docs/tasks/debug-application-cluster/debug-application-introspection/" rel="nofollow noreferrer">k8s pod inspection</a>):</p>
<pre><code>kubectl describe pod %pod_name%
</code></pre>
<p>Then you should do is to examine POD's logs using following command:</p>
<pre><code>kubectl logs lmhfhfhf-def-abc %container_name%
</code></pre>
<p>Container name is optional here, if your pod has more than 1 container, you have to use it.
Also you can check logs from previous state of the pod:</p>
<pre><code>kubectl logs --previous %pod_name% %container_name%
</code></pre>
<p>Once you have your container up and running, you can continue troubleshooting your application by running command directly in pod using <code>exec</code> command:</p>
<pre><code>kubectl exec -it %pod_name% -- sh
</code></pre>
<p>There are different types of possible troubleshooting methods, they are all described here <a href="https://kubernetes.io/docs/tasks/debug-application-cluster/debug-running-pod/" rel="nofollow noreferrer">k8s debugging a running pod</a></p>
|
<p>This is a Kubespray deployment using calico. All the defaults are were left as-is except for the fact that there is a proxy. Kubespray ran to the end without issues.</p>
<p>Access to Kubernetes services started failing and after investigation, there was <strong>no route to host</strong> to the <em>coredns</em> service. Accessing a K8S service by IP worked. Everything else seems to be correct, so I am left with a cluster that works, but without DNS.</p>
<p>Here is some background information:
Starting up a busybox container:</p>
<pre><code># nslookup kubernetes.default
Server: 169.254.25.10
Address: 169.254.25.10:53
** server can't find kubernetes.default: NXDOMAIN
*** Can't find kubernetes.default: No answer
</code></pre>
<p>Now the output while explicitly defining the IP of one of the CoreDNS pods:</p>
<pre><code># nslookup kubernetes.default 10.233.0.3
;; connection timed out; no servers could be reached
</code></pre>
<p>Notice that telnet to the Kubernetes API works:</p>
<pre><code># telnet 10.233.0.1 443
Connected to 10.233.0.1
</code></pre>
<p><strong>kube-proxy logs:</strong>
10.233.0.3 is the service IP for coredns. The last line looks concerning, even though it is INFO.</p>
<pre><code>$ kubectl logs kube-proxy-45v8n -nkube-system
I1114 14:19:29.657685 1 node.go:135] Successfully retrieved node IP: X.59.172.20
I1114 14:19:29.657769 1 server_others.go:176] Using ipvs Proxier.
I1114 14:19:29.664959 1 server.go:529] Version: v1.16.0
I1114 14:19:29.665427 1 conntrack.go:52] Setting nf_conntrack_max to 262144
I1114 14:19:29.669508 1 config.go:313] Starting service config controller
I1114 14:19:29.669566 1 shared_informer.go:197] Waiting for caches to sync for service config
I1114 14:19:29.669602 1 config.go:131] Starting endpoints config controller
I1114 14:19:29.669612 1 shared_informer.go:197] Waiting for caches to sync for endpoints config
I1114 14:19:29.769705 1 shared_informer.go:204] Caches are synced for service config
I1114 14:19:29.769756 1 shared_informer.go:204] Caches are synced for endpoints config
I1114 14:21:29.666256 1 graceful_termination.go:93] lw: remote out of the list: 10.233.0.3:53/TCP/10.233.124.23:53
I1114 14:21:29.666380 1 graceful_termination.go:93] lw: remote out of the list: 10.233.0.3:53/TCP/10.233.122.11:53
</code></pre>
<p>All pods are running without crashing/restarts etc. and otherwise services behave correctly.</p>
<p>IPVS looks correct. CoreDNS service is defined there:</p>
<pre><code># ipvsadm -ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 10.233.0.1:443 rr
-> x.59.172.19:6443 Masq 1 0 0
-> x.59.172.20:6443 Masq 1 1 0
TCP 10.233.0.3:53 rr
-> 10.233.122.12:53 Masq 1 0 0
-> 10.233.124.24:53 Masq 1 0 0
TCP 10.233.0.3:9153 rr
-> 10.233.122.12:9153 Masq 1 0 0
-> 10.233.124.24:9153 Masq 1 0 0
TCP 10.233.51.168:3306 rr
-> x.59.172.23:6446 Masq 1 0 0
TCP 10.233.53.155:44134 rr
-> 10.233.89.20:44134 Masq 1 0 0
UDP 10.233.0.3:53 rr
-> 10.233.122.12:53 Masq 1 0 314
-> 10.233.124.24:53 Masq 1 0 312
</code></pre>
<p>Host routing also looks correct.</p>
<pre><code># ip r
default via x.59.172.17 dev ens3 proto dhcp src x.59.172.22 metric 100
10.233.87.0/24 via x.59.172.21 dev tunl0 proto bird onlink
blackhole 10.233.89.0/24 proto bird
10.233.89.20 dev calib88cf6925c2 scope link
10.233.89.21 dev califdffa38ed52 scope link
10.233.122.0/24 via x.59.172.19 dev tunl0 proto bird onlink
10.233.124.0/24 via x.59.172.20 dev tunl0 proto bird onlink
x.59.172.16/28 dev ens3 proto kernel scope link src x.59.172.22
x.59.172.17 dev ens3 proto dhcp scope link src x.59.172.22 metric 100
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 linkdown
</code></pre>
<p>I have redeployed this same cluster in separate environments with flannel and calico with iptables instead of ipvs. I have also disabled the docker http proxy after deploy temporarily. None of which makes any difference.</p>
<p>Also:
kube_service_addresses: 10.233.0.0/18
kube_pods_subnet: 10.233.64.0/18
(They do not overlap)</p>
<p>What is the next step in debugging this issue?</p>
| <p>This is what works for me, I tried to install my k8s cluster using kubespray configured with calico as CNI and containerd as container runtime</p>
<pre><code>iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F
[delete coredns pod]
</code></pre>
|
<p>I learning about k8s and Helm so I started to create a simple flask app which uses mongondb, I have the deployment, the service and the ingress installed with helm and are working fine. For the mongo container I am using the chart from Bitnami, but I need to insert some data on creation, as I do wih the normal deployment by adding:</p>
<pre><code> volumeMounts:
- name: mongo-initdb
mountPath: /docker-entrypoint-initdb.d
</code></pre>
<p>In the bitnami documentation <a href="https://artifacthub.io/packages/helm/bitnami/mongodb" rel="nofollow noreferrer">https://artifacthub.io/packages/helm/bitnami/mongodb</a> it says that the data can be entered through a script or a configmap with the parameters <code>initdbScripts</code> or <code>initdbScriptsConfigMap</code> but I tried adding them like this and does not work:</p>
<pre><code>mongodb:
metrics:
enabled: true
global:
namespaceOverride: flask-app
initdbScriptsConfigMap: mongo-initdb.yaml
</code></pre>
<p>being this the configmap which works when using K8s with .yaml files:</p>
<pre><code>apiVersion: v1
data:
init-db.js: |-
db = db.getSiblingDB("cars_db");
db.car_tb.drop();
db.car_tb.insertMany([
{
"id": 1,
"brand": "Ford",
"model": "Mustang"
},
{
"id": 2,
"brand": "Lamborghini",
"model": "Veneno"
},
{
"id": 3,
"brand": "Ferrari",
"model": "Enzo"
},
{
"id": 4,
"brand": "Mercedes",
"model": "Cls63-AMG"
},
]);
kind: ConfigMap
metadata:
name: mongo-initdb
namespace: flask-app
</code></pre>
<p>Being the mongo-configmap.yaml inside the templates folder.</p>
<p>As it does not work I have tried adding a configmap named <code>docker-entrypoint-initdb.d </code> and set it inside a folder named files as stated here <a href="https://docs.bitnami.com/kubernetes/infrastructure/mongodb/administration/initialize-instance/" rel="nofollow noreferrer">https://docs.bitnami.com/kubernetes/infrastructure/mongodb/administration/initialize-instance/</a> but none of them works and do not have any examples on the documentation.</p>
<p>EDIT
I have tried adding this to the <code>values.yaml</code>:</p>
<pre><code>mongodb:
metrics:
enabled: true
global:
namespaceOverride: flask-app
auth:
username: root
password: pass
database: cars_db
rootPassword: pass
initdbScripts:
init-db.js: |
db = db.getSiblingDB("cars_db");
db.car_tb.drop();
db.car_tb.insertMany([
{
"id": 1,
"brand": "Ford",
"model": "Mustang"
},
{
"id": 2,
"brand": "Lamborghini",
"model": "Veneno"
},
{
"id": 3,
"brand": "Ferrari",
"model": "Enzo"
},
{
"id": 4,
"brand": "Mercedes",
"model": "Cls63-AMG"
},
]);
</code></pre>
<p>But this does not work either I got this from the official github <a href="https://github.com/bitnami/charts/blob/master/bitnami/mongodb/values.yaml" rel="nofollow noreferrer">https://github.com/bitnami/charts/blob/master/bitnami/mongodb/values.yaml</a> but I do not get how to make it work from the documentation and I cannot get any examples anywhere I have looked for</p>
| <p>You've probably figured this out by now, because you were close. I was able to do what you're looking to do using the following in my parent Chart's <code>values.yaml</code>:</p>
<pre><code>mongodb:
initdbScripts:
my_init_script.js: |
db = db.getSiblingDB("cars_db");
db.car_tb.drop();
db.car_tb.insertMany([
{
"id": 1,
"brand": "Ford",
"model": "Mustang"
},
{
"id": 2,
"brand": "Lamborghini",
"model": "Veneno"
},
{
"id": 3,
"brand": "Ferrari",
"model": "Enzo"
},
{
"id": 4,
"brand": "Mercedes",
"model": "Cls63-AMG"
},
]);
</code></pre>
<p>The important part is that this is within my parent chart's <code>values.yaml</code>. If you're modifying the mongodb chart directly (you probably shouldn't but whatever), omit the <code>mongodb</code> part and out-dent the rest. That's only necessary to override a child chart's values.</p>
<p>Also worth noting that I haven't tried this with the un/db/password overrides you're using, so maybe try removing those?</p>
<p>One other thing it could be is that there's a bugged version of the Bitnami mongo charts in which they straight up forgot to execute the <em>.js/</em>.sh files at startup so nothing happens. Try updating your chart version. I did this using:</p>
<pre><code>- name: mongodb
version: "10.15.0"
repository: https://charts.bitnami.com/bitnami
</code></pre>
|
<p>I am trying to access a remote kubernetes cluster with kubectl. In order to copy/paste cluster credentials in the kubeconfig file I tried to access with "<strong>~/.kube/config</strong>" command but there is an error saying "<strong>No such file or directory</strong>".</p>
<p>Could anyone please tell me why i get this error? kubectl is perfectly working.</p>
| <p>In my case I had KUBECONFIG variable set to "~/.kube/config" in .bashrc. The file existed & had correct permissions yet it wasn't being resolved somehow. Turned out I had to use ${HOME} in place of ~. That did the trick.</p>
|
<p>We're moving a legacy app to Kubernetes. We will have many instances of it running (a Kubernetes namespace per customer), so we want to automate our application upgrade process.</p>
<p>Kubernetes has well established patterns for rolling upgrades, but I can't use them (yet). My application requires the following process:</p>
<ol>
<li>all existing pods are deleted</li>
<li>a database upgrade job (Kubernetes Job) runs and completes successfully</li>
<li>new pods are created</li>
</ol>
<p>We define the pods through a Deployment. The database upgrade job is idempotent as long as we never run more than one at a time.</p>
<p>I assume my workflow is not an uncommon one for legacy applications, and yet I can't find any established patterns or tools preconfigured. Is there something out there? If I do have to write my own operator (or use something like Kudo), what is the best set of steps for it to perform?</p>
| <p>Yes, there is an existing process for that:</p>
<ol>
<li><p>Use the <code>kubectl scale</code> command to scale down the existing Deployment to zero replicas: <code>kubectl scale --replicas=0 deploy/my-legacy-deployment</code></p>
</li>
<li><p>Wait for that to stabilize (there's your requested downtime ;-)</p>
<p>Using <code>kubectl wait</code> will be helpful, although I personally don't have experience introducing downtime in order to know the remaining arguments to <code>wait</code> to suggest here</p>
<p>You can also use something like <code>while true; do [[ 0 -eq $(kubectl get pods -o name -l legacy-deployment-selector | wc -l) ]] && break; done</code> to stall until there are no pods remaining</p>
</li>
<li><p>Run your database job, or migrations of your choosing</p>
</li>
<li><p>Deploy the new version as you normally would; depending on the tool you use, this may or may not actually influence the currently zero-scaled Deployment</p>
<p>For example, <code>kubectl set image deploy/my-legacy-deployment "*=example.com/my/new/image"</code> will leave the Deployment at zero replicas</p>
<p>But a <code>helm install --upgrade legacy whatever-else</code> may very well set the Deployment's replicas to the value found in the chart</p>
</li>
<li><p>If your tool has not yet scaled up the new Deployment, you can now set it back to the desired value with the opposite command: <code>kubectl scale --replicas=3 deploy/my-legacy-deployment</code></p>
</li>
</ol>
|
<p>I read the following <a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/expose/expose-intro/" rel="nofollow noreferrer">kubernetes docs</a> which resulted in the following yaml's to run postgresql & pgadmin in a cluster:</p>
<pre><code>--- pgadmin-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: pgadmin-deployment
spec:
replicas: 1
selector:
matchLabels:
app: pgadmin-pod
template:
metadata:
labels:
app: pgadmin-pod
spec:
containers:
- name: pgadmin-container
image: dpage/pgadmin4
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 80
env:
- name: PGADMIN_DEFAULT_EMAIL
value: email@example.com
- name: PGADMIN_DEFAULT_PASSWORD
value: password
--- pgadmin-service.yaml
apiVersion: v1
kind: Service
metadata:
name: pgadmin-service
spec:
type: NodePort
ports:
- port: 30000
targetPort: 80
selector:
app: pgadmin-pod
--- postgres-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres-deployment
spec:
replicas: 1
selector:
matchLabels:
app: postgres-pod
template:
metadata:
labels:
app: postgres-pod
spec:
containers:
- name: postgres-container
image: postgres:9.6-alpine
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 5432
env:
- name: POSTGRES_DB
value: database
- name: POSTGRES_PASSWORD
value: password
- name: POSTGRES_USER
value: username
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgrepvc
volumes:
- name: postgrepvc
persistentVolumeClaim:
claimName: postgres-pv-claim
--- postgres-service.yaml
apiVersion: v1
kind: Service
metadata:
name: postgres-service
spec:
type: NodePort
ports:
- port: 30001
targetPort: 5432
selector:
app: postgres-pod
--- postgres-storage.yaml
postgres-storage.yaml
kind: PersistentVolume
apiVersion: v1
metadata:
name: postgres-pv-volume
labels:
type: local
app: postgres
spec:
storageClassName: manual
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
hostPath:
path: "/mnt/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: postgres-pv-claim
labels:
app: postgres
spec:
storageClassName: manual
accessModes:
- ReadWriteMany
resources:
requests:
storage: 5Gi
</code></pre>
<p>I then run the following command <code>kubectl create -f ./</code> which results in the following:
<a href="https://i.stack.imgur.com/13zeL.png" rel="nofollow noreferrer">kubernetes pods / svc's</a></p>
<p>Then I try to access pgAdmin on 10.43.225.170:30000 from outside of the cluster, but I get "10.43.225.170 took too long to respond." no matter what I try.</p>
<p>So how do I expose pgAdmin & postgress to the outside world, and is there a way to give them static ip's so I don't have to update ip's in connection strings each time I re-deploy on kubernetes, or do I have to use statefulset for this?</p>
| <hr />
<p>Problems here</p>
<ol>
<li>you are trying to reach <strong>node internal ip</strong> <code>10.43.225.170</code> instead of <strong>external</strong> one.</li>
<li>nodePort service configured incorrectly. In addition you are trying to call incorrect port</li>
</ol>
<hr />
<p>You haven't specified what platform you use. I'm using GKE, so in my case its easier because I have external IP's automatically assigned during cluster node creation. But I had to manually create ingress firewall rule to allow access from outside to nodes and required ports (30000,30001)</p>
<p>In any case, to be able to use <code>nodePort</code> - you should have <strong>external IP address assigned to one of the nodes in cluster and a Firewall rule that allows ingress traffic to that port</strong></p>
<hr />
<p>Going next. You are trying to call <code><NodeIP>:spec.ports[*].port</code>.</p>
<p>As per <a href="https://kubernetes.io/docs/concepts/services-networking/service/#nodeport" rel="nofollow noreferrer">Type NodePort documentation</a>:</p>
<blockquote>
<p>Service is visible as <code><NodeIP>:spec.ports[*].nodePort</code></p>
</blockquote>
<p>You need explicitly specify nodePort</p>
<hr />
<p>I have changed a bit your deployment, can access pgAdmin after deploying it and opening corresponding ports in firewall.</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: pgadmin-deployment
spec:
replicas: 1
selector:
matchLabels:
app: pgadmin-pod
template:
metadata:
labels:
app: pgadmin-pod
spec:
containers:
- name: pgadmin-container
image: dpage/pgadmin4
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 80
env:
- name: PGADMIN_DEFAULT_EMAIL
value: email@example.com
- name: PGADMIN_DEFAULT_PASSWORD
value: password
---
apiVersion: v1
kind: Service
metadata:
name: pgadmin-service
spec:
type: NodePort
ports:
- nodePort: 30000
targetPort: 80
port: 80
selector:
app: pgadmin-pod
--- postgres-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres-deployment
spec:
replicas: 1
selector:
matchLabels:
app: postgres-pod
template:
metadata:
labels:
app: postgres-pod
spec:
containers:
- name: postgres-container
image: postgres:9.6-alpine
imagePullPolicy: "IfNotPresent"
ports:
- containerPort: 5432
env:
- name: POSTGRES_DB
value: database
- name: POSTGRES_PASSWORD
value: password
- name: POSTGRES_USER
value: username
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgrepvc
volumes:
- name: postgrepvc
persistentVolumeClaim:
claimName: postgres-pv-claim
---
apiVersion: v1
kind: Service
metadata:
name: postgres-service
spec:
type: NodePort
ports:
- nodePort: 30001
targetPort: 5432
port: 5432
selector:
app: postgres-pod
---
kind: PersistentVolume
apiVersion: v1
metadata:
name: postgres-pv-volume
labels:
type: local
app: postgres
spec:
storageClassName: manual
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
hostPath:
path: "/mnt/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: postgres-pv-claim
labels:
app: postgres
spec:
storageClassName: manual
accessModes:
- ReadWriteMany
resources:
requests:
storage: 5Gi
</code></pre>
<p>Check:</p>
<pre><code>kubectl apply -f pg_my.yaml
deployment.apps/pgadmin-deployment created
service/pgadmin-service created
service/postgres-service created
persistentvolume/postgres-pv-volume created
persistentvolumeclaim/postgres-pv-claim created
#In my case I take node external ip from any node from `kubectl get nodes -o wide` output:
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP
gke-cluster-1-default-pool-*******-***** Ready <none> 20d v1.18.16-gke.502 10.186.0.7 *.*.*.*
curl *.*.*.*:30000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/login?next=%2F">/login?next=%2F</a>.
</code></pre>
<p><a href="https://i.stack.imgur.com/tY8WR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tY8WR.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/pLsUJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pLsUJ.png" alt="enter image description here" /></a></p>
|
<p>There is no clear information about how to make a backup and restore from a regular node like node01 for instance, I mean:</p>
<ul>
<li><p><a href="https://kubernetes.io/docs/tasks/administer-cluster/configure-upgrade-etcd/" rel="nofollow noreferrer">Operating etcd clusters for Kubernetes</a> shows information like how to use it and</p>
</li>
<li><p><a href="https://discuss.kubernetes.io/t/etcd-backup-and-restore-management/11019" rel="nofollow noreferrer">ETCD - backup and restore management</a> shows some of the necessary steps.</p>
</li>
</ul>
<p>But how about in the cert exam, you are operating most of the time from a regular node01, the config files are not the same? Can some one elaborate?</p>
<p>Thanks</p>
| <p>It is impossible to backup cluster from a regular node using etcd. <a href="https://www.veeam.com/blog/backup-kubernetes-master-node.html" rel="nofollow noreferrer">The etcd can only be run on a master node.</a></p>
<p>But you can backup your Kubernetes cluster by command: <code>etcdctl backup</code>. Here you can find completely guide, how to use <a href="https://etcd.io/docs/v2.3/admin_guide/#disaster-recovery" rel="nofollow noreferrer">etcdctl backup command</a>.</p>
<p>Another way is making a <a href="https://kubernetes.io/docs/tasks/administer-cluster/configure-upgrade-etcd/#built-in-snapshot" rel="nofollow noreferrer">snapshot</a> of your cluster by command: <code>etcdctl snapshot save</code>.</p>
<p>This command will let you create <strong>incremental backup</strong>.</p>
<blockquote>
<p>Incremental backup of etcd, where full snapshot is taken first and then we apply watch and persist the logs accumulated over certain period to snapshot store. Restore process, restores from the full snapshot, start the embedded etcd and apply the logged events one by one.</p>
</blockquote>
<p>You can find more about incremental backup function <a href="https://github.com/gardener/etcd-backup-restore/issues/2" rel="nofollow noreferrer">here</a>.</p>
|
<p>I have several apps of different shapes and purposes, each with their own <code>templates/</code> folder as generated by <code>helm create chart</code>. The templates within each App are sufficiently different to justify having them as one-offs. However, the <code>_helpers.tpl</code> is identical for all of them. I'd like to externalize/reuse this <code>_helpers.tpl</code> template so that I don't need a copy of it in every app.</p>
<p>What I have currently looks something like this:</p>
<pre><code>App1
|--app (random source code crap, irrelevant)
|--chart
|---templates
|------_helpers.tpl
|------ deployment.yaml
|------ other unique templates
App2
|--app (random source code crap, irrelevant)
|--chart
|---templates
|------_helpers.tpl
|------ deployment.yaml
|------ other unique templates
</code></pre>
<p>I'd like to centralize this <code>_helpers.tpl</code> so that I don't need to maintain N versions of it. I'm imagining something like this, but I'm open to whatever:</p>
<pre><code>Common
|--chart
|----templates
|------ _helpers.tpl (I live here now and was removed from the 2 Apps below)
App1
|-- app (random source code crap, irrelevant)
|-- chart
|--- templates
|------ deployment.yaml
|------ other unique templates
App2
|-- app (random source code crap, irrelevant)
|-- chart
|--- templates
|------ deployment.yaml
|------ other unique templates
</code></pre>
<p>I have tried doing this with a symlink pointing <code>AppN/chart/templates/_helper.tpl</code> to <code>Common/chart/templates/_helper.tpl</code> but that's clearly bad and I imagine there's a built-in way to do this that I'm just not finding.</p>
<p>Even if <code>AppN/chart/templates/_helpers.tpl</code> needs to exist only to read <code>../../_helpers.tpl</code>, that's good enough but I'm not sure how to approach that given the YAML-y/Go-y syntax.</p>
| <p>If one Helm chart includes another as a subchart, any <code>{{ define }}</code> templates anywhere in any of the parent or child charts are visible to all of the charts to be <code>{{ include }}</code>d or <code>{{ template }}</code>d. This means that you can create a <a href="https://docs.helm.sh/docs/topics/library_charts/" rel="nofollow noreferrer">library chart</a> that only contains the helpers, with basically exactly the structure you show above</p>
<pre class="lang-none prettyprint-override"><code>common
+-- Chart.yaml
\-- templates/
+-- _a_helper.tpl
\-- _another.tpl
</code></pre>
<p>This looks like a normal Helm chart in that it has a <code>Chart.yaml</code> file and a <code>templates</code> subdirectory, but inside <code>templates</code> are only <code>_*.tpl</code> files and not <code>*.yaml</code> files, and those files only contain <code>{{ define }}</code> top-level directives.</p>
<p>In your application charts, you can consume the library chart like any other chart dependency. If these are all checked into the same repository, you can use relative <code>file:</code> URLs to point at the common chart.</p>
<pre class="lang-yaml prettyprint-override"><code># app1/Chart.yaml
dependencies:
- name: common
repository: file://../common/
</code></pre>
<p>You do need to remember to run <code>helm dep up</code> before deploying the application chart; this makes a copy in the <code>charts</code> subdirectory.</p>
<p>(If you're using modern Helm 3, you can flag the library chart with <code>type: library</code> in the <code>Chart.yaml</code> file. If you're using obsolete Helm 2, the dependency needs to go in a separate <code>requirements.yaml</code> file. You can't usefully configure the library chart with values; if an application chart calls <code>{{ include "common.some.template" . }}</code> it will pass along the parent chart's view of <code>.Values</code> as part of the template parameter.)</p>
|
<p>Is there a way to access existing validation specs? For example, I want to be able to set NodeAffinity on my CRD, and would like to just $ref: . I found the entire API here: <a href="https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/swagger.json" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/swagger.json</a>
OR kubectl proxy -> localhost:8001/openapi/v2 (from within my cluster)</p>
<p>I could manually copy paste the api validation schema, but I was wondering if there was a way to automatically reference an existing OpenAPI Validation Spec from within my CRD with $ref. I imagine something like $ref: localhost:8001/openapi/v2/definitions/io.k8s.api.core.v1.NodeAffinity</p>
<p>If this is even possible, will it resolve the inner $refs as well?</p>
<p>For reference, here's what the nodeaffinity definition looks like in the API:</p>
<pre><code>"io.k8s.api.core.v1.NodeAffinity": {
"description": "Node affinity is a group of node affinity scheduling rules.",
"properties": {
"preferredDuringSchedulingIgnoredDuringExecution": {
"description": "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.",
"items": {
"$ref": "#/definitions/io.k8s.api.core.v1.PreferredSchedulingTerm"
},
"type": "array"
},
"requiredDuringSchedulingIgnoredDuringExecution": {
"$ref": "#/definitions/io.k8s.api.core.v1.NodeSelector",
"description": "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node."
}
},
"type": "object"
},
</code></pre>
<p>(using Operator-SDK with Ansible, incase that matters)</p>
<p>EDIT: (adding a full example to further explain)</p>
<p>I have a CRD called Workshop, and I require validation on certain spec parameters.</p>
<pre><code>apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: workshops.k8s.example.tk
spec:
group: k8s.example.tk
names:
kind: Workshop
listKind: WorkshopList
plural: workshops
singular: workshop
scope: Namespaced
subresources:
status: {}
validation:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required:
- workshopID
properties:
workshopID: #
type: string
description: Unique identifier for this particular virtual
workshop
example: d8e8fca2dc0f896fd7cb4cb0031ba249
</code></pre>
<p>Now I need to add a nodeAffinity spec field that will be applied to any pods that live under this CustomResourceDefinition. The validation for it is going to be the exact same as the validation for nodeAffinity in pods.</p>
<p>Let me pull the validation spec that is ALREADY WRITTEN in OpenApi from: <a href="https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/swagger.json" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/swagger.json</a> and convert it to YAML then add it to my spec.</p>
<pre><code>apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: workshops.k8s.example.tk
spec:
group: k8s.example.tk
names:
kind: Workshop
listKind: WorkshopList
plural: workshops
singular: workshop
scope: Namespaced
subresources:
status: {}
validation:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required:
- workshopID
properties:
workshopID: #
type: string
description: Unique identifier for this particular virtual
workshop
example: d8e8fca2dc0f896fd7cb4cb0031ba249
affinity: #
type: object
properties:
nodeAffinity: #
description: Node affinity is a group of node affinity scheduling rules.
type: object
properties:
preferredDuringSchedulingIgnoredDuringExecution:
description: The scheduler will prefer to schedule pods to nodes that satisfy
the affinity expressions specified by this field, but it may choose a node that
violates one or more of the expressions. The node that is most preferred is
the one with the greatest sum of weights, i.e. for each node that meets all
of the scheduling requirements (resource request, requiredDuringScheduling affinity
expressions, etc.), compute a sum by iterating through the elements of this
field and adding "weight" to the sum if the node matches the corresponding matchExpressions;
the node(s) with the highest sum are the most preferred.
type: array
items:
description: An empty preferred scheduling term matches all objects with implicit
weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no
objects (i.e. is also a no-op).
type: object
required:
- weight
- preference
properties:
preference:
description: A node selector term, associated with the corresponding weight.
A null or empty node selector term matches no objects. The requirements
of them are ANDed. The TopologySelectorTerm type implements a subset of
the NodeSelectorTerm.
type: object
properties:
matchExpressions:
description: A list of node selector requirements by node's labels.
type: array
items:
description: A node selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
type: object
required:
- key
- operator
properties:
key:
description: The label key that the selector applies to.
type: string
operator:
description: Represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
Lt.
type: string
values:
description: An array of string values. If the operator is In
or NotIn, the values array must be non-empty. If the operator
is Exists or DoesNotExist, the values array must be empty. If
the operator is Gt or Lt, the values array must have a single
element, which will be interpreted as an integer. This array
is replaced during a strategic merge patch.
type: array
items:
type: string
matchFields:
description: A list of node selector requirements by node's fields.
type: array
items:
description: A node selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
type: object
required:
- key
- operator
properties:
key:
description: The label key that the selector applies to.
type: string
operator:
description: Represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
Lt.
type: string
values:
description: An array of string values. If the operator is In
or NotIn, the values array must be non-empty. If the operator
is Exists or DoesNotExist, the values array must be empty. If
the operator is Gt or Lt, the values array must have a single
element, which will be interpreted as an integer. This array
is replaced during a strategic merge patch.
type: array
items:
type: string
weight:
description: Weight associated with matching the corresponding nodeSelectorTerm,
in the range 1-100.
type: integer
format: int32
requiredDuringSchedulingIgnoredDuringExecution:
description: If the affinity requirements specified by this field are not met
at scheduling time, the pod will not be scheduled onto the node. If the affinity
requirements specified by this field cease to be met at some point during pod
execution (e.g. due to an update), the system may or may not try to eventually
evict the pod from its node. A node selector represents the union of the results
of one or more label queries over a set of nodes; that is, it represents the
OR of the selectors represented by the node selector terms.
type: object
required:
- nodeSelectorTerms
properties:
nodeSelectorTerms:
description: Required. A list of node selector terms. The terms are ORed.
type: array
items:
description: A null or empty node selector term matches no objects. The
requirements of them are ANDed. The TopologySelectorTerm type implements
a subset of the NodeSelectorTerm.
type: object
properties:
matchExpressions:
description: A list of node selector requirements by node's labels.
type: array
items:
description: A node selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
type: object
required:
- key
- operator
properties:
key:
description: The label key that the selector applies to.
type: string
operator:
description: Represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
Lt.
type: string
values:
description: An array of string values. If the operator is In
or NotIn, the values array must be non-empty. If the operator
is Exists or DoesNotExist, the values array must be empty. If
the operator is Gt or Lt, the values array must have a single
element, which will be interpreted as an integer. This array
is replaced during a strategic merge patch.
type: array
items:
type: string
matchFields:
description: A list of node selector requirements by node's fields.
type: array
items:
description: A node selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
type: object
required:
- key
- operator
properties:
key:
description: The label key that the selector applies to.
type: string
operator:
description: Represents a key's relationship to a set of values.
Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
Lt.
type: string
values:
description: An array of string values. If the operator is In
or NotIn, the values array must be non-empty. If the operator
is Exists or DoesNotExist, the values array must be empty. If
the operator is Gt or Lt, the values array must have a single
element, which will be interpreted as an integer. This array
is replaced during a strategic merge patch.
type: array
items:
type: string
</code></pre>
<p>Wow, for just one field (and its sub fields) to be validated, my CRD definition has grown by 100+ lines, all just to reimplement something that already exists in the Kubernetes-native pod api definition. It also took about 15 minutes to manually copy paste and resolve all the references in the Kubernetes spec by hand. Wouldn't it make so much sense to either:</p>
<p>A) Store this long API spec in an external file, and use $ref: externalfile.json to pull it in to keep my CRD small and clean.</p>
<p>OR BETTER YET</p>
<p>B) Insert the actual Kubernetes-native validation spec that ALREADY EXISTS with a $ref tag like this:</p>
<pre><code>apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: workshops.k8s.example.tk
spec:
group: k8s.example.tk
names:
kind: Workshop
listKind: WorkshopList
plural: workshops
singular: workshop
scope: Namespaced
subresources:
status: {}
validation:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required:
- workshopID
properties:
workshopID: #
type: string
description: Unique identifier for this particular virtual
workshop
example: d8e8fca2dc0f896fd7cb4cb0031ba249
affinity:
type: object
properties:
nodeAffinity:
$ref: <kubernetes-api>/openapi/v2#/definitions/io.k8s.api.core.v1.NodeAffinity
</code></pre>
<p>Back down to 30 or so lines of code, AND the validation spec stays up-to-date with Kubernetes native validation, since it's pulling the information from Kubernetes API itself. According to this, $ref should be supported in doing this: <a href="https://swagger.io/docs/specification/using-ref/#syntax" rel="nofollow noreferrer">https://swagger.io/docs/specification/using-ref/#syntax</a></p>
| <p>There unfortunately isn't a way to do nicely this currently. We solved the problem by writing <a href="https://gist.github.com/danrspencer/f695a22b15b1e4e3b3cae75a7a8a93ec" rel="nofollow noreferrer">a horrible Bash script</a> to rip the definition out of Kubernetes and included it via Helm templating into our CRD.</p>
|
<p>I have two EKS Clusters in a VPC.</p>
<ol>
<li><p>Cluster A running in Public subnet of VPC [Frontend application is deployed here]</p>
</li>
<li><p>Cluster B running in Private subnet of VPC [ Backend application is deployed here]</p>
</li>
</ol>
<p>I would like to establish a networking with these two cluster such that, the pods from cluster A should be able to communicate with pods from Cluster B.</p>
| <p>At the high level, you will need to expose the backend application via a K8s service. You'd then expose this service via an ingress object (<a href="https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html" rel="nofollow noreferrer">see here</a> for the details and how to configure it). Front end pods will automatically be able to reach this service endpoint if you point them to it. It is likely that you will want to do the same thing to expose your front-end service (via an ingress).</p>
<p>Usually an architecture like this is deployed into a single cluster and in that case you'd only need one ingress for the front-end and the back-end would be reachable through standard in-cluster discovery of the back-end service. But because you are doing this across clusters you have to expose the back-end service via an ingress. The alternative would be to enable cross-clusters discovery using a mesh (<a href="https://aws.amazon.com/blogs/containers/cross-amazon-eks-cluster-app-mesh-using-aws-cloud-map/" rel="nofollow noreferrer">see here</a> for more details).</p>
|
<p>I have been trying to run an external-dns pod using the guide provided by k8s-sig group. I have followed every step of the guide, and getting the below error.</p>
<pre><code>time="2021-02-27T13:27:20Z" level=error msg="records retrieval failed: failed to list hosted zones: WebIdentityErr: failed to retrieve credentials\ncaused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity\n\tstatus code: 403, request id: 87a3ca86-ceb0-47be-8f90-25d0c2de9f48"
</code></pre>
<p>I had created AWS IAM policy using Terraform, and it was successfully created. Except IAM Role for service account for which I had used <code>eksctl</code>, everything else has been spun via Terraform.</p>
<p>But then I got hold of this <a href="https://www.google.com/amp/s/www.freecodecamp.org/news/how-to-setup-dns-for-a-website-using-kubernetes-eks-and-nginx/amp/" rel="noreferrer">article</a> which says creating AWS IAM policy using awscli would eliminate this error. So I deleted the policy created using Terraform, and recreated it with awscli. Yet, it is throwing the same error error.</p>
<p><strong>Below is my external dns yaml file.</strong></p>
<pre><code>apiVersion: v1
kind: ServiceAccount
metadata:
name: external-dns
# If you're using Amazon EKS with IAM Roles for Service Accounts, specify the following annotation.
# Otherwise, you may safely omit it.
annotations:
# Substitute your account ID and IAM service role name below.
eks.amazonaws.com/role-arn: arn:aws:iam::268xxxxxxx:role/eksctl-ats-Eks1-addon-iamserviceaccoun-Role1-WMLL93xxxx
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
name: external-dns
rules:
- apiGroups: [""]
resources: ["services","endpoints","pods"]
verbs: ["get","watch","list"]
- apiGroups: ["extensions","networking.k8s.io"]
resources: ["ingresses"]
verbs: ["get","watch","list"]
- apiGroups: [""]
resources: ["nodes"]
verbs: ["list","watch"]
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
name: external-dns-viewer
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: external-dns
subjects:
- kind: ServiceAccount
name: external-dns
namespace: default
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: external-dns
spec:
strategy:
type: Recreate
selector:
matchLabels:
app: external-dns
template:
metadata:
labels:
app: external-dns
spec:
serviceAccountName: external-dns
containers:
- name: external-dns
image: k8s.gcr.io/external-dns/external-dns:v0.7.6
args:
- --source=service
- --source=ingress
- --domain-filter=xyz.com # will make ExternalDNS see only the hosted zones matching provided domain, omit to process all available hosted zones
- --provider=aws
- --policy=upsert-only # would prevent ExternalDNS from deleting any records, omit to enable full synchronization
- --aws-zone-type=public # only look at public hosted zones (valid values are public, private or no value for both)
- --registry=txt
- --txt-owner-id=Z0471542U7WSPZxxxx
securityContext:
fsGroup: 65534 # For ExternalDNS to be able to read Kubernetes and AWS token files
</code></pre>
<p>I am scratching my head as there is no proper solution to this error anywhere in the net. Hoping to find a solution to this issue in this forum.</p>
<p>End result must show something like below and fill up records in hosted zone.</p>
<pre><code>time="2020-05-05T02:57:31Z" level=info msg="All records are already up to date"
</code></pre>
| <p>I also struggled with this error.</p>
<p>The problem was in the definition of the trust relationship.</p>
<p>You can see in some offical aws tutorials (like <a href="https://docs.aws.amazon.com/eks/latest/userguide/create-service-account-iam-policy-and-role.html" rel="noreferrer">this</a>) the following setup:</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::${AWS_ACCOUNT_ID}:oidc-provider/${OIDC_PROVIDER}"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"${OIDC_PROVIDER}:sub": "system:serviceaccount:<my-namespace>:<my-service-account>"
}
}
}
]
}
</code></pre>
<p><strong>Option 1 for failure</strong></p>
<p>My problem was that I passed the a wrong value for <code>my-service-account</code> at the end of <code>${OIDC_PROVIDER}:sub</code> in the <code>Condition</code> part.</p>
<p><strong>Option 2 for failure</strong></p>
<p>After the previous fix - I still faced the same error - it was solved by following <a href="https://aws.amazon.com/blogs/opensource/introducing-fine-grained-iam-roles-service-accounts/" rel="noreferrer">this aws tutorial</a> which shows the output of using the eksctl with the command below:</p>
<pre><code>eksctl create iamserviceaccount \
--name my-serviceaccount \
--namespace <your-ns> \
--cluster <your-cluster-name> \
--attach-policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess \
--approve
</code></pre>
<p>When you look at the output in the <em>trust relationship</em> tab in the AWS web console - you can see that an additional condition was added with the postfix of <code>:aud</code> and the value of <code>sts.amazonaws.com</code>:</p>
<p><a href="https://i.stack.imgur.com/ezhkK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ezhkK.png" alt="enter image description here" /></a></p>
<p>So this need to be added after the <code>"${OIDC_PROVIDER}:sub"</code> condition.</p>
|
<p>I have a script that I want to run using a dockerfile that looks like this:</p>
<pre><code>FROM debian:unstable-slim
RUN apt-get update && apt-get install -y netcat-traditional httpie postgresql-client
COPY go.sh /tmp/go.sh
WORKDIR /tmp
CMD ["bash", "-c", "/tmp/go.sh"]
</code></pre>
<p>It works fine on local, but I need to deploy it as a kubernetes cronjob, I have a config file with something like this:</p>
<pre><code>script:
- docker build -t {github_enterprise_url/org/repo} .
</code></pre>
<p>And the build output seems ok:</p>
<pre><code>...
Step 3/7 : COPY go.sh /tmp/go.sh
---> ab8d5227f65e
...
Successfully built e79162d90def
</code></pre>
<p>And for the cronjob yaml, among other things, I have something like this:</p>
<pre><code>spec:
containers:
- image: >-
${ trigger.artifacts.?[type == 'docker'].?[name matches
'org/repo'].![reference][0] }
</code></pre>
<p>the deploy then succeded but with this message:</p>
<pre><code>Cannot determine if job needs to be started: Too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew.
</code></pre>
<p>So I tried to run it manually like this:</p>
<pre><code>kubectl create job --from=cronjob/name name-manual-123
</code></pre>
<p>And when looking at the logs for the pod created, I get this:</p>
<pre><code>kubectl logs name-manual-123-ab1cd
bash: line 1: /tmp/go.sh: No such file or directory
</code></pre>
<p>any clue?</p>
| <p>The <code>/tmp</code> directory is generally intended for temporary file storage. It's common to mount a RAM disk (<code>tmpfs</code>) there, and it's possible the Kubernetes setup does this without you noticing it.</p>
<p>You can address this by storing your script in a location that's on the default <code>PATH</code>, like <code>/usr/local/bin</code>:</p>
<pre class="lang-sh prettyprint-override"><code># /usr/local/bin, not /tmp
COPY go.sh /usr/local/bin
CMD ["go.sh"]
# will work when the script is executable; on $PATH (in /usr/local/bin);
# and has a correct shebang line
# #!/bin/sh
</code></pre>
|
<p>I'm following <a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#check-required-ports" rel="nofollow noreferrer">this</a> and am about to ask our IT team to open the hardware firewall port for me:</p>
<p><strong>Control-plane node(s)</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Protocol</th>
<th>Direction</th>
<th>Port Range</th>
<th>Purpose</th>
<th>Used By</th>
</tr>
</thead>
<tbody>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>6443*</td>
<td>Kubernetes API server</td>
<td>All</td>
</tr>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>2379-2380</td>
<td>etcd server client API</td>
<td>kube-apiserver, etcd</td>
</tr>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>10250</td>
<td>kubelet API</td>
<td>Self, Control plane</td>
</tr>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>10251</td>
<td>kube-scheduler</td>
<td>Self</td>
</tr>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>10252</td>
<td>kube-controller-manager</td>
<td>Self</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Worker node(s)</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Protocol</th>
<th>Direction</th>
<th>Port Range</th>
<th>Purpose</th>
<th>Used By</th>
</tr>
</thead>
<tbody>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>10250</td>
<td>kubelet API</td>
<td>Self, Control plane</td>
</tr>
<tr>
<td>TCP</td>
<td>Inbound</td>
<td>30000-32767</td>
<td>NodePort Services†</td>
<td>All</td>
</tr>
</tbody>
</table>
</div>
<p>Before I ask IT to open the hardware port for me, I checked my local environment which doesn't have a hardware firewall, and I see this:</p>
<pre><code># netstat -oanltp | grep 10250
tcp6 0 0 :::10250 :::* LISTEN 3914/kubelet off (0.00/0/0)
# netstat -oanltp | grep 10251
# netstat -oanltp | grep 10252
</code></pre>
<p>You can see that nothing is listening on <code>10251</code> and <code>10252</code>. But my <code>kube-scheduler</code> and <code>kube-controller-manager</code> are running, and everything looks OK:</p>
<pre><code>kube-system kube-controller-manager-shlava 1/1 Running 0 47h 10.192.244.109
kube-system kube-scheduler-shlava 1/1 Running 0 47h 10.192.244.109
</code></pre>
<p>So I wonder: is it normal that nothing is listening on <code>10251</code> and <code>10252</code>?</p>
| <p>The answer is: <em>it depends</em>.</p>
<ul>
<li>You may have specified a different port for serving HTTP with <code>--port</code> flag</li>
<li>You may have disabled serving HTTP altogether with <code>--port 0</code></li>
<li>You are using latest version of K8s</li>
</ul>
<p>Last one is most probable as <a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/" rel="noreferrer">Creating a cluster with kubeadm</a> states it is written for version <em>1.21</em></p>
<p>Ports <code>10251</code> and <code>10252</code> have been replaced in veresion <em>1.17</em> (see more <a href="https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.17.md#cluster-lifecycle-1" rel="noreferrer">here</a>)</p>
<blockquote>
<p>Kubeadm: enable the usage of the secure kube-scheduler and kube-controller-manager ports for health checks. For kube-scheduler was 10251, becomes 10259. For kube-controller-manager was 10252, becomes 10257.</p>
</blockquote>
<p>Moreover, this functionality is depracted in <em>1.19</em> (more <a href="https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.19.md#deprecation" rel="noreferrer">here</a>)</p>
<blockquote>
<p>Kube-apiserver: the componentstatus API is deprecated. This API provided status of etcd, kube-scheduler, and kube-controller-manager components, but only worked when those components were local to the API server, and when kube-scheduler and kube-controller-manager exposed unsecured health endpoints. Instead of this API, etcd health is included in the kube-apiserver health check and kube-scheduler/kube-controller-manager health checks can be made directly against those components' health endpoints.</p>
</blockquote>
<p>It seems some parts of documentation are outdated.</p>
|
<p>Kubernetes creates one PersistentVolume for each VolumeClaimTemplate definition on an statefulset. That makes each statefulset pod have its own storage that is not shared across the replicas. However, I would like to share the same volume across all the statefulset replicas.</p>
<p>It looks like the approach should be the following:</p>
<ol>
<li>Create a PVC on the same namespace.</li>
<li>On the statefulset use Volumes to bound the PVC</li>
<li>Ensure that the PVC is ReadOnlyMany or ReadWriteMany</li>
</ol>
<p>Assuming that my application is able to deal with any concurrency on the shared volume, is there any technical problem if I have one PVC to share the same volume across all statefulset replicas?</p>
| <p>I wholeheartedly agree with the comments made by @Jonas and @David Maze:</p>
<blockquote>
<p>You can do this, it should work. There is no need to use volumeClaimTemplates unless your app needs it.</p>
</blockquote>
<blockquote>
<p>Two obvious problems are that ReadWriteMany volumes are actually a little tricky to get (things like AWS EBS volumes are only ReadWriteOnce), and that many things you want to run in StatefulSets (like databases) want exclusive use of their filesystem space and use file locking to enforce this.</p>
</blockquote>
<hr />
<p>Answering on the question:</p>
<blockquote>
<p>Is there any technical problem if I have one PVC to share the same volume across all statefulset replicas?</p>
</blockquote>
<p>I'd say that this would mostly depend on the:</p>
<ul>
<li>How the application would handle such scenario where it's having single PVC (writing concurrency).</li>
<li>Which storage solution are supported by your Kubernetes cluster (or could be implemented).</li>
</ul>
<p>Subjectively speaking, I don't think there should be an issue when above points are acknowledged and aligned with the requirements and configuration that the cluster/applications allows.</p>
<hr />
<p>From the application perspective, there is an inherent lack of the software we are talking about. Each application could behave differently and could require different tuning (look on the David Maze comment).</p>
<p>We do not also know anything about your infrastructure so it could be hard to point you potential issues. From the hardware perspective (Kubernetes cluster), this would inherently go into making a research on the particular storage solution that you would like to use. It could be different from cloud provider to cloud provider as well as on-premise solutions. You would need to check the requirements of your app to align it to the options you have.</p>
<p>Continuing on the matter of <code>Volumes</code>, I'd reckon the one of the important things would be <code>accessModes</code>.</p>
<p>Citing the official docs:</p>
<blockquote>
<h3>Access Modes</h3>
<p>A PersistentVolume can be mounted on a host in any way supported by the resource provider. As shown in the table below, providers will have different capabilities and each PV's access modes are set to the specific modes supported by that particular volume. For example, NFS can support multiple read/write clients, but a specific NFS PV might be exported on the server as read-only. Each PV gets its own set of access modes describing that specific PV's capabilities.</p>
<p>The access modes are:</p>
<ul>
<li>ReadWriteOnce -- the volume can be mounted as read-write by a single node</li>
<li>ReadOnlyMany -- the volume can be mounted read-only by many nodes</li>
<li>ReadWriteMany -- the volume can be mounted as read-write by many nodes</li>
</ul>
<p>In the CLI, the access modes are abbreviated to:</p>
<ul>
<li>RWO - ReadWriteOnce</li>
<li>ROX - ReadOnlyMany</li>
<li>RWX - ReadWriteMany</li>
</ul>
<hr />
<ul>
<li><em><a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes" rel="nofollow noreferrer">Kubernetes.io: Docs: Concepts: Storage: Persistent Volumes: Access modes</a></em></li>
</ul>
</blockquote>
<p>One of the issues you can run into is with the <code>ReadWriteOnce</code> when the <code>PVC</code> is mounted to the <code>Node</code> and <code>sts-X</code> (<code>Pod</code>) is scheduled onto a different <code>Node</code> but from the question, I'd reckon you already know about it.</p>
<hr />
<blockquote>
<p>However, I would like to share the same volume across all the statefulset replicas.</p>
</blockquote>
<p>An example of a <code>StatefulSet</code> with a <code>Volume</code> that would be shared across all of the replicas could be following (modified example from Kubernetes documentation):</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
selector:
matchLabels:
app: nginx # has to match .spec.template.metadata.labels
serviceName: "nginx"
replicas: 3 # by default is 1
template:
metadata:
labels:
app: nginx # has to match .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
name: web
# VOLUME START
volumeMounts:
- name: example-pvc
mountPath: /usr/share/nginx/html
volumes:
- name: example-pvc
persistentVolumeClaim:
claimName: pvc-for-sts
# VOLUME END
</code></pre>
<hr />
<p>Additional resources:</p>
<ul>
<li><em><a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" rel="nofollow noreferrer">Kubernetes.io: Docs: Concepts: Workloads: Controllers: Statefulset</a></em></li>
<li><em><a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/" rel="nofollow noreferrer">Kubernetes.io: Docs: Concepts: Storage: Persistent Volumes</a></em></li>
</ul>
|
<p>I have prometheus config that works on my cluster deployed by terraform. Now, I would like to setup Prometheus using the same prometheus.yml locally (outside terraform). I created a new project to set up Promethese using docker-compose and use the same prometheus.yml file but when I go to prometheus site, it seems like the metrics for kubernetes is not available, such as these metrics about kubernetes containers:
container_cpu_usage_seconds_total
container_cpu_load_average_10s
container_memory_usage_bytes
container_memory_rss</p>
<p>Could you please let me know what I am missing in my project to make this work?</p>
<p>This is <code>prometheus.yml</code></p>
<pre><code>global:
scrape_interval: 15s
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'kube-state-metrics'
static_configs:
- targets: ['10.36.1.10']
- targets: ['10.36.2.6']
- targets: ['10.36.1.12']
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- api_server: https://10.36.1.10:6443
role: node
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
tls_config:
insecure_skip_verify: true
- api_server: https://10.36.2.6:6443
role: node
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
tls_config:
insecure_skip_verify: true
- api_server: https://10.36.1.12:6443
role: node
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
tls_config:
insecure_skip_verify: true
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
- source_labels: [__meta_kubernetes_namespace]
action: replace
target_label: kubernetes_namespace
- source_labels: [__meta_kubernetes_pod_label_component]
action: replace
target_label: job
- source_labels: [__meta_kubernetes_pod_name]
action: replace
target_label: kubernetes_pod_name
</code></pre>
<p>And, this is <code>docker-compose.yml</code></p>
<pre><code>version: '3'
services:
prometheus:
image: prom/prometheus:v2.21.0
ports:
- 9000:9090
volumes:
- ./prometheus:/etc/prometheus
- prometheus-data:/prometheus
command: --web.enable-lifecycle --config.file=/etc/prometheus/prometheus.yml
grafana:
image: grafana/grafana:$GRAFANA_VERSION
environment:
GF_SECURITY_ADMIN_USER: $GRAFANA_ADMIN_USER
GF_SECURITY_ADMIN_PASSWORD: $GRAFANA_ADMIN_PASSWORD
ports:
- 3000:3000
volumes:
- grafana-storage:/var/lib/grafana
depends_on:
- prometheus
networks:
- internal
networks:
internal:
volumes:
prometheus-data:
grafana-storage:
</code></pre>
<p><a href="https://i.stack.imgur.com/eA6VZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eA6VZ.png" alt="ipK8s" /></a></p>
<p><a href="https://i.stack.imgur.com/YxuiX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YxuiX.png" alt="node_exporter" /></a></p>
| <p>You are running the <strong>Prometheus</strong> at the local and server level both.</p>
<p>server one working fine and getting the metrics of Kubernetes containers as it's on kubernetes.</p>
<p>while docker-compose one not working due to you are running it locally on docker not on kubernetes cluster.</p>
<p>it's the issue of the <strong>Target</strong> your Prometheus is not getting the metrics of your <strong>Kubernetes</strong> cluster.</p>
<p>for example, you are running the <strong>Prometheus</strong> locally but want to monitor the external <strong>Kubernetes</strong> cluster you have to expose your <strong>Kube-state-metrics</strong> service using <strong>IP</strong>.</p>
<p>in that case your Prometheus config will have job like</p>
<pre><code>scrape_configs:
- job_name: 'kube-state-metrics'
static_configs:
- targets: ['address'] //address of the k8s service IP
</code></pre>
<p>in your case you have to do something like</p>
<pre><code>kubernetes_sd_configs:
- api_server: https://<ip>:6443
role: node
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
tls_config:
insecure_skip_verify: true
</code></pre>
<p>this will fetch the metrics of kubernetes cluster and you can see data locally.</p>
<p>you can read this nice gist : <a href="https://gist.github.com/sacreman/b61266d2ec52cf3a1af7c278d9d93450" rel="nofollow noreferrer">https://gist.github.com/sacreman/b61266d2ec52cf3a1af7c278d9d93450</a></p>
|
<p>The certificate file of cert-manager is mounted on the nginx volume and is being used.</p>
<p>e.g</p>
<p><strong>nginx deploy.yaml -</strong></p>
<pre><code> volumes:
- name: secret-volume
secret:
secretName: my.test.app.com
- name: configmap-volume
configMap:
name: nginxconfigmap
containers:
- name: nginxhttps
image: bprashanth/nginxhttps:1.0
ports:
- containerPort: 443
- containerPort: 80
volumeMounts:
- mountPath: /etc/nginx/ssl
name: secret-volume
- mountPath: /etc/nginx/conf.d
name: configmap-volume
</code></pre>
<p><strong>and my nginx.conf file in</strong></p>
<pre><code> ssl_certificate /etc/nginx/ssl/tls.crt;
ssl_certificate_key /etc/nginx/ssl/tls.key;
</code></pre>
<p>And it's working very well.
In addition, the certificate is smoothly reissued by cert-manager.</p>
<p>However, because the reissued certificate file is not updated in the nginx container, it is said that the certificate has expired when accessed from a browser.</p>
<p>There is no problem if I force restart the pod, but I want to automate it.</p>
<p>I wonder if there is a way to automatically renew the certificate without restarting the pod forcibly.</p>
| <p>Not sure that the certificate is for your specific application using <strong>Nginx</strong> or main <code>Nginx ingress</code> which is handing the whole traffic of your cluster.</p>
<p>if it is the main <strong>Nginx</strong> which is handling the whole traffic of your cluster you can create the <strong>ingress</strong> and add the <strong>cert-manager</strong> integration there.</p>
<p>Cert-manager will manage the certificate and save it inside the secret and ingress will use that secret run time. Whenever the certificate gets renew secret content will game update while ingress will be using the same secret name.</p>
<p>in the above scenario there no pod restart required.</p>
<p>if you want to read and check the whole example please refer: <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes</a></p>
<p>in the above example, Nginx will run without having any certificate in volume while it will use the certificate stored in secret.</p>
<p>For YAML example if <strong>issuer</strong> and <strong>ingress</strong> please check : <a href="https://stackoverflow.com/a/67184948/5525824">https://stackoverflow.com/a/67184948/5525824</a></p>
|
<p>I have install bitnami/external-dns on my EKS Kubernetes cluster. The role of the pod is to create new records in my Route53 hosted zone once an Ingress expects the records to be there. No problems to this point.</p>
<p>But when removing the Ingress, the Route53 records are not deleted. What is expected to delete these records? What do I do wrong?</p>
<p>Installation of External DNS</p>
<pre><code>helm install extdns bitnami/external-dns \
--set provider=aws \
--set interval=1m \
--set logLevel=debug \
</code></pre>
<p>The Ingress</p>
<pre><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: {{$.Chart.Name}}-ingress
annotations:
kubernetes.io/ingress.class: alb
alb.ingress.kubernetes.io/target-type: ip
alb.ingress.kubernetes.io/scheme: internet-facing
alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-west-2:xxxxxxxx:certificate/some-uuid
alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTP": 81}, {"HTTPS":443}]'
external-dns.alpha.kubernetes.io/hostname: zzz1.blah.nl
labels:
app: {{$.Chart.Name}}-service
spec:
rules:
- host: zzz1.blah.nl
http:
paths:
- path: /*
backend:
serviceName: {{$.Chart.Name}}-service
servicePort: 8080
- http:
paths:
- path: /zzz1/*
backend:
serviceName: {{$.Chart.Name}}-service
servicePort: 8080
</code></pre>
<p>External DNS logging</p>
<pre><code>time="2021-05-05T20:31:02Z" level=debug msg="Refreshing zones list cache"
time="2021-05-05T20:31:02Z" level=debug msg="Considering zone: /hostedzone/xxxx (domain: local.)"
time="2021-05-05T20:31:02Z" level=debug msg="Considering zone: /hostedzone/xxxx (domain: blah.nl.)"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service kube-system/aws-load-balancer-webhook-service"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service default/extdns-external-dns"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service default/module1-service"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service default/kubernetes"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service kube-system/kube-dns"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service kubernetes-dashboard/kubernetes-dashboard"
time="2021-05-05T20:31:03Z" level=debug msg="No endpoints could be generated from service kubernetes-dashboard/dashboard-metrics-scraper"
time="2021-05-05T20:31:03Z" level=debug msg="Endpoints generated from ingress: default/module1-ingress: [zzz1.blah.nl 0 IN CNAME k8s-default-module1i-0000000-1693479811.us-west-2.elb.amazonaws.com [] zzz1.liberaalgeluid.nl 0 IN CNAME k8s-default-module1i-000000-1693479811.us-west-2.elb.amazonaws.com []]"
time="2021-05-05T20:31:03Z" level=debug msg="Removing duplicate endpoint zzz1.blah.nl 0 IN CNAME k8s-default-module1i-000000000-1693479811.us-west-2.elb.amazonaws.com []"
time="2021-05-05T20:31:03Z" level=debug msg="Modifying endpoint: zzz1.blah.nl 0 IN CNAME k8s-default-module1i-000000000-1693479811.us-west-2.elb.amazonaws.com [], setting alias=true"
time="2021-05-05T20:31:03Z" level=debug msg="Modifying endpoint: zzz1.blah.nl 0 IN CNAME k8s-default-module1i-000000000-1693479811.us-west-2.elb.amazonaws.com [{alias true}], setting aws/evaluate-target-health=true"
time="2021-05-05T20:31:03Z" level=debug msg="Refreshing zones list cache"
time="2021-05-05T20:31:03Z" level=debug msg="Considering zone: /hostedzone/Z000000000 (domain: blah.nl.)"
time="2021-05-05T20:31:03Z" level=debug msg="Considering zone: /hostedzone/Z000000000 (domain: local.)"
time="2021-05-05T20:31:03Z" level=info msg="All records are already up to date"
^
</code></pre>
| <p>The default <code>--policy</code> option in the Chart is <code>upsert-only</code>, this is different from the underlying default in ext-dns itself which is <code>sync</code>. In <code>upsert-only</code> mode, it will not delete anything. This is usually for safety as cleanup can happen in batches and under user supervision. You can override the policy value back to <code>sync</code> if you would like though (<a href="https://github.com/bitnami/charts/blob/05a5bd69206574f3f8638197eb98da2164343a42/bitnami/external-dns/values.yaml#L432" rel="nofollow noreferrer">https://github.com/bitnami/charts/blob/05a5bd69206574f3f8638197eb98da2164343a42/bitnami/external-dns/values.yaml#L432</a>).</p>
|
<p>I am trying to use helm charts with k0s.</p>
<p>Having my own helm-charts app, I would like to create a local repo. But I cannot use the <code>serve</code> command since I am using version: 3.5.4 and the serve command had been ditched for security concerns.</p>
<p>I am not sure now how to create a local repo ? and where can I find tutorials or examples ?</p>
<p>Also, how to deploy my chart in k0s cluster ?</p>
| <p>I would try to use <a href="https://github.com/helm/chartmuseum" rel="nofollow noreferrer">ChartMuseum</a> instead. You can follow the <a href="https://chartmuseum.com/docs/#using-with-local-filesystem-storage" rel="nofollow noreferrer">docs to create a local filesystem chart</a>.</p>
<p>You simply deploy the same way as with helm v2. Make sure you <a href="https://helm.sh/docs/helm/helm_repo_add/" rel="nofollow noreferrer">add the chart repo</a> and you have <a href="https://kubernetes.io/docs/tasks/tools/" rel="nofollow noreferrer">kubectl</a> configured to point to the cluster that you want to talk to so that <code>~/.kube/config</code> has the right configuration.</p>
|
<p>I am trying to understand the Node-Controller in Kubernetes. Kubernetes <a href="https://kubernetes.io/docs/concepts/architecture/nodes/#heartbeats" rel="nofollow noreferrer">documentation</a> mentions that node heartbeats are done using NodeStatus and LeaseObject updates. Someone, please explain why both mechanisms are needed for monitoring node health.
Does Kubernetes master internally use a job/cronjob for a node health check processing?</p>
| <p><a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#lease-v1-coordination-k8s-io" rel="nofollow noreferrer">Lease</a> is a lightweight resource, which improves the performance of the node heartbeats as the cluster scales.</p>
<p>The Lease objects are tracked as a way of helping the heartbeats to continue functioning efficiently as a cluster scales up. According to the docs, this would be their primary function relating to heartbeats.</p>
<p>Whereas the <code>NodeStatus</code> is used for Heartbeats by the kubelet, <code>NodeStatus</code> is also an important signal for other controllers in k8s.</p>
<p>For example: the k8s scheduler is responsible for scheduling pods on nodes. It tries to find the best fit for a node to optimize memory, cpu, and other usage on the node. It wouldn't however want to schedule a pod on a node with <a href="https://kubernetes.io/docs/concepts/architecture/nodes/#node-status" rel="nofollow noreferrer">node status</a> condition set to <code>NetworkUnavailable: true</code> or some other condition which would make the pod unsuitable to run on that node.</p>
<p>If there is a signal or signals that you don't know or understand, there is a good chance there is a controller that uses that field or signal to accomplish its logic.</p>
<p><strong>EDIT:</strong></p>
<p>The node-controller is a part of the <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kube-controller-manager/" rel="nofollow noreferrer">kube-controller-manager</a>:</p>
<blockquote>
<p>The Kubernetes controller manager is a daemon that embeds the core
control loops shipped with Kubernetes. In applications of robotics and
automation, a control loop is a non-terminating loop that regulates
the state of the system. In Kubernetes, a controller is a control loop
that watches the shared state of the cluster through the apiserver and
makes changes attempting to move the current state towards the desired
state. Examples of controllers that ship with Kubernetes today are the
replication controller, endpoints controller, namespace controller,
and serviceaccounts controller.</p>
</blockquote>
<p>Logically, each controller is a separate process, but to reduce complexity, they are all compiled into a single binary and run in a single process.</p>
<p><strong>EDIT_2</strong>:</p>
<p>Based on your latest comments, we have 2 additional points to address:</p>
<blockquote>
<ol>
<li>"how the node-controller processes the node health check"</li>
</ol>
</blockquote>
<p>While implementing k8s, you probably don't need to know this level of detail. All the details which should be useful for you are already in the <a href="https://kubernetes.io/docs/concepts/overview/components/#kube-controller-manager" rel="nofollow noreferrer">linked public docs</a>. There is no need to worry about that but I understand that it brought the more practical question:</p>
<blockquote>
<ol start="2">
<li>I am not sure how much load a big cluster can generate.</li>
</ol>
</blockquote>
<p>This is where the <a href="https://kubernetes.io/docs/setup/best-practices/cluster-large/" rel="nofollow noreferrer">Considerations for large clusters</a> comes to help. It will show you how to handle big clusters and which tools are there at your disposal when it comes to managing them.</p>
|
<p>My Kubernetes user is not admin in the cluster. So I just cannot create a cluster role binding for filebeat service account. I am using auto discover in filebeat. Can someone help how can I achieve this without clusterrole.</p>
<pre><code>apiVersion: v1
kind: ConfigMap
metadata:
name: filebeat-config
namespace: logging
labels:
k8s-app: filebeat
kubernetes.io/cluster-service: "true"
data:
filebeat.yml: |-
setup.dashboards.enabled: false
setup.template.enabled: true
setup.template.settings:
index.number_of_shards: 1
filebeat.modules:
- module: system
syslog:
enabled: true
#var.paths: ["/var/log/syslog"]
auth:
enabled: true
#var.paths: ["/var/log/authlog"]
filebeat.autodiscover:
providers:
- type: kubernetes
templates:
- condition:
equals:
kubernetes.namespace: microsrv-test
config:
- type: docker
json.keys_under_root: true
json.add_error_key: true
json.message_key: log
containers:
ids:
- "${data.kubernetes.container.id}"
processors:
- drop_event:
when.or:
- and:
- regexp:
message: '^\d+\.\d+\.\d+\.\d+ '
- equals:
fileset.name: error
- and:
- not:
regexp:
message: '^\d+\.\d+\.\d+\.\d+ '
- equals:
fileset.name: access
- add_cloud_metadata:
- add_kubernetes_metadata:
- add_docker_metadata:
output.elasticsearch:
hosts: ["elasticsearch:9200"]
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: filebeat
namespace: logging
labels:
k8s-app: filebeat
kubernetes.io/cluster-service: "true"
spec:
template:
metadata:
labels:
k8s-app: filebeat
kubernetes.io/cluster-service: "true"
spec:
serviceAccountName: filebeat
terminationGracePeriodSeconds: 30
containers:
- name: filebeat
image: docker.elastic.co/beats/filebeat:7.3.2
imagePullPolicy: Always
args: [
"-c", "/etc/filebeat.yml",
"-e",
]
env:
- name: ELASTICSEARCH_HOST
value: elasticsearch
- name: ELASTICSEARCH_PORT
value: "9200"
- name: KIBANA_HOST
value: kibana
- name: KIBANA_PORT
value: "5601"
securityContext:
runAsUser: 0
volumeMounts:
- name: config
mountPath: /etc/filebeat.yml
readOnly: true
subPath: filebeat.yml
- name: data
mountPath: /usr/share/filebeat/data
- name: varlog
mountPath: /var/log
readOnly: true
- name: varlibdockercontainers
mountPath: /var/lib/docker/containers
readOnly: true
- name: dockersock
mountPath: /var/run/docker.sock
volumes:
- name: config
configMap:
defaultMode: 0600
name: filebeat-config
- name: varlog
hostPath:
path: /var/log
- name: varlibdockercontainers
hostPath:
path: /var/lib/docker/containers
- name: dockersock
hostPath:
path: /var/run/docker.sock
- name: data
emptyDir: {}
---
</code></pre>
<p>Cluster Roles and role bindings</p>
<pre><code>apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
name: filebeat
subjects:
- kind: ServiceAccount
name: filebeat
namespace: logging
roleRef:
kind: ClusterRole
name: filebeat
apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
name: filebeat
labels:
k8s-app: filebeat
rules:
- apiGroups: [""] # "" indicates the core API group
resources:
- namespaces
- pods
verbs:
- get
- watch
- list
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: filebeat
namespace: logging
labels:
k8s-app: filebeat
</code></pre>
<p>I have tried creating non cluster role and rolebinding as below,</p>
<pre><code>apiVersion: v1
kind: ServiceAccount
metadata:
name: filebeat
namespace: logging
labels:
k8s-app: filebeat
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: filebeat
namespace: logging
labels:
k8s-app: filebeat
rules:
- apiGroups: [""] # "" indicates the core API group
resources:
- pods
verbs:
- get
- watch
- list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: filebeat
namespace: logging
subjects:
- kind: ServiceAccount
name: filebeat
namespace: logging
roleRef:
kind: Role
name: filebeat
apiGroup: rbac.authorization.k8s.io
</code></pre>
<p>but I am getting error.</p>
<blockquote>
<p>Performing a resource sync err kubernetes api: Failure 403 pods is
forbidden: User "system:serviceaccount:xxxxx:filebeat" cannot list
resource "pods" in API group "" at the cluster scope for *v1.PodList|</p>
</blockquote>
| <p>Unfortunately, it will not work the way you want it and the error you are getting indicates it perfectly:</p>
<pre><code>Performing a resource sync err kubernetes api: Failure 403 pods is forbidden: User "system:serviceaccount:xxxxx:filebeat" cannot list resource "pods" in API group "" at the cluster scope for *v1.PodList|
</code></pre>
<p>Notice the most important part which is: <code>at the cluster scope</code>. You could also check whether an action is allowed by executing the <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands" rel="nofollow noreferrer">kubectl auth can-i</a> command. More about that can be found in the <a href="https://kubernetes.io/docs/reference/access-authn-authz/authorization/" rel="nofollow noreferrer">Authorization Overview</a>.</p>
<p>This brings us to the differences between <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/#role-and-clusterrole" rel="nofollow noreferrer">Role and ClusterRole</a>:</p>
<blockquote>
<p>An RBAC <code>Role</code> or <code>ClusterRole</code> contains rules that represent a set of
permissions. Permissions are purely additive (there are no "deny"
rules).</p>
<p>A <code>Role</code> always sets permissions <strong>within a particular namespace</strong>;
when you create a <code>Role</code>, you have to specify the namespace it belongs
in.</p>
<p><code>ClusterRole</code>, by contrast, <strong>is a non-namespaced resource</strong>. The
resources have different names (<code>Role</code> and <code>ClusterRole</code>) because a
Kubernetes object always has to be either namespaced or not
namespaced; it can't be both.</p>
<p><code>ClusterRoles</code> have several uses. You can use a <code>ClusterRole</code> to:</p>
<ul>
<li><p>define permissions on namespaced resources and be granted within individual namespace(s)</p>
</li>
<li><p>define permissions on namespaced resources and be granted across all namespaces</p>
</li>
<li><p>define permissions on cluster-scoped resources</p>
</li>
</ul>
<p>If you want to define a role within a namespace, use a Role; if you
want to define a role cluster-wide, use a <code>ClusterRole</code>.</p>
</blockquote>
<p>And between <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/#rolebinding-and-clusterrolebinding" rel="nofollow noreferrer">RoleBinding and ClusterRoleBinding</a>:</p>
<blockquote>
<p>A role binding grants the permissions defined in a role to a user or
set of users. It holds a list of subjects (users, groups, or service
accounts), and a reference to the role being granted. A <code>RoleBinding</code>
grants permissions within a specific namespace whereas a
<code>ClusterRoleBinding</code> grants that access cluster-wide.</p>
<p>A <code>RoleBinding</code> may reference any Role in the same namespace.
Alternatively, a <code>RoleBinding</code> can reference a <code>ClusterRole</code> and bind that
<code>ClusterRole</code> to the namespace of the <code>RoleBinding</code>. If you want to bind a
<code>ClusterRole</code> to all the namespaces in your cluster, you use a
<code>ClusterRoleBinding</code>.</p>
</blockquote>
<p>So it is impossible to get the cluster scope permissions by using <code>Role</code> and <code>RoleBinding</code>.</p>
<p>You will most likely have to ask your Admin to help you solve this issue.</p>
|
<p>I am using K8s 1.21.0 in a bare metal configuration without a loadbalancer.
I've installed nginx ingress in a NodePort configuration using helm:</p>
<p><code>helm install ********** nginx-stable/nginx-ingress --set "controller.service.type=NodePort" --namespace=nginx-ingress</code></p>
<p>Edit: I've also tried this as a LoadBalancer, but the result is the same.</p>
<p>I've deployed a simple nginx web server with the following yaml:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: www-deployment
spec:
selector:
matchLabels:
app: www
replicas: 1
template:
metadata:
labels:
app: www
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
</code></pre>
<p>and a service:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: webserver-service
spec:
selector:
app: www
ports:
- protocol: TCP
port: 80
targetPort: 80
</code></pre>
<p>with the following ingress:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: test-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: k8stest.************.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: webserver-service
port:
number: 80
</code></pre>
<p>From my control plane I can curl the cluster IP for the service fine. I get what I expect:</p>
<pre><code>curl 10.103.183.94
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>....
</code></pre>
<p>However, If I curl my ingress controller via its service, I always get a 404.</p>
<pre><code>curl -H "Host: k8stest.**********.com" http://10.106.95.61
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.19.9</center>
</body>
</html>
</code></pre>
<p>I've tried removing the rewrite target annotation, but this leads to the same result. 404.</p>
<p>It seems that the ingress controller is not communicating with my service.</p>
<p>In the ingress controller logs I am just seeing:</p>
<pre><code>[06/May/2021:08:31:53 +0000] "GET / HTTP/1.1" 404 153 "-" "curl/7.68.0" "-"
</code></pre>
<p>I've also tried with and without the host value in the ingress configuration and also tried using /test instead of just / in the ingress path. Nothing ever gets sent to the backend nginx service.</p>
| <p>Ok, I ditched the helm installed nginx ingress controller and went with the bare metal installation as documented here:</p>
<p><a href="https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal</a></p>
<p>As soon as this was up and running, everything sprang into life as expected.</p>
|
<p>I'm trying to configure a daemonset to run on the global pid namespace resulting the ability to see other processes in the host, including the containers' processes.</p>
<p>I couldn't find an option to achieve this.
In general, what I'm looking for is close to the sidecar container <code>shareProcessNamespace</code> attribute only on the host level.</p>
| <p>There is an attribute that allows this - <code>hostPID: true</code></p>
<p>So the yaml file should looks something like that:</p>
<pre><code>apiVersion: apps/v1
kind: DaemonSet
metadata:
name: busybox
spec:
selector:
matchLabels:
name: busybox
template:
metadata:
labels:
name: busybox
spec:
hostPID: true
containers:
- name: busybox
image: busybox
command: [ "sh", "-c", "sleep 1h" ]
</code></pre>
<p>More info in:</p>
<ul>
<li><a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces</a></li>
<li><a href="https://medium.com/@chrispisano/limiting-pod-privileges-hostpid-57ce07b05896" rel="nofollow noreferrer">https://medium.com/@chrispisano/limiting-pod-privileges-hostpid-57ce07b05896</a></li>
</ul>
|
<p>I am trying to use helm charts with k0s.</p>
<p>Having my own helm-charts app, I would like to create a local repo. But I cannot use the <code>serve</code> command since I am using version: 3.5.4 and the serve command had been ditched for security concerns.</p>
<p>I am not sure now how to create a local repo ? and where can I find tutorials or examples ?</p>
<p>Also, how to deploy my chart in k0s cluster ?</p>
| <p>Yes it does, you can also utilize k8slens.dev to easily deploy helm charts to your Kubernetes clusters. Regardless of the distro..</p>
|
<p>I've got this ingress.yaml base configuration:</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
labels:
sia: aza
app: asap-ingress-internal
name: asap-ingress-internal
annotations:
kubernetes.io/ingress.class: "nginx-external"
nginx.ingress.kubernetes.io/use-regex: "true"
spec:
rules:
- host: the-host-value
http:
paths:
- path: /asap-srv-template/(.*)
backend:
serviceName: asap-srv-template
servicePort: 8080
</code></pre>
<p>And want to replace the spec.rules.host value only (and keep all http.paths as is.</p>
<p>So I create a env-var.yaml like this :</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: asap-ingress-internal
spec:
rules:
- host: the.real.hostname
</code></pre>
<p>But the result is the following:</p>
<pre><code>$ kustomize build
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx-external
nginx.ingress.kubernetes.io/use-regex: "true"
labels:
app: asap-ingress-internal
env: dev
sia: aza
name: asap-ingress-internal
namespace: aza-72461-dev
spec:
rules:
- host: the.real.hostname
</code></pre>
<p>I have lost all http.paths configuration and I can't find out how to do.</p>
<p>I tried with patches: or patchesStrategicMerge in kustomization.yaml but the result is always the same.</p>
<p>Any help would be greatly appreciated</p>
| <p>You can use a json patch for this, below is an example.</p>
<p>Here is an example <code>kustomization.yaml</code>. It will call out a patch in the <code>patches</code> section:</p>
<pre><code>apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base/app1
patches:
- target:
kind: Ingress
name: my-ingress
path: ingress-patch.json
</code></pre>
<p>Here would be an example <code>ingress-patch.json</code>:</p>
<pre><code>[
{
"op": "replace",
"path": "/spec/rules/0/host",
"value": "the.real.hostname"
}
]
</code></pre>
|
<p>Since we don't need to configure most of the Infrastructure services for Containers and Kubernetes, still we have ability to manage different Infrastructure services.
Does this make them Infrastructure as a Service or Platform as a Service?</p>
| <p>kubernetes is considered PaaS when the control p<a href="https://learn.microsoft.com/en-us/azure/aks/concepts-clusters-workloads" rel="noreferrer">lane components</a>: the scheduler, the API server, ETCD (key-value metadata)and controller are managed by the provider
some examples are Microsoft <a href="https://azure.microsoft.com/en-us/services/kubernetes-service/" rel="noreferrer">AKS</a>, Google <a href="https://cloud.google.com/kubernetes-engine" rel="noreferrer">GKE</a>, AWS <a href="https://aws.amazon.com/eks/?whats-new-cards.sort-by=item.additionalFields.postDateTime&whats-new-cards.sort-order=desc&eks-blogs.sort-by=item.additionalFields.createdDate&eks-blogs.sort-order=desc" rel="noreferrer">EKS</a>.
It is considered IaaS if you built and maintain all the components</p>
|
<p>I tried to run a Helm upgrade before running <code>helm repo update</code> and now it seems to be permanently stuck in "STATUS: pending-upgrade" and won't let me try to run the upgrade again.</p>
<p>Trying to run:
<code>helm upgrade --namespace coder --install --force --atomic --wait --version 1.13.2 --values ./coder.yaml coder coder/coder</code></p>
<p>outputs: <code>Error: UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress</code></p>
| <p>This solution worked for me:</p>
<pre><code>kubectl get secrets
kubectl delete secret sh.helm.release.v1.<RELEASE_NAME>.v<LATEST_REVISION>
</code></pre>
<p>Following the resolution described in <a href="https://github.com/helm/helm/issues/8987#issuecomment-786149813" rel="noreferrer">this issue</a></p>
|
<p>I use next command to check dns issue in my k8s:</p>
<pre><code>kubectl apply -f https://k8s.io/examples/admin/dns/dnsutils.yaml
kubectl exec -i -t dnsutils -- nslookup kubernetes.default
</code></pre>
<p>The nslookup result is:</p>
<pre><code>;; connection timed out; no servers could be reached
command terminated with exit code 1
</code></pre>
<p><strong>dnsutils.yaml:</strong></p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: dnsutils
namespace: default
spec:
containers:
- name: dnsutils
image: gcr.io/kubernetes-e2e-test-images/dnsutils:1.3
command:
- sleep
- "3600"
imagePullPolicy: IfNotPresent
restartPolicy: Always
</code></pre>
<p><strong>NOTE:</strong> it's a machine which default disable all ports, so I ask our IT admin already open the port based on next doc <a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#check-required-ports" rel="nofollow noreferrer">check-required-ports</a>, I'm not sure if this matters.</p>
<p>And use next I could get the pod ip of coredns.</p>
<pre><code>kubectl get pods -n kube-system -o wide | grep core
coredns-7877db9d45-swb6c 1/1 Running 0 2m58s 10.244.1.8 node2 <none> <none>
coredns-7877db9d45-zwc8v 1/1 Running 0 2m57s 10.244.0.6 node1 <none> <none>
</code></pre>
<p>Here, <code>10.244.0.6</code> is my master while <code>10.244.1.8</code> is my working node.</p>
<p>Then if I directly specify coredns pod ip:</p>
<p><strong>master node ok:</strong></p>
<pre><code>kubectl exec -i -t dnsutils -- nslookup kubernetes.default 10.244.0.6
Server: 10.244.0.6
Address: 10.244.0.6#53
Name: kubernetes.default.svc.cluster.local
Address: 10.96.0.1
</code></pre>
<p><strong>work node not ok:</strong></p>
<pre><code># kubectl exec -i -t dnsutils -- nslookup kubernetes.default 10.244.1.8
;; connection timed out; no servers could be reached
command terminated with exit code 1
</code></pre>
<p>So, the question narrow down to why COREDNS on work node not works? Anything I need to pay attention?</p>
<p><strong>Environment:</strong></p>
<ul>
<li>OS: ubuntu18.04</li>
<li>K8S: v1.21.0</li>
<li>Cluster boot command:</li>
</ul>
<pre><code>kubeadm init --pod-network-cidr=10.244.0.0/16
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
</code></pre>
| <p>Finally, I find the root cause, this is hardware firewall issue, see <a href="https://github.com/flannel-io/flannel/blob/master/Documentation/troubleshooting.md#firewalls" rel="nofollow noreferrer">this</a>:</p>
<blockquote>
<p><strong>Firewalls</strong><br/>
When using udp backend, flannel uses UDP port 8285 for sending encapsulated packets.<br/>
When using vxlan backend, kernel uses UDP port 8472 for sending encapsulated packets.<br/>
Make sure that your firewall rules allow this traffic for all hosts participating in the overlay network.<br/>
Make sure that your firewall rules allow traffic from pod network cidr visit your kubernetes master node.</p>
</blockquote>
<ul>
<li>When <code>nslookup client</code> on the same node of <code>dns server</code>, it won't trigger firewall block, so everything is ok.</li>
<li>When <code>nslookup client</code> not on the same node of <code>dns server</code>, it will trigger firewall block, so we can't access dns server.</li>
</ul>
<p>So, after open the ports, everything ok now.</p>
|
<p>I have a Tekton <code>Pipeline</code> and <code>PipelineRun</code> definitions. But, I couldn't achieve to run <code>Pipeline</code> via passing parameter.</p>
<pre><code>apiVersion: tekton.dev/v1beta1
kind: PipelineRun
metadata:
generateName: build-deploy-
labels:
tekton.dev/pipeline: build-deploy
spec:
serviceAccountName: tekton-build-bot
pipelineRef:
name: build-deploy
params:
- name: registry-address
value: $(REG_ADDRESS)
- name: repo-address
#value: $(REPO_ADDRESS)
value: $(REPO_ADDRESS)
- name: repo-name
value: $(REPO_NAME)
- name: version
value: $(VERSION)
workspaces:
- name: source
persistentVolumeClaim:
claimName: my-pvc
</code></pre>
<p>How can I pass while parameters while trying to run that runner with following command <code>kubectl create -f pipelinerun.yaml</code>?</p>
<p>Example:</p>
<p><code>value: $(REG_ADDRESS)</code> -> I wanted to pass registry address as right before the running pipeline instead of giving hard-coded constant.</p>
<p>Any ideas?</p>
| <p>You cannot pass those parameters when using <code>kubectl create</code>.</p>
<p>There are two alternatives:</p>
<h2>Use tkn cli</h2>
<p>You can use <a href="https://github.com/tektoncd/cli" rel="nofollow noreferrer">tkn</a>, a purpose made CLI for Tekton. Then you can start a run of a Pipeline with, e.g.:</p>
<pre><code>tkn pipeline start build-deploy \
--param registry-address=yay \
--param repo-name=nay \
--workspace name=source,claimName=my-pvc
</code></pre>
<h2>Initiate pipeline with Trigger</h2>
<p>You can setup a <a href="https://github.com/tektoncd/triggers" rel="nofollow noreferrer">Trigger</a> that initiates runs of your Pipeline on certain events, e.g. when you push to Git.</p>
<p>Then your <code>PipelineRun</code> template with parameter mapping is done using a <a href="https://github.com/tektoncd/triggers/blob/main/docs/triggertemplates.md" rel="nofollow noreferrer">TriggerTemplate</a></p>
|
<p>I just installed the controller via Helm, I can list the helm packages via <code>helm list</code>, but is it possible to list all the controllers running in the cluster via <code>kubectl</code> or <code>api-query</code>?</p>
| <p>Not sure if there is a way to list controllers in k8s. every resource/object in k8s is controlled by a controller (control loop) with spec fields as values for desired state. if you have deployed a controller outside control plane (built-in controllers) then what i will do to find the controller:</p>
<ol>
<li>find the resource/object by running <code>kubectl api-resources</code></li>
<li>verify the list and find the resource name</li>
<li>search all pods and grep the resource name <code>kubectl get pods --all-namespaces |grep <resource-name></code></li>
<li>the pod in the above search will be running you controller</li>
<li>NOTE: the pod name might not contain the resource name but it will contain some similar name. i just share this info to understand what a controller is and how external controller works other than (build in controllers).</li>
</ol>
<p>more info - <a href="https://kubernetes.io/docs/concepts/architecture/controller/" rel="noreferrer">https://kubernetes.io/docs/concepts/architecture/controller/</a></p>
|
<p>Recently, I tried to setup letsencrypt using microk8s and the default ingress controller on a bare-metal server.</p>
<p>I found a few guides online that were very useful but it seems as if there must have been a recent update to microk8s that changed the way the ingress controller is configured.</p>
<p>To save you guys time, I wrote out exactly what I did.</p>
<p>Here are some useful resources if you get stuck or to get a better understanding.</p>
<p><a href="https://cert-manager.io/docs/installation/kubernetes/" rel="noreferrer">https://cert-manager.io/docs/installation/kubernetes/</a></p>
<p><a href="https://cert-manager.io/docs/tutorials/acme/ingress/" rel="noreferrer">https://cert-manager.io/docs/tutorials/acme/ingress/</a></p>
<p>This link was really useful for troubleshooting</p>
<p><a href="https://cert-manager.io/docs/faq/acme/" rel="noreferrer">https://cert-manager.io/docs/faq/acme/</a></p>
| <p><strong>This guide is to set up Letsencrypt with Kubernetes using Microk8s and the default Ingress controller.</strong></p>
<p><strong>Versions used:</strong></p>
<p><em>microk8s version 1.21/stable</em></p>
<p><em>cert-manager v1.3.1</em></p>
<p><strong>Pre-requisite:</strong> Forward ports 80 & 443 to your server. Set up a domain name that points to your server.</p>
<p>Install microk8s</p>
<pre><code>snap install microk8s --classic --channel=1.21/stable
</code></pre>
<p>Enable dns and ingress</p>
<pre><code>sudo microk8s enable dns ingress
</code></pre>
<p>We'll create a test webserver deployment/service using the nginx webserver image to test web traffic</p>
<p><em><strong>webserver-depl-svc.yaml</strong></em></p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: webserver-depl
spec:
selector:
matchLabels:
app: webserver-app
template:
metadata:
labels:
app: webserver-app
spec:
containers:
- name: webserver-app
image: nginx:1.8
---
apiVersion: v1
kind: Service
metadata:
name: webserver-svc
spec:
selector:
app: webserver-app
ports:
- name: webserver-app
protocol: TCP
port: 80
targetPort: 80
</code></pre>
<p>apply the config file</p>
<pre><code>sudo microk8s kubectl apply -f webserver-depl-svc.yaml
</code></pre>
<p>now to configure the default ingress to serve the test webserver</p>
<p><em><strong>ingress-routes.yaml</strong></em></p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-routes
spec:
rules:
#change yourdomain.com to your domain
- host: yourdomain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: webserver-svc
port:
number: 80
</code></pre>
<p>Apply the ingress routes</p>
<pre><code>sudo microk8s kubectl apply -f ingress-routes.yaml
</code></pre>
<p>When you visit <em>yourdomain.com</em>, you should see the default "welcome to nginx!" splash screen.</p>
<p>Now to install cert-manager <a href="https://cert-manager.io/docs/installation/kubernetes/" rel="nofollow noreferrer">https://cert-manager.io/docs/installation/kubernetes/</a></p>
<pre><code>sudo microk8s kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.3.1/cert-manager.yaml
</code></pre>
<p>The next command should show 3 pods to confirm cert-manager is installed and running</p>
<pre><code>sudo microk8s kubectl get pods -n=cert-manager
</code></pre>
<p>Now to create the certificate issuer config. A detail to notice is that the class used in this config is <em>public</em> as opposed to <em>nginx</em>. This may be microk8s specific. <a href="https://cert-manager.io/docs/tutorials/acme/ingress/" rel="nofollow noreferrer">https://cert-manager.io/docs/tutorials/acme/ingress/</a></p>
<p><em><strong>letsencrypt-staging.yaml</strong></em></p>
<pre><code>apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-staging
spec:
acme:
#change to your email
email: youremail@gmail.com
server: https://acme-staging-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-staging
solvers:
- http01:
ingress:
class: public
</code></pre>
<p><em><strong>letsencrypt-prod.yaml</strong></em></p>
<pre><code>apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
#change to your email
email: youremail@gmail.com
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: public
</code></pre>
<p>Apply both issuer configs</p>
<pre><code>sudo microk8s kubectl apply -f letsencrypt-staging.yaml
sudo microk8s kubectl apply -f letsencrypt-prod.yaml
</code></pre>
<p>now to update <em><strong>ingress-routes.yaml</strong></em> to use the staging certificate.</p>
<pre><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: ingress-routes
annotations:
cert-manager.io/cluster-issuer: "letsencrypt-staging"
spec:
tls:
- hosts:
#change to your domain
- yourdomain.com
secretName: tls-secret
rules:
#change to your domain
- host: yourdomain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: webserver-svc
port:
number: 80
</code></pre>
<p>Apply the update</p>
<pre><code>sudo microk8s kubectl apply -f ingress-routes.yaml
</code></pre>
<p>Run the next command to confirm Ready=True</p>
<pre><code>sudo microk8s kubectl get certificate
</code></pre>
<p>If it returned true, that means HTTP-01 challenge was successful.
You can see more detail at the end of output running the next command</p>
<pre><code>sudo microk8s kubectl describe certificate tls-secret
</code></pre>
<p>Now to change <em><strong>ingress-routes.yaml</strong></em> to use the production certificate.</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-routes
annotations:
cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
tls:
- hosts:
#change to your domain
- yourdomain.com
secretName: tls-secret
rules:
#change to your domain
- host: yourdomain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: webserver-svc
port:
number: 80
</code></pre>
<p>Apply the update</p>
<pre><code>sudo microk8s kubectl apply -f ingress-routes.yaml
</code></pre>
<p>Now the moment of truth. Run the next command to confirm a certificate was generated. Ready=True</p>
<pre><code>sudo microk8s kubectl get certificate
</code></pre>
<p>Run the next command and look at the final output to verify the certificate was issued.</p>
<pre><code>sudo microk8s kubectl describe certificate tls-secret
</code></pre>
<p>Now if you visit your domain. You should see the little lock of success! :-)</p>
|
<p>I've added <code>—-runtime-config=batch/v2alpha1=true</code> to the <code>kube-apiserver</code> config like so:</p>
<pre><code> ... other stuff
command:
- "/hyperkube"
- "apiserver"
- "--admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota"
- "--address=0.0.0.0"
- "--allow-privileged"
- "--insecure-port=8080"
- "--secure-port=443"
- "--cloud-provider=azure"
- "--cloud-config=/etc/kubernetes/azure.json"
- "--service-cluster-ip-range=10.0.0.0/16"
- "--etcd-servers=http://127.0.0.1:2379"
- "--etcd-quorum-read=true"
- "--advertise-address=10.240.255.15"
- "--tls-cert-file=/etc/kubernetes/certs/apiserver.crt"
- "--tls-private-key-file=/etc/kubernetes/certs/apiserver.key"
- "--client-ca-file=/etc/kubernetes/certs/ca.crt"
- "--service-account-key-file=/etc/kubernetes/certs/apiserver.key"
- "--storage-backend=etcd2"
- "--v=4"
- "—-runtime-config=batch/v2alpha1=true"
... etc
</code></pre>
<p>but after restarting the master <code>kubectl api-versions</code> still shows only <code>batch/v1</code>, no <code>v2alpha1</code> to be seen.</p>
<pre><code>$ kubectl api-versions
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1beta1
apps/v1beta1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
batch/v1
certificates.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1alpha1
rbac.authorization.k8s.io/v1beta1
settings.k8s.io/v1alpha1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
</code></pre>
<p>Here's my job definition:</p>
<pre><code>kind: CronJob
apiVersion: batch/v2alpha1
metadata:
name: mongo-backup
spec:
schedule: "* */1 * * *"
jobTemplate:
spec:
... etc
</code></pre>
<p>And the error I get when I try to create the job:</p>
<pre><code>$ kubectl create -f backup-job.yaml
error: error validating "backup-job.yaml": error validating data: unknown object type schema.GroupVersionKind{Group:"batch", Version:"v2alpha1", Kind:"CronJob"}; if you choose to ignore these errors, turn validation off with --validate=false
$ kubectl create -f backup-job.yaml --validate=false
error: unable to recognize "backup-job.yaml": no matches for batch/, Kind=CronJob
</code></pre>
<p>What else do I need to do?</p>
<p>PS. this is on Azure ACS, I don't think it makes a difference though.</p>
| <p>You may use the latest API versions here <code>apiVersion: batch/v1beta1</code> that should fix the issue.</p>
|
<p>Azure Admins created a cluster for us.
On VM I installed <code>"az cli" and "kubectl"</code>.
With my account from Azure Portal I can see that Kubernetes Service and Resource Group to which it belongs.
From the level of that cluster in Azure Portal I can see that I have a role:</p>
<blockquote>
<p>"AKS Cluster Admin Operator"</p>
</blockquote>
<p>I am logged on VM with kubectl with my account. I need to config my kubectl to work with our cluster.
When I try to execute:</p>
<pre><code>az aks get-credentials --resource-group FRONT-AKS-NA2 --name front-aks
</code></pre>
<p>I am getting error:</p>
<blockquote>
<p>ForbiddenError: The client 'my_name@my_comp.COM' with object id
'4ea46ad637c6' does not have authorization to perform action
'Microsoft.ContainerService/managedClusters/listClusterUserCredential/action'
over scope
'/subscriptions/89e05d73-8862-4007-a700-0f895fc0f7ea/resourceGroups/FRONT-AKS-NA2/providers/Microsoft.ContainerService/managedClusters/front-aks'
or the scope is invalid. If access was recently granted, please
refresh your credentials.</p>
</blockquote>
| <p>In my case to refresh recently granted credentials helped this one:</p>
<pre class="lang-sh prettyprint-override"><code>az account set --subscription "your current subscription name"
</code></pre>
<p>It led to re-login and fix the issue.</p>
|
<p>Hi there I was reviewing the GKE autopilot mode and noticed that in cluster configureation istio is disabled and I'm not able to change it. Also installation via istioctl install fail with following error</p>
<pre><code> error installer failed to update resource with server-side apply for obj MutatingWebhookConfiguration//istio-sidecar-injector: mutatingwebhookconfigurations.admissionregistration.k8s.io "istio-sidecar-injector" is forbidden: User "something@example" cannot patch resource "mutatingwebhookconfigurations" in API group "admissionregistration.k8s.io" at the cluster scope: GKEAutopilot authz: cluster scoped resource "mutatingwebhookconfigurations/" is managed and access is denied
</code></pre>
<p>Am I correct or it's not possible to run istio in GKE autopilot mode?</p>
| <p><strong>TL;DR</strong></p>
<p>It is not possible at this moment to run istio in GKE autopilot mode.</p>
<p><strong>Conclusion</strong></p>
<p>If you are using Autopilot, you don't need to manage your nodes. You don't have to worry about operations such as updating, scaling or changing the operating system. However, the autopilot has a number of <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview#limits" rel="noreferrer">limitations</a>.</p>
<p>Even if you are trying to install istio with a command <code>istioctl install</code>, istio will not be installed. You will then see the following message:</p>
<p>This will install the Istio profile into the cluster. Proceed? (y/N) y</p>
<p>✔ Istio core installed<br />
✔ Istiod installed<br />
✘ Ingress gateways encountered an error: failed to wait for resource: resources not ready after 5m0s: timed out waiting for the condition
Deployment/istio-system/istio-ingressgateway</p>
<ul>
<li>Pruning removed resources 2021-05-07T08:24:40.974253Z warn installer retrieving resources to prune type admissionregistration.k8s.io/v1beta1, Kind=MutatingWebhookConfiguration: mutatingwebhookconfigurations.admissionregistration.k8s.io is forbidden: User "something@example" cannot list resource "mutatingwebhookconfigurations" in API group "admissionregistration.k8s.io" at the cluster scope: GKEAutopilot authz: cluster scoped resource "mutatingwebhookconfigurations/" is managed and access is denied not found
Error: failed to install manifests: errors occurred during operation</li>
</ul>
<p>This command failed, bacuse for <a href="https://istio.io/latest/docs/setup/additional-setup/sidecar-injection/" rel="noreferrer">sidecar injection</a>, installer tries to create a <em>MutatingWebhookConfiguration</em> called <em>istio-sidecar-injector</em>. This limitation is <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview#webhooks_limitations" rel="noreferrer">mentioned here</a>.</p>
<p>For more information you can also <a href="https://medium.com/sakajunlabs/running-istio-on-gke-autopilot-707f6de2d43b" rel="noreferrer">read this page</a>.</p>
|
<h1>Installation Process</h1>
<p>I am all new to Kubernetes and currently setting up a Kubernetes Cluster inside of Azure VMs. I want to deploy Windows containers, but in order to achieve this I need to add Windows worker nodes. I already deployed a Kubeadm cluster with 3 master nodes and one Linux worker node and those nodes work perfectly.</p>
<p>Once I add the Windows node all things go downward. Firstly I use Flannel as my CNI plugin and prepare the deamonset and control plane according to the Kubernetes documentation: <a href="https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/adding-windows-nodes/" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/adding-windows-nodes/</a></p>
<p>Then after the installation of the Flannel deamonset, I installed the proxy and Docker EE accordingly.</p>
<h2>Used Software</h2>
<h3>Master Nodes</h3>
<p>OS: Ubuntu 18.04 LTS<br />
Container Runtime: Docker 20.10.5<br />
Kubernetes version: 1.21.0<br />
Flannel-image version: 0.14.0<br />
Kube-proxy version: 1.21.0</p>
<h3>Windows Worker Node</h3>
<p>OS: Windows Server 2019 Datacenter Core<br />
Container Runtime: Docker 20.10.4<br />
Kubernetes version: 1.21.0<br />
Flannel-image version: 0.13.0-nanoserver<br />
Kube-proxy version: 1.21.0-nanoserver</p>
<h1>Wanted Results:</h1>
<p>I wanted to see a full cluster ready to use and with all the needed in the <code>Running</code> state.</p>
<h1>Current Results:</h1>
<p>After the installation I checked if the installation was successful:</p>
<pre><code>azureuser@Kube-M-001:~$ kubectl get pods -o wide -n kube-system
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
coredns-558bd4d5db-8mshg 1/1 Running 0 178m 10.244.0.3 kube-m-001 <none> <none>
coredns-558bd4d5db-xhsmn 1/1 Running 0 178m 10.244.0.2 kube-m-001 <none> <none>
etcd-kube-m-001 1/1 Running 0 178m 10.0.10.4 kube-m-001 <none> <none>
etcd-kube-m-002 1/1 Running 0 164m 10.0.10.5 kube-m-002 <none> <none>
etcd-kube-m-003 1/1 Running 0 162m 10.0.10.6 kube-m-003 <none> <none>
kube-apiserver-kube-m-001 1/1 Running 0 178m 10.0.10.4 kube-m-001 <none> <none>
kube-apiserver-kube-m-002 1/1 Running 1 165m 10.0.10.5 kube-m-002 <none> <none>
kube-apiserver-kube-m-003 1/1 Running 0 162m 10.0.10.6 kube-m-003 <none> <none>
kube-controller-manager-kube-m-001 1/1 Running 1 178m 10.0.10.4 kube-m-001 <none> <none>
kube-controller-manager-kube-m-002 1/1 Running 0 165m 10.0.10.5 kube-m-002 <none> <none>
kube-controller-manager-kube-m-003 1/1 Running 0 163m 10.0.10.6 kube-m-003 <none> <none>
kube-flannel-ds-5lwzf 1/1 Running 0 165m 10.0.10.5 kube-m-002 <none> <none>
kube-flannel-ds-6lvgp 1/1 Running 0 129m 10.0.10.7 kube-w-001 <none> <none>
kube-flannel-ds-dlmkt 1/1 Running 0 163m 10.0.10.6 kube-m-003 <none> <none>
kube-flannel-ds-h27r7 1/1 Running 0 169m 10.0.10.4 kube-m-001 <none> <none>
kube-flannel-ds-windows-amd64-hwbjc 1/1 Running 0 121m 10.0.64.4 kube-w-002 <none> <none>
kube-proxy-4rkgk 1/1 Running 0 178m 10.0.10.4 kube-m-001 <none> <none>
kube-proxy-6g4sb 1/1 Running 0 129m 10.0.10.7 kube-w-001 <none> <none>
kube-proxy-tvm9g 1/1 Running 0 165m 10.0.10.5 kube-m-002 <none> <none>
kube-proxy-windows-j7c27 0/1 CrashLoopBackOff 26 121m 10.244.4.2 kube-w-002 <none> <none>
kube-proxy-wzjm7 1/1 Running 0 163m 10.0.10.6 kube-m-003 <none> <none>
kube-scheduler-kube-m-001 1/1 Running 1 178m 10.0.10.4 kube-m-001 <none> <none>
kube-scheduler-kube-m-002 1/1 Running 0 165m 10.0.10.5 kube-m-002 <none> <none>
kube-scheduler-kube-m-003 1/1 Running 0 162m 10.0.10.6 kube-m-003 <none> <none>
</code></pre>
<p>I checked the logs of the specific kube-proxy pod and got the following results:</p>
<pre><code>azureuser@Kube-M-001:~$ kubectl logs -n kube-system kube-proxy-windows-j7c27 -p
Directory: C:\host\var\lib\kube-proxy\var\run\secrets\kubernetes.io
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 12:08 PM serviceaccount
Directory: C:\host\k
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 12:24 PM kube-proxy
Using CNI conf file: 10-flannel.conf
I0503 12:30:23.146002 2448 flags.go:59] FLAG: --add-dir-header="false"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --alsologtostderr="false"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --bind-address="0.0.0.0"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --bind-address-hard-fail="false"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --cleanup="false"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --cluster-cidr=""
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --config="/var/lib/kube-proxy/config.conf"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --config-sync-period="15m0s"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --conntrack-max-per-core="32768"
I0503 12:30:23.194891 2448 flags.go:59] FLAG: --conntrack-min="131072"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --conntrack-tcp-timeout-close-wait="1h0m0s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --conntrack-tcp-timeout-established="24h0m0s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --detect-local-mode=""
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --enable-dsr="false"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --feature-gates="WinOverlay=true"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --healthz-bind-address="0.0.0.0:10256"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --healthz-port="10256"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --help="false"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --hostname-override="kube-w-002"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --iptables-masquerade-bit="14"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --iptables-min-sync-period="1s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --iptables-sync-period="30s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-exclude-cidrs="[]"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-min-sync-period="0s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-scheduler=""
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-strict-arp="false"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-sync-period="30s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-tcp-timeout="0s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-tcpfin-timeout="0s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --ipvs-udp-timeout="0s"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --kube-api-burst="10"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --kube-api-content-type="application/vnd.kubernetes.protobuf"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --kube-api-qps="5"
I0503 12:30:23.195318 2448 flags.go:59] FLAG: --kubeconfig=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --log-backtrace-at=":0"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --log-dir=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --log-file=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --log-file-max-size="1800"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --log-flush-frequency="5s"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --logtostderr="true"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --masquerade-all="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --master=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --metrics-bind-address="127.0.0.1:10249"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --metrics-port="10249"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --network-name=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --nodeport-addresses="[]"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --one-output="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --oom-score-adj="-999"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --profiling="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --proxy-mode=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --proxy-port-range=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --show-hidden-metrics-for-version=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --skip-headers="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --skip-log-headers="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --source-vip=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --stderrthreshold="2"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --udp-timeout="250ms"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --v="6"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --version="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --vmodule=""
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --windows-service="false"
I0503 12:30:23.195454 2448 flags.go:59] FLAG: --write-config-to=""
I0503 12:30:23.197789 2448 feature_gate.go:243] feature gates: &{map[WinOverlay:true]}
I0503 12:30:23.197789 2448 feature_gate.go:243] feature gates: &{map[WinOverlay:true]}
I0503 12:30:23.200622 2448 loader.go:372] Config loaded from file: /var/lib/kube-proxy/kubeconfig.conf
I0503 12:30:23.221725 2448 server_windows.go:107] Using Kernelspace Proxier.
I0503 12:30:23.221725 2448 server_windows.go:110] creating dualStackProxier for Windows kernel.
time="2021-05-03T12:30:23Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 12"
time="2021-05-03T12:30:23Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 10"
time="2021-05-03T12:30:23Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 12"
time="2021-05-03T12:30:23Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 13"
time="2021-05-03T12:30:23Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 10"
I0503 12:30:23.224600 2448 proxier.go:562] "Cleaning up old HNS policy lists"
I0503 12:30:33.229568 2448 proxier.go:583] "Hns Network loaded" hnsNetworkInfo=&{name:flannel.4096 id:ae948621-bb34-486d-b31d-cf397757b7c1 networkType:Overlay remoteSubnets:[0xc0000b77c0 0xc0000b7840 0xc0000b78c0 0xc0000b7940]}
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 12"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 10"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 12"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 13"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 10"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 12"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 10"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 12"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 13"
time="2021-05-03T12:30:33Z" level=info msg="currentVersion.Major < versionRange.MinVersion.Major: 9, 10"
F0503 12:30:33.256757 2448 server.go:489] unable to create proxier: unable to create ipv4 proxier: Could not find host mac address for 0.0.0.0, hostname: kube-w-002, clusterCIDR : 10.244.0.0/16, nodeIP:0.0.0.0
</code></pre>
<p>But I think something already went wrong in the Flannel installation, because the logs of the Flannel pod give the following results:</p>
<pre><code>PS C:\Users\azureuser> docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0cfa1c0c7b6d mcr.microsoft.com/oss/kubernetes/pause:1.4.1 "cmd /S /C pauseloop…" 2 hours ago Up 2 hours k8s_POD_kube-proxy-windows-j7c27_kube-system_df8fda84-cf94-4ca7-863a-9c9694f2b3ba_8
fb3ccc5e0cf7 sigwindowstools/flannel "pwsh -file /etc/kub…" 2 hours ago Up 2 hours k8s_kube-flannel_kube-flannel-ds-windows-amd64-hwbjc_kube-system_9f0aa635-200b-4902-93cc-1d1da7f49a5d_0
bc8e97427613 mcr.microsoft.com/oss/kubernetes/pause:1.4.1 "cmd /S /C pauseloop…" 2 hours ago Up 2 hours k8s_POD_kube-flannel-ds-windows-amd64-hwbjc_kube-system_9f0aa635-200b-4902-93cc-1d1da7f49a5d_0
PS C:\Users\azureuser> docker logs fb3ccc5e0cf7
Directory: C:\host\etc\cni
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 10:28 AM net.d
Directory: C:\host\etc
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 10:28 AM kube-flannel
Directory: C:\host\opt\cni
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 10:28 AM bin
Directory: C:\host\k
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 10:28 AM flannel
Directory: C:\host\k\flannel\var\run\secrets\kubernetes.io
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 5/3/2021 10:28 AM serviceaccount
Configuring CNI for docker
WARNING: The names of some imported commands from the module 'hns' include unapproved verbs that might make them less
discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose
parameter. For a list of approved verbs, type Get-Verb.
Invoke-HnsRequest : @{Error=An adapter was not found. ; ErrorCode=2151350278; Success=False}
At C:\k\flannel\hns.psm1:233 char:16
+ ... return Invoke-HnsRequest -Method POST -Type networks -Data $Json ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-HNSRequest
FATA[2021-05-03T10:28:44Z] rpc error: code = Internal desc = could not create IP forward entry: The object already exists.
I0503 10:28:45.340006 5512 main.go:518] Determining IP address of default interface
I0503 10:28:47.695146 5512 main.go:531] Using interface with name Ethernet 2 and address 10.0.64.4
I0503 10:28:47.695146 5512 main.go:548] Defaulting external address to interface address (10.0.64.4)
I0503 10:28:47.767526 5512 kube.go:119] Waiting 10m0s for node controller to sync
I0503 10:28:47.769102 5512 kube.go:306] Starting kube subnet manager
I0503 10:28:48.769283 5512 kube.go:126] Node controller sync successful
I0503 10:28:48.769283 5512 main.go:246] Created subnet manager: Kubernetes Subnet Manager - kube-w-002
I0503 10:28:48.769283 5512 main.go:249] Installing signal handlers
I0503 10:28:48.769283 5512 main.go:390] Found network config - Backend type: vxlan
I0503 10:28:48.769283 5512 vxlan_windows.go:127] VXLAN config: Name=flannel.4096 MacPrefix=0E-2A VNI=4096 Port=4789 GBP=false DirectRouting=false
I0503 10:28:48.838521 5512 device_windows.go:115] Attempting to create HostComputeNetwork &{ flannel.4096 Overlay [] {[]} { [] [] []} [{Static [{10.244.4.0/24 [[123 34 84 121 112 101 34 58 34 86 83 73 68 34 44 34 83 101 116 116 105 110 103 115 34 58 123 34 73 115 111 108 97 116 105 111 110 73 100 34 58 52 48 57 54 125 125]] [{10.244.4.1 0.0.0.0/0 0}]}]}] 8 {2 0}}
E0503 10:28:49.279614 5512 streamwatcher.go:109] Unable to decode an event from the watch stream: read tcp 10.0.64.4:50315-><PUBLIC-IP>:6443: wsarecv: An established connection was aborted by the software in your host machine.
E0503 10:28:49.323566 5512 reflector.go:304] github.com/coreos/flannel/subnet/kube/kube.go:307: Failed to watch *v1.Node: Get "https://kube-lb.eastus.cloudapp.azure.com:6443/api/v1/nodes?resourceVersion=6092&timeoutSeconds=582&watch=true": dial tcp: lookup kube-lb.eastus.cloudapp.azure.com: no such host
I0503 10:28:53.739453 5512 device_windows.go:123] Waiting to get ManagementIP from HostComputeNetwork flannel.4096
I0503 10:28:54.248878 5512 device_windows.go:134] Waiting to get net interface for HostComputeNetwork flannel.4096 (10.0.64.4)
I0503 10:28:54.758966 5512 device_windows.go:148] Created HostComputeNetwork flannel.4096
I0503 10:28:54.804770 5512 main.go:313] Changing default FORWARD chain policy to ACCEPT
I0503 10:28:54.816024 5512 main.go:321] Wrote subnet file to /run/flannel/subnet.env
I0503 10:28:54.816024 5512 main.go:325] Running backend.
I0503 10:28:54.816024 5512 main.go:343] Waiting for all goroutines to exit
I0503 10:28:54.816024 5512 vxlan_network_windows.go:63] Watching for new subnet leases
</code></pre>
<p>Can anyone please help me? So I can use my Windows worker-node in the Kubernetes cluster.</p>
<h1>Edit 1:</h1>
<p>Solved the Flannel FATA-error, this problem was caused by Flannel not being able to identify the network adapter. So before I started Flannel I created the needed network manually:</p>
<pre><code>#First download HNS
PS C:\Users\azureuser> curl.exe -LO https://raw.githubusercontent.com/microsoft/SDN/master/Kubernetes/windows/hns.psm1
ipmo ./hns.psm1
#Create the network
PS C:\Users\azureuser> New-HNSNetwork -Type Overlay -AddressPrefix "192.168.255.0/30" -Gateway "192.168.255.1" -Name "External" -AdapterName "Ethernet 2" -SubnetPolicies @(@{Type = "VSID"; VSID = 9999; });
</code></pre>
<p>After this you can join the windows-node to the cluster and Flannel will startup without a problem, but the Kube-proxy problem still remains.</p>
| <p>Are you still having this error? I managed to fix this by downgrading windows kube-proxy to at least 1.20.0. There must be some missing config or bug for 1.21.0.</p>
<pre class="lang-sh prettyprint-override"><code>curl -L https://github.com/kubernetes-sigs/sig-windows-tools/releases/latest/download/kube-proxy.yml | sed 's/VERSION/v1.20.0/g' | kubectl apply -f -
</code></pre>
|
<p>I have minikube installed on Windows10, and I'm trying to work with <a href="https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/" rel="noreferrer">Ingress Controller</a></p>
<p>I'm doing:</p>
<blockquote>
<p>$ minikube addons enable ingress</p>
</blockquote>
<pre><code>* After the addon is enabled, please run "minikube tunnel" and your ingress resources would be available at "127.0.0.1"
- Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
- Using image k8s.gcr.io/ingress-nginx/controller:v0.44.0
- Using image docker.io/jettech/kube-webhook-certgen:v1.5.1
* Verifying ingress addon...
* The 'ingress' addon is enabled
</code></pre>
<blockquote>
<p>minikube addons list</p>
</blockquote>
<pre><code> minikube addons list
|-----------------------------|----------|--------------|
| ADDON NAME | PROFILE | STATUS |
|-----------------------------|----------|--------------|
| ambassador | minikube | disabled |
| auto-pause | minikube | disabled |
| csi-hostpath-driver | minikube | disabled |
| dashboard | minikube | disabled |
| default-storageclass | minikube | enabled ✅ |
| efk | minikube | disabled |
| freshpod | minikube | disabled |
| gcp-auth | minikube | disabled |
| gvisor | minikube | disabled |
| helm-tiller | minikube | disabled |
| ingress | minikube | enabled ✅ |
| ingress-dns | minikube | disabled |
| istio | minikube | disabled |
| istio-provisioner | minikube | disabled |
| kubevirt | minikube | disabled |
| logviewer | minikube | disabled |
| metallb | minikube | disabled |
| metrics-server | minikube | disabled |
| nvidia-driver-installer | minikube | disabled |
| nvidia-gpu-device-plugin | minikube | disabled |
| olm | minikube | disabled |
| pod-security-policy | minikube | disabled |
| registry | minikube | disabled |
| registry-aliases | minikube | disabled |
| registry-creds | minikube | disabled |
| storage-provisioner | minikube | enabled ✅ |
| storage-provisioner-gluster | minikube | disabled |
| volumesnapshots | minikube | disabled |
|-----------------------------|----------|--------------|
</code></pre>
<p><strong>Note</strong>:
I ran <code>minikube tunnel</code> after the addon was enabled</p>
<p>But can't see the nginx controller anywhere:</p>
<blockquote>
<p>$ kubectl get pods -n kube-system</p>
</blockquote>
<pre><code>NAME READY STATUS RESTARTS AGE
coredns-74ff55c5b-8gkwj 1/1 Running 0 2m35s
etcd-minikube 1/1 Running 0 2m48s
kube-apiserver-minikube 1/1 Running 0 2m48s
kube-controller-manager-minikube 1/1 Running 0 2m48s
kube-proxy-jq4wm 1/1 Running 0 2m35s
kube-scheduler-minikube 1/1 Running 0 2m48s
storage-provisioner 1/1 Running 2 2m47s
</code></pre>
<blockquote>
<p>$ kubectl get pods</p>
</blockquote>
<pre><code>No resources found in default namespace.
</code></pre>
| <p>As already discussed in the comments the Ingress Controller will be created in the <code>ingress-nginx</code> namespace instead of the <code>kube-system</code> namespace. Other than that the rest of the tutorial should work as expected.</p>
|
<p>I have created subnets in GCP with allotted secondary IP ranges for pods and services. And have started a GKE cluster by providing the above secondary IP ranges for services and pods. Lets call this cluster-A.</p>
<p>Now I want to create another GKE cluster within same region, and want to use same subnets.
Can I use the same secondary IP ranges, which I provided for cluster-A, to create a new GKE-cluster?</p>
<p>My assumptions is, both the clusters will be provided IPs from the common subnet and secondary ranges, and there won't be any conflict. GCP would take care of it. But I am not sure of this, so can't move forward, fearing this might break my existing cluster.</p>
<p>The secondary IP ranges are big enough to accommodate services and pods of both the cluster.</p>
<p>Can anybody help me with this? Share some knowledge. Thanks.</p>
| <p>The pod secondary CIDR ranges and sub-networks can be shared across multiple clusters. However, Services secondary CIDR ranges must be different across multiple clusters and cannot be shared because secondary service ranges are unique to a given cluster.</p>
<p>Sharing IP ranges is not recommended as :</p>
<p>1.It can add extra noise in the networks.</p>
<p>2.The IP range that the subnet is using to assign to Nodes/Pods is now effectively shared among clusters.This can lead to IP exhaustion since one cluster may use more IP's than another one and this may leave the second cluster incapable of using more IP's which can’t create more nodes.</p>
<p>For more information refer the link:</p>
<p><a href="https://cloud.google.com/kubernetes-engine/docs/concepts/alias-ips#cluster_sizing_secondary_range_svcs" rel="nofollow noreferrer">https://cloud.google.com/kubernetes-engine/docs/concepts/alias-ips#cluster_sizing_secondary_range_svcs</a></p>
|
<p>I have around 200-300 yaml files lying around and What I am trying to achieve is to change only the image: option in few of my yaml files, I have a shell script which can get the required yaml files, and I just want to achieve changing the image: key only.</p>
<p><strong>Solution Tried:</strong></p>
<p>Used a tool <a href="https://mikefarah.gitbook.io/yq/" rel="nofollow noreferrer">yq</a> v4:</p>
<pre><code>for i in ${deployment[@]}
do
yq eval '( select(.spec.template.spec.containers[0].image |= "gcr.io/myrepo/mynginx:1.2.3"' deployment-$i.yaml
done
</code></pre>
<p>What this command does is it achieves the desired result of changing the image, but it also appends the changes on the all the parts of deployment file which is for example at the end of every spec in the file:</p>
<pre><code> apiVersion: apps/v1
kind: Deployment
metadata:
name: portal-1
spec:
selector:
matchLabels:
component: portal-1
role: ui
replicas: 1
template:
metadata:
labels:
component: reactportal
role: ui
spec:
containers:
- name: portal
image: gcr.io/myrepo/mynginx:4.52 <<< Desired CHange Happens Here >>>
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
nginx.ingress.kubernetes.io/enable-cors: "false"
nginx.ingress.kubernetes.io/cors-allow-origin: "https://example.com"
name: portal-ingress
spec:
rules:
- host: mydomain.com
http:
paths:
- backend:
serviceName: portal-svc
servicePort: 80
path: /(.*)
template: <<<< THIS IS ALSO GETTING APPENDED >>>
spec:
containers:
- image: gcr.io/myrepo/mynginx:1.2.3
</code></pre>
<p>How to achieve the desired result without appending the image on every part of the deployment file?</p>
| <p>This should get you the expected result :</p>
<pre><code>for i in ${deployment[@]}; do
yq eval '.spec|=select(.selector.matchLabels.component=="portal-1")
.template.spec.containers[0].image =
"gcr.io/myrepo/mynginx:1.2.3"' deployment-$i.yaml
done
</code></pre>
|
<p>I want to periodically restart the deployment using k8s cronjob.</p>
<p>Please check what is the problem with the yaml file.</p>
<p>When I execute the command from the local command line, the deployment restarts normally, but it seems that the restart is not possible with cronjob.
e.g $ kubectl rollout restart deployment my-ingress -n my-app</p>
<h2>my cronjob yaml file</h2>
<pre><code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: deployment-restart
namespace: my-app
spec:
schedule: '0 8 */60 * *'
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 600
template:
spec:
serviceAccountName: deployment-restart
restartPolicy: Never
containers:
- name: kubectl
image: bitnami/kubectl:latest
command:
- 'kubectl'
- 'rollout'
- 'restart'
- 'deployment/my-ingress -n my-app'
</code></pre>
| <p>as David suggested run cron of <strong>kubectl</strong> is like by executing the command</p>
<pre><code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/5 * * * *"
jobTemplate:
spec:
template:
spec:
serviceAccountName: sa-jp-runner
containers:
- name: hello
image: bitnami/kubectl:latest
command:
- /bin/sh
- -c
- kubectl rollout restart deployment my-ingress -n my-app
restartPolicy: OnFailure
</code></pre>
<p>i would also suggest you to check the <strong>role</strong> and <strong>service account</strong> permissions</p>
<p>example for ref :</p>
<pre><code>kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: default
name: kubectl-cron
rules:
- apiGroups:
- extensions
- apps
resources:
- deployments
verbs:
- 'patch'
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: kubectl-cron
namespace: default
subjects:
- kind: ServiceAccount
name: sa-kubectl-cron
namespace: default
roleRef:
kind: Role
name: kubectl-cron
apiGroup: ""
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: sa-kubectl-cron
namespace: default
---
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.