prompt stringlengths 65 38.7k | response stringlengths 41 29.1k |
|---|---|
<ul>
<li>client-go v0.19.2</li>
<li>golang 1.13</li>
</ul>
<p>I'm building a tool to create k8s resources from json(just like kubectl create -f).</p>
<p>I found that dynamic client can do such things,but when i use it with code bellow,i found it is hard to find schema.GroupVersionResource for given resource's json.Am i missing something or the only way to get resource is through restmapper?</p>
<pre class="lang-golang prettyprint-override"><code>container := &unstructured.Unstructured{}
if err := container.UnmarshalJSON([]byte(jsonstring); err != nil {
return err
}
_, err := k8sclient.Dynamic.Resource(?).Create(ctx, container, metav1.CreateOptions{})
if err != nil {
return err
}
</code></pre>
<p>I know a work around is to write some code like bellow, but i'm sure it's not the best practice and there are too many of them besides crds.</p>
<pre class="lang-golang prettyprint-override"><code>var kindResourceMap = map[string]schema.GroupVersionResource{
"Deployment": {
Group: "apps",
Version: "v1",
Resource: "deployments",
},
"ConfigMap": {
Group: "apps",
Version: "v1",
Resource: "configmaps",
},
"Job": {
Group: "batch",
Version: "v1",
Resource: "jobs",
},
"Secret": {
Group: "api",
Version: "v1",
Resource: "secrets",
},
"Service": {
Group: "api",
Version: "v1",
Resource: "services",
},
"StatefulSet": {
Group: "apps",
Version: "v1",
Resource: "statefulsets",
},
"PersistentVolume": {
Group: "api",
Version: "v1",
Resource: "persistentvolumes",
},
"CustomResourceDefinition": {
Group: "apiextensions.k8s.io",
Version: "v1beta1",
Resource: "customresourcedefinitions",
},
}
</code></pre>
| <p>You can use <code>restmapper</code> that directly queries the definitions from <code>metav1</code> using the <code>discovery</code> client.</p>
<pre class="lang-golang prettyprint-override"><code>import (
"k8s.io/client-go/rest"
"k8s.io/client-go/discovery"
"k8s.io/client-go/restmapper"
"k8s.io/apimachinery/pkg/runtime/schema"
)
...
c := discovery.NewDiscoveryClientForConfigOrDie(&rest.Config{})
groupResources, err := restmapper.GetAPIGroupResources(c)
mapper := restmapper.NewDiscoveryRESTMapper(groupResources)
mapping, err := mapper.RESTMapping(schema.ParseGroupKind("apps.Deployment"))
fmt.Println(mapping.Resource)
</code></pre>
<p>This is cooked in <code>sigs.k8s.io/controller-runtime/pkg/client</code></p>
<pre class="lang-golang prettyprint-override"><code>mapping, err := c.RESTMapper().RESTMapping(schema.ParseGroupKind("apps.Deployment"))
fmt.Println(mapping.Resource)
</code></pre>
<p>Look here for how it's done:
<a href="https://github.com/kubernetes-sigs/controller-runtime/blob/master/pkg/client/apiutil/dynamicrestmapper.go#L77" rel="nofollow noreferrer">https://github.com/kubernetes-sigs/controller-runtime/blob/master/pkg/client/apiutil/dynamicrestmapper.go#L77</a></p>
|
<p>In k8s you can <a href="https://yankeexe.medium.com/how-rolling-and-rollback-deployments-work-in-kubernetes-8db4c4dce599" rel="nofollow noreferrer">roll back a deployment</a>. Can you also roll back a service?</p>
<p>Rolling back a service may be helpful if there was an erroneous update done to a service resource.</p>
| <p>rollback / rollout undo is not available for <code>service</code> resource:</p>
<pre><code>kubectl rollout
Manage the rollout of a resource.
Valid resource types include:
* deployments
* daemonsets
* statefulsets
</code></pre>
|
<p>I'm new to Ingress in Kubernetes. I installed Ingress NGINX controller in my AKS cluster. My application runs in a pod (Port 80) in testns (Namespace). I created a service for it in the same namespace. Now I want to access my application from outside. So I created an Ingress yaml for it.</p>
<p><strong>service.yaml</strong></p>
<pre><code> kubectl get svc -A | grep my-svc
testns my-svc ClusterIP 10.0.116.192 <none> 80/TCP 93m
</code></pre>
<p><strong>ingress</strong></p>
<pre><code>Name: example-ingress
Namespace: testns
Address:
Default backend: default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
Host Path Backends
---- ---- --------
*
/apple my-svc:80 (10.244.1.33:80)
Annotations: ingress.kubernetes.io/rewrite-target: /
Events: <none>
</code></pre>
<p><strong>ingress.yaml</strong></p>
<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: example-ingress
annotations:
ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /apple
backend:
serviceName: my-svc
servicePort: 80
</code></pre>
<p>When I access using the <strong><IP_ADDRESS_OF_THE_INGRESS>/apple</strong>, it gives an 404 error. I want to know why the application can't be accessed.</p>
| <p>Try adding the ingress class into YAML config <code>kubernetes.io/ingress.class: "nginx"</code></p>
<p>as annotation</p>
<pre><code>kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/rewrite-target: /
</code></pre>
<p>Example</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: example-ingress
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /apple
backend:
serviceName: my-svc
servicePort: 80
</code></pre>
|
<p>I am new for pod health check with Readiness and Liveness. Recently I am working on Readiness. The scenario is as following:</p>
<p>The pod is a RestAPI service, it needs to connect to Database and store information in DB. So if RestAPI service wants to offer service, it needs to make sure database connection is successfully.</p>
<p>Si in our pod Readiness logic implementation, we use HTTP-Get and check if DB connection is connected, if it is okay, then HTTP-Get returns Ok, otherwise Readiness will be failed.</p>
<p>Not sure if the above logic is reasonable? Or is there any other approach for this logic processing?</p>
<p>Apart from Readiness, how about Liveness? Do I need to check DB connection in order to check Liveness is okay?</p>
<p>Any idea and suggestion are appreciated</p>
| <p><strong>readiness</strong> and <strong>liveness</strong> is mostly for service you are running inside container, there could be a scenario where your DB is up but there is issue with the <strong>application</strong> at that time also your <strong>readiness</strong> will be <strong>Up</strong> as DB is running, in ideal scenario if application not working it should stop accepting traffic.</p>
<p>i would recommend using the <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" rel="nofollow noreferrer">Init container</a> or <a href="https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/" rel="nofollow noreferrer">Life cycle hook</a> for checking the condition of the Database first if it's up process will move ahead and your application or deployment will come into the picture.</p>
<p>If the application works well your readiness and liveness will <strong>HTTP-OK</strong> and the service start accepting traffic.</p>
<p><strong>init container example</strong></p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox
command: ['sh', '-c', 'echo The app is running! && sleep 3600']
initContainers:
- name: init-myservice
image: busybox
command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;']
- name: init-mydb
image: busybox
command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']
</code></pre>
<p><strong>Extra Notes</strong></p>
<p>There is actually no need to check the DB readiness at all.</p>
<p>As your application will be trying to connect with the <strong>Database</strong> so if <strong>DB</strong> is <strong>not</strong> <strong>UP</strong> your application won't respond <strong>HTTP-OK</strong> so your application won't start, and readiness keep failing for application.</p>
<p>As soon as your Database comes up your application will create a successful connection with DB and it will give <strong>200</strong> responses and readiness will mark POD ready.</p>
<p>there is no extra requirement to setup the readiness for Db and based on that start POD.</p>
|
<p>I already installed Linkerd on a Kubernetes cluster that is runing in AWS: <a href="https://linkerd.io/2.11/getting-started/" rel="nofollow noreferrer">Linkerd - Getting Started</a></p>
<p>All checks are ok, but I cannot see the viz dashboard in my local:</p>
<pre><code>kubectl -n linkerd-viz port-forward svc/web 8084
</code></pre>
<p>Is there a way to expose it via ingress ALB?</p>
| <p>You can expose the dashboard in a couple ways. You can modify the web service to add an external load balancer, which will respect any AWS annotations you already use with AWS load balancers. You can also create the appropriate routing rules for your existing ingress. You can find some examples here: <a href="https://linkerd.io/2.11/tasks/exposing-dashboard/" rel="nofollow noreferrer">https://linkerd.io/2.11/tasks/exposing-dashboard/</a></p>
|
<p>I have a k0s Kubernetes cluster on a single node. I am trying to run a <code>selenium/standalone-chrome</code> to create a remote Selenium node. The trouble that I am having is that it responds if I port forward <code>4444</code> from the pod, but cannot seem to access it via a Service port. I get connection refused. I don't know if it's because it's ignore connections that non-localhost.</p>
<p>The <code>Pod</code> definition for <code>pod/standalone-chrome</code> is:</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: standalone-chrome
spec:
containers:
- name: standalone-chrome
image: selenium/standalone-chrome
ports:
- containerPort: 4444
env:
- name: JAVA_OPTS
value: '-Dwebdriver.chrome.whitelistedIps=""'
</code></pre>
<p>The <code>Service</code> definition I have for <code>service/standalone-chrome-service</code> is:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: standalone-chrome-service
labels:
app: standalone-chrome
spec:
ports:
- port: 4444
name: standalone-chrome
type: ClusterIP
selector:
app: standalone-chrome
</code></pre>
<p>This creates the following, along with a <code>busybox</code> container I have just for testing connectivity.</p>
<pre><code>NAME READY STATUS RESTARTS AGE
pod/busybox1 1/1 Running 70 2d22h
pod/standalone-chrome 1/1 Running 0 3m15s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 18d
service/standalone-chrome-service ClusterIP 10.111.12.1 <none> 4444/TCP 3m5s
</code></pre>
<p>The issue I am having now is that I'm not able to access the remote Selenium service via <code>standalone-chrome-service</code>. I get connection refused. For example, here is trying to reach it via the <code>busybox1</code> container:</p>
<pre><code>$ wget http://standalone-chrome-service:4444
Connecting to standalone-chrome-service:4444 (10.111.12.1:4444)
wget: can't connect to remote host (10.111.12.1): Connection refused
</code></pre>
<p>I am able to port forward from <code>pod/standalone-chrome</code> to my host machine using <code>kubectl port-forward</code> though and it works OK, which I think confirms a service is successfully running but not accessible via the <code>Service</code>:</p>
<pre><code>$ kubectl port-forward pod/standalone-chrome 4444:4444 &
Forwarding from 127.0.0.1:4444 -> 4444
Forwarding from [::1]:4444 -> 4444
$ wget http://localhost:4444
--2021-11-22 13:37:20-- http://localhost:4444/
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:4444... connected.
...
</code></pre>
<p>I'd greatly appreciate any help in figuring out how to get the Selenium remote server accessible via the <code>Service</code>.</p>
<hr />
<p>EDIT: Here is the updated Service definition with <code>name</code>...</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: standalone-chrome-service
labels:
app: standalone-chrome
spec:
ports:
- port: 4444
name: standalone-chrome
type: ClusterIP
selector:
name: standalone-chrome
</code></pre>
<p>Here is the output of describe:</p>
<pre><code>Name: standalone-chrome-service
Namespace: default
Labels: app=standalone-chrome
Annotations: <none>
Selector: name=standalone-chrome
Type: ClusterIP
IP Families: <none>
IP: 10.100.179.116
IPs: 10.100.179.116
Port: standalone-chrome 4444/TCP
TargetPort: 4444/TCP
Endpoints: <none>
Session Affinity: None
Events: <none>
</code></pre>
| <p>Service's syntax with:</p>
<pre><code> selector:
app: standalone-chrome
</code></pre>
<p>is correct, <code>selector</code> should be matched by <code>label</code>.</p>
<blockquote>
<p>Services match a set of Pods using labels and selectors, a grouping
primitive that allows logical operation on objects in Kubernetes.
Labels are key/value pairs attached to objects</p>
</blockquote>
<p>See for more details <a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/expose/expose-intro/" rel="nofollow noreferrer">Using a Service to Expose Your App</a>.</p>
<p>Now you need to add this <code>label</code> (which is <code>app: standalone-chrome</code>) to your <code>pod.yaml</code> metadata:</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: standalone-chrome
labels:
app: standalone-chrome # this label should match to selector in service
spec:
containers:
- name: standalone-chrome
image: selenium/standalone-chrome
ports:
- containerPort: 4444
env:
- name: JAVA_OPTS
value: '-Dwebdriver.chrome.whitelistedIps=""'
</code></pre>
|
<p>How do I expose an ingress when running kubernetes with minikube in windows 10?</p>
<p>I have enabled the minikube ingress add on.</p>
<p>My ingress is running here...</p>
<pre><code>NAME CLASS HOSTS ADDRESS PORTS AGE
helmtest-ingress nginx helmtest.info 192.168.49.2 80 37m
</code></pre>
<p>I have added my <code>hosts</code> entry...</p>
<pre><code>192.168.49.2 helmtest.info
</code></pre>
<p>I just get nothing when attempting to browse or ping either <code>192.168.49.2</code> or <code>helmtest.info</code></p>
<p>My ingress looks like the following</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: helmtest-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: helmtest.info
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: helmtest-service
port:
number: 80
</code></pre>
<p>My service looks like the following...</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
name: helmtest-service
labels:
app: helmtest-service
spec:
type: ClusterIP
selector:
app: helmtest
ports:
- port: 80
targetPort: 80
protocol: TCP
</code></pre>
<p>I can access my service successfully in the browser after running <code>minikube service helmtest-service --url</code></p>
<p>If I run <code>minikube tunnel</code> it just hangs here....</p>
<pre><code>minikube tunnel
❗ Access to ports below 1024 may fail on Windows with OpenSSH clients older than v8.1. For more information, see: https://minikube.sigs.k8s.io/docs/handbook/accessing/#access-to-ports-1024-on-windows-requires-root-permission
🏃 Starting tunnel for service helmtest-ingress.
</code></pre>
<p>Where am I going wrong here?</p>
| <p>OP didn't provide further information so I will provide answer based on the current information.</p>
<p>You can run <code>Ingress</code> on <a href="https://minikube.sigs.k8s.io/docs/" rel="nofollow noreferrer">Minikube</a> using the <code>$ minikube addons enable ingress</code> command. However, ingress has more addons, like <a href="https://minikube.sigs.k8s.io/docs/handbook/addons/ingress-dns/" rel="nofollow noreferrer">Ingress DNS</a> using <code>minikube addons enabled ingress-dns</code>. In <code>Minikube</code> documentation you can find more details about this addon and when you should use it.</p>
<p>Minikube has quite a well described section about <a href="https://minikube.sigs.k8s.io/docs/commands/tunnel/" rel="nofollow noreferrer">tunnel</a>. Quite important fact about the tunnel is that it must be run in a separate terminal window to keep the LoadBalancer running.</p>
<blockquote>
<p>Services of type <code>LoadBalancer</code> can be exposed via the <code>minikube tunnel</code> command. It must be run in a separate terminal window to keep the <code>LoadBalancer</code> running. <code>Ctrl-C</code> in the terminal can be used to terminate the process at which time the network routes will be cleaned up.</p>
</blockquote>
<p>This part is described in <a href="https://minikube.sigs.k8s.io/docs/handbook/accessing/" rel="nofollow noreferrer">Accessing apps</a> documentation.</p>
<p>As OP mention</p>
<blockquote>
<p>I can access my service successfully in the browser after running minikube service helmtest-service --url</p>
<p>If I run minikube tunnel it just hangs here....</p>
</blockquote>
<p><strong>Possible Solution</strong></p>
<ul>
<li>You might use the old version of SSH, update it.</li>
<li>You are using ports <1024. This situation it's described in <a href="https://minikube.sigs.k8s.io/docs/handbook/accessing/#access-to-ports-1024-on-windows-requires-root-permission" rel="nofollow noreferrer">this known issue</a> part. Try to use higher port like 5000 like in <a href="https://stackoverflow.com/questions/59994578/how-do-i-expose-ingress-to-my-local-machine-minikube-on-windows">this example</a></li>
<li>It might look like it just hangs, but you need a separate terminal window. Maybe it works correctly but you have to use another terminal</li>
</ul>
<p>Useful links</p>
<ul>
<li><a href="https://stackoverflow.com/questions/59994578/how-do-i-expose-ingress-to-my-local-machine-minikube-on-windows">How do I expose ingress to my local machine? (minikube on windows)</a></li>
<li><a href="https://stackoverflow.com/questions/58790433/">Cannot export a IP in minikube and haproxy loadBalancer - using minikube tunnel</a></li>
</ul>
|
<p>I have an nginx-ingress calling a custom <code>auth-service</code> before sending requests to the backend service, using this simple ConfigMap and Ingress:</p>
<pre><code>apiVersion: v1
kind: ConfigMap
metadata:
...
data:
global-auth-url: auth-service-url:8080/authenticate
global-auth-method: GET
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
...
spec:
rules:
- host: host1
http:
paths:
- backend:
serviceName: backend-service
servicePort: 8080
</code></pre>
<p>Now I need something different.</p>
<p>How can I send requests, all with the same "Host" header, through different flows, one with auth-service and connected to <code>backend-service1</code> and the other without any authentication and connecting to <code>backend-service2</code>?</p>
<p>To be clear, and using the custom header "Example-header: test"</p>
<ol>
<li>If "Example-header" is "test", authenticate via my <code>auth-service</code> before sending to <code>backend-service</code>, as it's done now.</li>
<li>If "Example-header" is not defined, I want to send requests to a different backend service and do not use <code>auth-service</code> in the process.</li>
</ol>
<p>I tried a couple of things, namely having 2 Ingresses, one with <code>global-auth-url</code> and the other with <code>nginx.ingress.kubernetes.io/enable-global-auth: "false"</code> but the auth-service is always called.</p>
<p>Can I do this with NGINX, or do I have to use Istio or Ambassador?</p>
| <p>One way you can achieve this behavior is by abusing the <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#canary" rel="noreferrer">canary feature</a>.</p>
<p>For your <code>backend-service</code>, create a normal Ingress, e. g.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-backend
spec:
ingressClassName: nginx
rules:
- host: localhost
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: backend-service
port:
number: 80
</code></pre>
<p>Create a second Ingress for you <code>auth-service</code> with enabled canary and set the header name and value, e. g.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-auth
annotations:
nginx.ingress.kubernetes.io/canary: "true"
nginx.ingress.kubernetes.io/canary-by-header: Example-header
nginx.ingress.kubernetes.io/canary-by-header-value: test
spec:
ingressClassName: nginx
rules:
- host: localhost
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: auth-service
port:
number: 80
</code></pre>
<p>Now, every request with <code>Example-header: test</code> routes to <code>auth-service</code>. Any other value, e. g. <code>Example-header: some-value</code>, will <strong>not</strong> route to <code>auth-service</code> but rather go to your <code>backend-service</code>.</p>
|
<p>I have a go routine running in docker container. I need output of the command dmidecode. But its coming blank.</p>
<p>Go:</p>
<p>func main() {</p>
<pre><code> cmd := exec.Command("dmidecode","-t 1")
x,_ := cmd.Output()
fmt.Println("output =======", string(x))
</code></pre>
<p>}</p>
<p>Docker run:</p>
<p>docker run --device /dev/mem:/dev/mem --cap-add SYS_RAWIO -p 8086:8086 -it my_img:1.0.1</p>
<p>What am I missing here?</p>
<p><strong>Updated:</strong></p>
<p>The above worked in docker after I added below in Dockerfile:</p>
<p>FROM alpine:latest
RUN apk --no-cache --update --verbose add grep bash dmidecode && <br />
rm -rf /var/cache/apk/* /tmp/* /sbin/halt /sbin/poweroff /sbin/reboot</p>
<p>And below in docker compose file:</p>
<p>privileged: true</p>
<p><strong>But When tried to use the above in kubernetes it not able to fetch demidecode output.</strong></p>
<p>A help will be really appreciated.</p>
| <blockquote>
<p>What am I missing here?</p>
</blockquote>
<p>For starters ,error handling.</p>
<pre><code> x,_ := cmd.Output()
</code></pre>
<p>Never, ever ignore an error in Go. Unlike languages like, say, Pyhton, there is no exception raising - handling error return values is your <em>only</em> chance to figure out if something went wrong.</p>
<p>Secondly, you're also ignoring your command's Standard Output stream. This is likely to contain a useful error message whenever a command execution doesn't work, so <a href="https://pkg.go.dev/os/exec#Cmd.Output" rel="nofollow noreferrer"><code>os/exec</code>'s <code>Output()</code> provides it as part of the error value</a> if not already captured in the <code>Cmd</code> configuration. Part of your error handling should be doing a <a href="https://go.dev/tour/methods/15" rel="nofollow noreferrer">type assertion</a> on that error value, if not nil, and if it's a valid <code>*exec.ExitError</code>, and if that type assertion succeeds, check <a href="https://pkg.go.dev/os/exec#ExitError" rel="nofollow noreferrer">its Stderr field</a> for an error message.</p>
<p>Third, looking at your command, I can see you made an easy mistake:</p>
<pre><code> cmd := exec.Command("dmidecode","-t 1")
</code></pre>
<p>At the <em>shell</em>, whitespace separates arguments. but there is no shell here; you're passing <code>-t 1</code> all as one argument to <code>dmidecode</code>. You should be passing them as <em>separate</em> arguments, almost certainly:</p>
<pre><code> cmd := exec.Command("dmidecode","-t", "1")
</code></pre>
<p>Finally, you've already found <a href="https://stackoverflow.com/questions/54068234/cant-run-dmidecode-on-docker-container/70084824#70084824">Can't run dmidecode on docker container</a> , but make sure to read and understand the accepted answer. Then, get your docker container configured to be able to run <code>dmidecode</code> without Go. Once it works at the command line, the same docker configuration should allow it to work under Go invocation as well.</p>
|
<p>To use alert by E-mail in Grafana, we have to set SMTP settings in grafana.ini.</p>
<p>On Ubuntu, we can easily run the grafana-prometheus-k8s stack by command
<code>microk8s enable prometheus</code>
However, how can we feed grafana.ini to grafana running in a k8s pod?</p>
| <p>We can modify grafana k8s deployment manifest by <strong>volumeMounts</strong> to feed grafana.ini on our host to grafana running in a pod.</p>
<p>First, prepare your grafana.ini with SMTP settings. E.g.</p>
<pre><code>[smtp]
enabled = true
host = smtp.gmail.com:465
# Please change user and password to your ones.
user = foo@bar.com
password = your-password
</code></pre>
<p>Then, you can place this file on your host. E.g. <code>/home/mydir/grafana.ini</code></p>
<p>Modify the loaded grafana k8s deployment manifest:</p>
<pre><code>kubectl edit deployments.apps -n monitoring grafana
</code></pre>
<p>Add a new mount to <strong>volumeMounts</strong> (not the one in <code>kubectl.kubernetes.io/last-applied-configuration</code>):</p>
<pre><code> volumeMounts:
- mountPath: /etc/grafana/grafana.ini
name: mydir
subPath: grafana.ini
</code></pre>
<p>Add a new <strong>hostPath</strong> to <strong>volumes</strong>:</p>
<pre><code> volumes:
- hostPath:
path: /home/mydir
type: ""
name: mydir
</code></pre>
<p>Finally, restart the deployment:</p>
<pre><code>kubectl rollout restart -n monitoring deployment grafana
</code></pre>
<p>Run this command and use a web browser on your host to navigate to http://localhost:8080 to grafana web app:</p>
<pre><code>kubectl port-forward -n monitoring svc/grafana 8080:3000
</code></pre>
<p>Then, you can navigate to Alerting / Notification channels / Add channel to add an Email notification channel and test it!</p>
|
<p>I have a small web application (a Rails app called <code>sofia</code>) that I'm deploying locally with <code>minikube</code>.</p>
<p>When I create the k8s resources and run my deployment, the containers do not contain any of the files that were supposed to be copied over during the image build process.</p>
<p>Here's what I'm doing:</p>
<h2>Dockerfile</h2>
<p>As part of the <code>Dockerfile</code> build, I copy the contents of my local cloned repository into the image working directory:</p>
<pre><code>RUN mkdir -p /app
WORKDIR /app
COPY . ./
</code></pre>
<h2>The (old) <code>docker-compose</code> setup</h2>
<p>Historically I've used a <code>docker-compose</code> file to run this application and all its services. I map my local directory to the container's working directory (see <code>volumes:</code> below). This is a nice convenience when working locally since all changes are reflected "live" inside the container:</p>
<pre class="lang-yaml prettyprint-override"><code># docker-compose.yml
sofia:
build:
context: .
args:
RAILS_ENV: development
environment:
DATABASE_URL: postgres://postgres:sekrit@postgres/
image: sofia/sofia:local
ports:
- # ...
volumes:
- .:/app #<---- HERE
</code></pre>
<h2>Building k8s resource file with <code>kompose</code></h2>
<p>In order to run this on <code>minikube</code>, I use the <a href="https://github.com/kubernetes/kompose" rel="nofollow noreferrer"><code>kompose</code> tool</a> that Kubernetes themselves provide in order to transform my <code>docker-compose</code> file into a k8s resource file that can be consumed.</p>
<pre class="lang-sh prettyprint-override"><code>$ kompose convert --file docker-compose.yml --out k8s.yml --with-kompose-annotation=false
WARN Volume mount on the host "/Users/jeeves/git/jeeves/sofia" isn't supported - ignoring path on the host
INFO Kubernetes file "k8s.yml" created
</code></pre>
<p>As you can see, it generates a warning that my local volume can not be mounted against the remote volume. This makes sense since a k8s deployment runs "remotely", so I just ignore the warning.</p>
<h2>Running</h2>
<p>Finally I run the above resources with k8s / <code>minikube</code></p>
<pre class="lang-sh prettyprint-override"><code>minikube start
kubectl apply -f k8s.yml
</code></pre>
<p>I notice the <code>sofia</code> container keeps crashing and restarting so I check the logs:</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl get pods
NAME READY STATUS RESTARTS AGE
pod/sofia-6668945bc8-x9267 0/1 CrashLoopBackOff 1 10s
pod/postgres-fc84cbd4b-dqbrh 1/1 Running 0 10s
pod/redis-cbff75fbb-znv88 1/1 Running 0 10s
$ kubectl logs pod/sofia-6668945bc8-x9267
Could not locate Gemfile or .bundle/ directory
</code></pre>
<p>That error is Ruby/Rails specific, but the underlying cause is that there <strong>are no files in the container</strong>! I can confirm this by entering the container and checking files with <code>ls</code> - it is indeed empty.</p>
<h2>Questions</h2>
<ol>
<li>If the <code>sofia/sofia:latest</code> image is correctly built with the <code>COPY</code>-ied file contents, why would it dissapear when runing the container on <code>minikube</code>?</li>
<li>What should I do to ensure my files get copied over correctly?</li>
</ol>
<p>Thanks!</p>
| <p>The issue is that Volumes are not behaving the same way in Docker in docker-compose and K8s. Kompose can't perfectly translate volume.
In Docker with docker-compose, your declared volume keep the existing files from the directory, while in k8s, a volume is created empty and shadow the existing content.</p>
<p>There is no direct equivalent of docker-compose volumes that keeps existing files in k8s, you will have to work around that with one of the following options, depending on what makes sense in your use case:</p>
<ul>
<li>leverage <a href="https://kubernetes.io/docs/concepts/storage/volumes/#configmap" rel="nofollow noreferrer">ConfigMaps</a> to add your files to this app volume (if needed, use subPath). Probably ok for a handfull of config files if that's what lives your app directory when the container starts</li>
<li>in your dockerfile, use COPY to something like app-tmp, then in your entrypoint script copy those files from that app-tmp directory to your "app" volume</li>
<li>Refactor your application so that it uses "app1" directory (without volumes) with existing files, "app2" starts empty and is used as your volume.</li>
</ul>
|
<p>I am running MongoDB as a StatefulSet in Kubernetes.</p>
<p>I am trying to use startup/liveness probes, and I noticed some helm charts use the MongoDB "ping" command.</p>
<p>As <a href="https://docs.mongodb.com/manual/reference/command/ping/" rel="nofollow noreferrer">the documentation</a> says,</p>
<blockquote>
<p>The ping command is a no-op used to test whether a server is responding to commands. This command will return immediately even if the server is write-locked:</p>
</blockquote>
<p>What does it mean? When a server is starting or in the midst of initial sync, what will the command return?</p>
| <p>I am not sure if the ping is a good idea. You don't care about the general state of the server; you care that it can receive connections.</p>
<p>Liveness probes have a timeout, so it's possible that in the future, when you're starting a new replica, the new pod in the stateful set will fail while waiting for the replication to end.</p>
<p>You should use the <a href="https://docs.mongodb.com/manual/reference/command/replSetGetStatus/#mongodb-dbcommand-dbcmd.replSetGetStatus" rel="nofollow noreferrer">rs.status()</a> and get the "myState" field.</p>
<p><em>myState</em> is an integer flag between 0-10. See <a href="https://docs.mongodb.com/manual/reference/replica-states/" rel="nofollow noreferrer">this</a> for all the possible statuses.</p>
<p>And if, for whatever reason the <em>rs.status()</em> command fails, that means that the ping would also fail.</p>
<p>However, a successful ping doesn't mean that the server is ready to receive connections and serve data, which is what you really care about.</p>
<h3>Probes</h3>
<p><strong>startup probe</strong>, myState equals to 1 or 2</p>
<p>This means that the startup probe will wait patiently until the server is ready, regardless if it's a primary or replica.</p>
<p><strong>Readiness probes</strong>, myState equals to 1 or 2</p>
<p>This means that, whenever a replica needs to rollback or is recovering or whatever reason that <em>mongod</em> decides that it's not ready to accept connections or serve data, this will let Kubernetes know that this pod is not ready, and will route requests to other pods in the sts.</p>
<p><strong>Livenes probe</strong>, myState is NOT equals to 6, 8 or 10</p>
<p>That means that, unless the server status is UNKOWN, DOWN or REMOVED, Kubernetes will assume that this server is alive.</p>
<p>So, let's test a scenario!</p>
<ul>
<li>sts started, first pod is on STARTUP, and myState = 0</li>
<li>startup probe waits</li>
<li>the first MongoDB node is ready, myState = 1</li>
<li>the startup probe finally passed. Now readiness and liveness probes start acting</li>
<li>a new replica triggered, second pod is on STARTUP, and myState = 0</li>
<li>a new replica successfully joins the set. myState = 5</li>
<li>a new replica is ready. myState = 2</li>
<li>the startup probe finally passed. Now readiness and liveness probes start acting</li>
<li><em>time for some action</em></li>
<li>a massive operation that altered hundreds of documents was rolled back on the primary</li>
<li>the second pod is now on ROLLBACK, myState = 9, and readiness probe failed. The second pod is now NOT READY</li>
<li>all connections are now sent to the PRIMARY</li>
<li>the second pod has finished the rollback</li>
<li>the second pod is now back as a SECONDARY, myState = 2, liveness probe succeeds and pod is back at the READY state</li>
<li>the MongoDB dba messed up and issued a command that removed the secondary from the replicationset, myState = 10</li>
<li>liveness probe fails, and Kubernetes kills the pod</li>
<li>sts wants two replicas and starts a second pod again
...</li>
</ul>
<p>All good :)</p>
|
<p>I'm confused about why we use configMap versions. I'm seeing multiple versions of confimap in my k8s cluster that is attached to a deployment/sts. I was expecting if I apply some changes in my yaml it will get reflected in all of the configMap versions, but that is not happening. Can someone help with this.</p>
<p>I don't have any <code>subdir</code> in configmap.</p>
<p>Do you know much time for reflecting these changes in the mounted volumes? or what I'm missing here</p>
<p>example configmap output</p>
<pre><code>NAME DATA AGE
ca-bundles 4 3d17h
c-rules-alerts 1 3d17h
c-rules-alerts-v000 1 3d16h
c-rules-alerts-v001 1 50m
c-rules-metrics 1 3d17h
c-rules-metrics-v000 1 3d16h
c-rules-metrics-v001 1 50m
c-alertmanager 1 3d17h
c-alertmanager-v000 1 3d16h
c-server 3 3d17h
c-server-v000 3 3d16h
</code></pre>
<p>here is the mount config</p>
<pre><code> volumeMounts:
- name: config-metric-volume
mountPath: /oracle_exporter
volumes:
- name: data-volume
emptyDir:
sizeLimit: 2Gi
- name: config-metric-volume
configMap:
name: chron-rules-metrics
</code></pre>
| <p>Kubernetes provides a way to store rollout information for some resources by default, one of those is deployments.</p>
<p>You can perform some commands providing a <code>--record</code> flag, which will record the current and new state of the deployment, allowing you to perform a <code>rollback</code></p>
<p>See <a href="https://stackoverflow.com/questions/62831410/usage-of-record-in-kubectl-imperative-commands-in-kubernetes">this answer</a> for more details</p>
<p>Other resources, don't have that feature and tools like <a href="https://helm.sh/docs/" rel="nofollow noreferrer">helm</a> and <a href="https://carvel.dev/kapp/" rel="nofollow noreferrer">kapp</a> create versions of the resources to allow you to rollback the deployment/statefulset/etc along with all of its related resources like secrets, configmaps, ingresses, etc.</p>
<p>Some tools store that information in annotations, others create a naming duplicate the current resource with a suffix following a convention.</p>
<hr />
<p>So, with that out of the way, we can talk about seeing the changes reflected on your deployments.</p>
<p>By default, again, if you change anything in a deployment(sts, ds, etc) spec that impacts the pods, kuberntes will trigger a rollout and will recreate all the pods to reflect the new spec.</p>
<p>That doesn't happen when you update secrets and config maps that are mapped to pods. There are arguments in favor and against that behaviour, some think that is useful, some think that this might lead to some huge chain reactions in the cluster.</p>
<p>Regardless of where this discussion ends, this is the behaviour today.</p>
<p>To see config map or secrets changes reflected on the pods, you must trigger a restart.</p>
<p><code>kubectl rollout restart deployment/my-awesome-app</code></p>
|
<p>In this application, nodejs pods are running inside kubernetes, and mongodb itself sitting outside at host as localhost.</p>
<p>This indeed not good design, but its only for dev environment. In production a separte mongodb server will be there, as such option to have a non loopback ip in endpoint, so will not be a problem in Production.</p>
<p>Have considered following options for dev environment</p>
<ol>
<li><p>Use localhost connect string to connect to mongodb, but it will refer to pod's own localhost not host's localhost</p>
</li>
<li><p>Use headless service and provide localhost ip and port in endpoint. However endpoint doesn't allow loopback</p>
</li>
</ol>
<p>Suggest if there is a way to access mongodb database at host's localhost from inside cluster (pod / nodejs application).</p>
| <p>I'm running on docker for windows, and for me just using <code>host.docker.internal</code> instead of <code>localhost</code> seems to work fine.</p>
<p>For example, my mongodb connection string looks like this:</p>
<pre><code>mongodb://host.docker.internal:27017/mydb
</code></pre>
<p>As an aside, my <code>hosts</code> file includes the following lines (which I didn't add, I guess the <code>docker desktop</code> installation did that):</p>
<pre><code># Added by Docker Desktop
192.168.1.164 host.docker.internal
192.168.1.164 gateway.docker.internal
</code></pre>
|
<p>I'm converting volume gp2 to volume gp3 for EKS but getting this error.<br />
<em><strong>Failed to provision volume with StorageClass "gp3": invalid AWS VolumeType "gp3"</strong></em><br />
This is my config.</p>
<p>StorageClass</p>
<pre><code>apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
annotations:
storageclass.kubernetes.io/is-default-class: "true"
name: gp3
parameters:
fsType: ext4
type: gp3
provisioner: kubernetes.io/aws-ebs
reclaimPolicy: Retain
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
</code></pre>
<p>PVC</p>
<pre><code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
labels:
app: test-pvc
name: test-pvc
namespace: default
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: gp3
</code></pre>
<p>When I type <code>kubectl describe pvc/test</code>. This is response:</p>
<pre><code>Name: test-pvc
Namespace: default
StorageClass: gp3
Status: Pending
Volume:
Labels: app=test-pvc
Annotations: volume.beta.kubernetes.io/storage-provisioner: kubernetes.io/aws-ebs
Finalizers: [kubernetes.io/pvc-protection]
Capacity:
Access Modes:
VolumeMode: Filesystem
Used By: <none>
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning ProvisioningFailed 58s (x9 over 4m35s) persistentvolume-controller Failed to provision volume with StorageClass "gp3": invalid AWS VolumeType "gp3"
</code></pre>
<p>I'm using Kubernetes version 1.18.<br />
Can someone help me. Thanks!</p>
| <p>I found the solution to use volume <code>gp3</code> in storage class on EKS.</p>
<ol>
<li>First, you need to install <code>Amazon EBS CSI driver</code> with offical instruction <a href="https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html" rel="nofollow noreferrer">here</a>.</li>
<li>The next, you need to create the storage class <code>ebs-sc</code> after <code>Amazon EBS CSI driver</code> is installed, example:</li>
</ol>
<hr />
<pre><code>cat << EOF | kubectl apply -f -
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-sc
provisioner: ebs.csi.aws.com
parameters:
type: gp3
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
EOF
</code></pre>
<p>So, you can use volume <code>gp3</code> in storage class on EKS.<br />
You can check by deploying resources:</p>
<pre><code>cat << EOF | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: ebs-gp3-claim
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: ebs-sc
---
apiVersion: v1
kind: Pod
metadata:
name: app-gp3-in-tree
spec:
containers:
- name: app
image: nginx
volumeMounts:
- name: persistent-storage
mountPath: /usr/share/nginx/html
volumes:
- name: persistent-storage
persistentVolumeClaim:
claimName: ebs-gp3-claim
EOF
</code></pre>
<p>Detailed documentation on Migrating Amazon EKS clusters from gp2 to gp3 EBS volumes: <a href="https://aws.amazon.com/vi/blogs/containers/migrating-amazon-eks-clusters-from-gp2-to-gp3-ebs-volumes/" rel="nofollow noreferrer">https://aws.amazon.com/vi/blogs/containers/migrating-amazon-eks-clusters-from-gp2-to-gp3-ebs-volumes/</a></p>
<p>References: <a href="https://stackoverflow.com/questions/69290796/persistent-storage-in-eks-failing-to-provision-volume">Persistent Storage in EKS failing to provision volume</a></p>
|
<p>While running a spark job with a Kubernetes cluster, we get the following error:</p>
<pre><code>2018-11-30 14:00:47 INFO DAGScheduler:54 - Resubmitted ShuffleMapTask(1, 58), so marking it as still running.
2018-11-30 14:00:47 WARN TaskSetManager:66 - Lost task 310.0 in stage 1.0 (TID 311, 10.233.71.29, executor 3): ExecutorLostFailure (executor 3 exited caused by one of the running tasks) Reason:
The executor with id 3 exited with exit code -1.
The API gave the following brief reason: Evicted
The API gave the following message: The node was low on resource: ephemeral-storage. Container executor was using 515228Ki, which exceeds its request of 0.
The API gave the following container statuses:
</code></pre>
<p>How to configure the job so we can increase the ephemeral storage size of each container ?</p>
<p>We use spark 2.4.0 and Kubernetes 1.12.1</p>
<p>The spark submit option is as follow</p>
<pre><code>--conf spark.local.dir=/mnt/tmp \
--conf spark.executor.instances=4 \
--conf spark.executor.cores=8 \
--conf spark.executor.memory=100g \
--conf spark.driver.memory=4g \
--conf spark.driver.cores=1 \
--conf spark.kubernetes.memoryOverheadFactor=0.1 \
--conf spark.kubernetes.container.image=spark:2.4.0 \
--conf spark.kubernetes.namespace=visionlab \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
--conf spark.kubernetes.container.image.pullPolicy=Always \
--conf spark.kubernetes.driver.volumes.persistentVolumeClaim.myvolume.options.claimName=pvc \
--conf spark.kubernetes.driver.volumes.persistentVolumeClaim.myvolume.mount.path=/mnt/ \
--conf spark.kubernetes.driver.volumes.persistentVolumeClaim.myvolume.mount.readOnly=false \
--conf spark.kubernetes.executor.volumes.persistentVolumeClaim.myvolume.options.claimName=pvc \
--conf spark.kubernetes.executor.volumes.persistentVolumeClaim.myvolume.mount.path=/mnt/ \
--conf spark.kubernetes.executor.volumes.persistentVolumeClaim.myvolume.mount.readOnly=false
</code></pre>
| <p>Had the same problem but I was able to upgrade to Spark 3.x where you can provide a <a href="http://spark.apache.org/docs/3.0.0/running-on-kubernetes.html#pod-template" rel="nofollow noreferrer">Pod Template</a>.</p>
<pre><code>--conf spark.kubernetes.executor.podTemplateFile=my_pod_template.yml
</code></pre>
<p>in which you can set the ephemeral storage request</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage:latest
resources:
requests:
ephemeral-storage: "50Gi"
</code></pre>
|
<p>I have a spring-boot postgres setup that I am trying to containerize and deploy in minikube. My pods and services show that they are up.</p>
<pre><code>$ kubectl get pods
NAME READY STATUS RESTARTS AGE
server-deployment-5bc57dcd4f-zrwzs 1/1 Running 0 14m
postgres-7f887f4d7d-5b8v5 1/1 Running 0 25m
</code></pre>
<pre><code>$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
server-service NodePort 10.100.21.232 <none> 8080:31457/TCP 15m
postgres ClusterIP 10.97.19.125 <none> 5432/TCP 26m
</code></pre>
<pre><code>$ minikube service list
|-------------|------------------|--------------|-----------------------------|
| NAMESPACE | NAME | TARGET PORT | URL |
|-------------|------------------|--------------|-----------------------------|
| default | kubernetes | No node port |
| kube-system | kube-dns | No node port |
| custom | server-service | http/8080 | http://192.168.59.106:31457 |
| custom | postgres | No node port |
|-------------|------------------|--------------|-----------------------------|
</code></pre>
<p>But when I try to hit any of my endpoints using postman, I get:</p>
<pre><code>Could not send request. Error: connect ECONNREFUSED 192.168.59.106:31457
</code></pre>
<p>I don't know where I am going wrong. I tried deploying the individual containers directly in docker (I had to modify some of the <code>application.properties</code> to get the rest server talking to the db container) and that works without a problem so clearly my server side code should not be a problem.</p>
<p>Here is the yml for the rest-server:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: server-deployment
namespace: custom
spec:
selector:
matchLabels:
app: server-deployment
template:
metadata:
name: server-deployment
labels:
app: server-deployment
spec:
containers:
- name: server-deployment
image: aruns1494/rest-server-k8s:latest
env:
- name: POSTGRES_USER
valueFrom:
configMapKeyRef:
name: postgres-config
key: postgres_user
- name: POSTGRES_PASSWORD
valueFrom:
configMapKeyRef:
name: postgres-config
key: postgres_password
- name: POSTGRES_SERVICE
valueFrom:
configMapKeyRef:
name: postgres-config
key: postgres_service
---
apiVersion: v1
kind: Service
metadata:
name: server-service
namespace: custom
spec:
selector:
name: server-deployment
ports:
- name: http
port: 8080
type: NodePort
</code></pre>
<p>I have not changed the spring boot's default port so I expect it to work on 8080. I tried connecting to that URL through chrome and Firefox and I get the same error message. I expect it to fall back to a default error message page when I try to hit the <code>/</code> endpoint.</p>
<p>I did look up several online articles but none of them seem to help. I am also attaching my kube-system pods if that helps:</p>
<pre><code>$ kubectl get pods -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-78fcd69978-x6mv6 1/1 Running 0 39m
etcd-minikube 1/1 Running 0 40m
kube-apiserver-minikube 1/1 Running 0 40m
kube-controller-manager-minikube 1/1 Running 0 40m
kube-proxy-dnr8p 1/1 Running 0 39m
kube-scheduler-minikube 1/1 Running 0 40m
storage-provisioner 1/1 Running 1 (39m ago) 40m
</code></pre>
| <p>My proposition is to check that provided Deployment and Service have the same labels and selectors, because now in the Deployment config pod label is <code>app: server-deployment</code>, but in the Service config selector is <code>name: server-deployment</code>.</p>
<p>If we want to use <code>name: server-deployment</code> selector for the Service, then we need to update the Deployment as shown below (<code>matchLabels</code> and <code>labels</code> fields):</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: server-deployment
namespace: custom
spec:
selector:
matchLabels:
name: server-deployment
template:
metadata:
name: server-deployment
labels:
name: server-deployment
spec:
containers:
...
</code></pre>
|
<p>I am trying to run a go-ethereum node on AWS EKS, for that i have used statefulsets with below configuration.
<a href="https://i.stack.imgur.com/RxyOt.png" rel="nofollow noreferrer">statefulset.yaml file</a></p>
<p>Running<code>kubectl apply -f statefulset.yaml</code> creates 2 pods out of which 1 is running and 1 is in CrashLoopBackOff state.
<a href="https://i.stack.imgur.com/PS6ez.png" rel="nofollow noreferrer">Pods status</a>
After checking the logs for second pod the error I am getting is <code>Fatal: Failed to create the protocol stack: datadir already used by another process</code>.
<a href="https://i.stack.imgur.com/J4rqa.png" rel="nofollow noreferrer">Error logs i am getting</a></p>
<p>The problem is mainly due to the pods using the same directory to write(geth data) on the persistant volume(i.e the pods are writing to '/data'). If I use a subpath expression and mount the pod's directory to a sub-directory with pod name(for eg: '/data/geth-0') it works fine.
<a href="https://i.stack.imgur.com/AxXQA.png" rel="nofollow noreferrer">statefulset.yaml with volume mounting to a sub directory with podname
</a>
But my requirement is that all the three pod's data is written at '/data' directory.
Below is my volume config file.
<a href="https://i.stack.imgur.com/fGegz.png" rel="nofollow noreferrer">volume configuration</a></p>
| <p>You need to dynamically provision the access point for each of your stateful pod. First create an EFS storage class that support dynamic provision:</p>
<pre><code>kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
name: efs-dyn-sc
provisioner: efs.csi.aws.com
reclaimPolicy: Retain
parameters:
provisioningMode: efs-ap
directoryPerms: "700"
fileSystemId: <get the ID from the EFS console>
</code></pre>
<p>Update your spec to support claim template:</p>
<pre><code>apiVersion: apps/v1
kind: StatefulSet
metadata:
name: geth
...
spec:
...
template:
...
spec:
containers:
- name: geth
...
volumeMounts:
- name: geth
mountPath: /data
...
volumeClaimTemplates:
- metadata:
name: geth
spec:
accessModes:
- ReadWriteOnce
storageClassName: efs-dyn-sc
resources:
requests:
storage: 5Gi
</code></pre>
<p>All pods now write to their own /data.</p>
|
<p>I have my python program running on k8s pod. The program reads data in pandas dataframe from the db & do some data transformation operations. In one of the operation, data size grows exponentially causing pod out of memory error. Since it's pandas, all data is held in the memory.</p>
<p>To avoid this, I am required to write the data to the disk if memory consumption crosses the threshold. And to do this, I need to know the current pod memory utilization inside my python program so that as soon as threshold reaches, say 90%, I start dumping data to disk & freeing memory.</p>
<p>Basically I need to know pod memory utilization inside my python program.</p>
<p>Any suggestions?
Thanks in advance.</p>
| <p>In container, you need to get cgroup's memory.</p>
<pre><code> ls /sys/fs/cgroup/memory/
</code></pre>
<p>In container: <code>cat /sys/fs/cgroup/memory/memory.usage_in_bytes</code> to get memory usage.</p>
<p>Or in host: <code>/sys/fs/cgroup/memory/docker/[containerId]/memory.usage_in_bytes</code></p>
<p><a href="https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt" rel="noreferrer">https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt</a></p>
|
<p>I have a Django application deployed on a K8s cluster. I need to send some emails (some are scheduled, others should be sent asynchronously), and the idea was to delegate those emails to Celery.</p>
<p>So I set up a Redis server (with Sentinel) on the cluster, and deployed an instance for a Celery worker and another for Celery beat.</p>
<p>The k8s object used to deploy the Celery worker is pretty similar to the one used for the Django application. The main difference is the command introduced on the celery worker: <code>['celery', '-A', 'saleor', 'worker', '-l', 'INFO']</code></p>
<p>Scheduled emails are sent with no problem (celery worker and celery beat don't have any problems connecting to the Redis server). However, the asynchronous emails - "delegated" by the Django application - are not sent because it is not possible to connect to the Redis server (<code>ERROR celery.backends.redis Connection to Redis lost: Retry (1/20) in 1.00 second. [PID:7:uWSGIWorker1Core0]</code>)</p>
<p>Error 1:</p>
<pre><code>socket.gaierror: [Errno -5] No address associated with hostname
</code></pre>
<p>Error 2:</p>
<pre><code>redis.exceptions.ConnectionError: Error -5 connecting to redis:6379. No address associated with hostname.
</code></pre>
<p>The Redis server, Celery worker, and Celery beat are in a "redis" namespace, while the other things, including the Django app, are in the "development" namespace.</p>
<p>Here are the variables that I define:</p>
<pre><code>- name: CELERY_PASSWORD
valueFrom:
secretKeyRef:
name: redis-password
key: redis_password
- name: CELERY_BROKER_URL
value: redis://:$(CELERY_PASSWORD)@redis:6379/1
- name: CELERY_RESULT_BACKEND
value: redis://:$(CELERY_PASSWORD)@redis:6379/1
</code></pre>
<p>I also tried to define <code>CELERY_BACKEND_URL</code> (with the same value as <code>CELERY_RESULT_BACKEND</code>), but it made no difference.</p>
<p>What could be the cause for not connecting to the Redis server? Am I missing any variables? Could it be because pods are in a different namespace?</p>
<p>Thanks!</p>
| <p><strong>Solution from @sofia that helped to fix this issue:</strong></p>
<p>You need to use the same namespace for the Redis server and for the Django application. In this particular case, change the namespace "redis" to "development" where the application is deployed.</p>
|
<p>I am following <a href="https://medium.com/@maheshd7878/restore-backup-migrate-kubernetes-cluster-with-velero-434fa151f1e8" rel="nofollow noreferrer">this tutorial</a> to install Velero to backup my cluster.</p>
<p>I have successfully installed the Minio the deployment but I am encountering a problem when installing Velero itself.</p>
<p>When I run the command:</p>
<pre><code> velero install \
--provider aws \
--plugins velero/velero-plugin-for-aws:v1.0.0 \
--bucket velero \
--secret-file ./credentials-velero \
--use-volume-snapshots=false \
--backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.velero.svc:9000
</code></pre>
<p>I keep getting this error:</p>
<pre><code>CustomResourceDefinition/backups.velero.io: attempting to create resource
An error occurred:
Error installing Velero. Use `kubectl logs deploy/velero -n velero` to check the deploy logs: Error creating resource CustomResourceDefinition/backups.velero.io: the server could not find the requested resource
</code></pre>
<p>When I type the <code>kubectl logs</code> command, I get this:</p>
<pre><code>ubuntu@kubemaster:~$ kubectl logs deploy/velero -n velero
Error from server (NotFound): deployments.apps "velero" not found
</code></pre>
<p>Am I missed something?</p>
| <p>In the article you mentioned you fetch and install <code>minio 1.1.0</code> version.</p>
<pre><code>curl -LO https://github.com/heptio/velero/releases/download/v1.1.0/velero-v1.1.0-linux-amd64.tar.gz
tar -C /usr/local/bin -xzvf velero-v1.1.0-linux-amd64.tar.gz
export PATH=$PATH:/usr/local/bin/velero-v1.1.0-linux-amd64/
</code></pre>
<p>At the same time you use aws plugin in command <code>--plugins velero/velero-plugin-for-aws:v1.0.0</code></p>
<hr />
<p>As per <a href="https://github.com/vmware-tanzu/velero/issues/2572#issuecomment-638269556" rel="nofollow noreferrer">comment</a> in <a href="https://github.com/vmware-tanzu/velero/issues/2572#" rel="nofollow noreferrer">Error in creating CRD on openshift 3.11</a>:</p>
<blockquote>
<p>for v1.1 you don't need to use an external AWS plugin, it was still
in-tree. Please make sure you're following the correct docs for the
Velero version you're using: <a href="https://velero.io/docs/v1.1.0/aws-config/" rel="nofollow noreferrer">https://velero.io/docs/v1.1.0/aws-config/</a></p>
</blockquote>
<p>By opening documentation for 1.1.0 aws configuration you see that no plugin argument was used in <code>velero install</code> command (by the way in medium article also).</p>
<pre><code>velero install \
--provider aws \
--bucket $BUCKET \
--secret-file ./credentials-velero \
--backup-location-config region=$REGION \
--snapshot-location-config region=$REGION
</code></pre>
<p>So it could be version issue. Think you should either use newer <a href="https://github.com/vmware-tanzu/velero/tags" rel="nofollow noreferrer">velero versions</a> either configure aws without plugin according to old documentation.</p>
|
<p>I have <a href="https://github.com/kubernetes-client/csharp/" rel="nofollow noreferrer">KubernetesClient</a> code running my app on K3s Orchestrator.</p>
<p>I want to understand the difference(use-case) between two K3s APIs <code>PatchNamespacedServiceWithHttpMessagesAsync</code> and <code>ReplaceNamespacedServiceWithHttpMessagesAsync</code> <a href="https://raw.githubusercontent.com/kubernetes-client/csharp/463e2d94dfe5a4bb54372aaab957ca8d794d767e/src/KubernetesClient/generated/Kubernetes.cs" rel="nofollow noreferrer">[link to these APIs]</a>. Apart from this link I cant find any place to read about K3s APIs use cases. Please help me here.</p>
<p><strong>PS:</strong></p>
<ol>
<li>Basically I am trying to update the existing Service, so want to understand the difference between above two APIs, either of which I will be calling with updated Patch body (updated service deployment).<br/></li>
<li>This que is extension of my <a href="https://stackoverflow.com/questions/70076040/how-to-find-existing-service-by-kubernetes-c-sharp-client-api">previous que</a></li>
</ol>
| <p><strong>TL;DR</strong></p>
<p><strong><code>ReplaceNamespacedServiceWithHttpMessagesAsync</code> use <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT" rel="nofollow noreferrer">PUT</a> HTTP method. <code>PatchNamespacedServiceWithHttpMessagesAsync</code> use <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH" rel="nofollow noreferrer">PATCH</a> HTTP method.</strong></p>
<p>PUT method is to update or create a new object. If such an object already exists, all data are updated, if not, a new object is created on the basis of the information sent. The PATCH method, like PUT, is used to update data about an object, but it requires the object to exist. This is because it does not send complete data in the request, but only the data that is to be updated.</p>
<hr />
<p><strong>Overall, both APIs are very similar to each other. They only differ in a few places:</strong></p>
<p>We have a different name in the first line:
In the <code>ReplaceNamespacedServiceWithHttpMessagesAsync</code></p>
<pre><code>public async Task<HttpOperationResponse<V1Service>> ReplaceNamespacedServiceWithHttpMessagesAsync(
V1Service body,
</code></pre>
<p>and in the <code>PatchNamespacedServiceWithHttpMessagesAsync</code>:</p>
<pre><code>public async Task<HttpOperationResponse<V1Service>> PatchNamespacedServiceWithHttpMessagesAsync(
V1Patch body,
</code></pre>
<hr />
<p>A <code>bool</code> is added to the 7th line in the <code>PatchNamespacedServiceWithHttpMessagesAsync</code></p>
<pre><code>bool? force = null,
</code></pre>
<p>and in the 36th line:</p>
<pre><code>tracingParameters.Add("force", force);
</code></pre>
<hr />
<p>Lines 37th for <code>ReplaceNamespacedServiceWithHttpMessagesAsync</code> and 39th for <code>PatchNamespacedServiceWithHttpMessagesAsync</code>are also different:</p>
<pre><code>ServiceClientTracing.Enter(_invocationId, this, "ReplaceNamespacedService", tracingParameters);
</code></pre>
<p>vs</p>
<pre><code>ServiceClientTracing.Enter(_invocationId, this, "PatchNamespacedService", tracingParameters);
</code></pre>
<hr />
<p>Then is added a fragment (from 56th to 59th ) line for <code>PatchNamespacedServiceWithHttpMessagesAsync</code>:</p>
<pre><code>if (force != null)
{
_queryParameters.Add(string.Format("force={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(force, SerializationSettings).Trim('"'))));
}
</code></pre>
<p><strong>The last and most important difference is the 65th line in the <code>ReplaceNamespacedServiceWithHttpMessagesAsync</code> and 71th line in the <code>PatchNamespacedServiceWithHttpMessagesAsync</code> .</strong></p>
<pre><code>_httpRequest.Method = HttpMethod.Put;
</code></pre>
<p>vs</p>
<pre><code>_httpRequest.Method = HttpMethod.Patch;
</code></pre>
|
<p>I have a deployment YAML file and I have 4 different containers in a single pod.
I want to do this when one of the containers is crashes then I want to restart the pod.</p>
<p>Right now when the container is crashed, only that container restart but I want to restart all containers</p>
| <p>A Deployment can't do this but you could abuse a <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#job-v1-batch" rel="nofollow noreferrer">Job</a> with a <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy" rel="nofollow noreferrer">restartPolicy</a> of Never to achieve it. But it's a hack and definitely <strong>violates best practices</strong>. It would require each container to artificially fail if any other container failed:</p>
<ol>
<li>Use a Job with a restartPolicy of Never instead of a Deployment</li>
<li>Make each container regularly write some "I'm alive" message to some shared location, e.g. an emptyDir volume that's shared between all the containers in the Pod</li>
<li>Make each container monitor the "I'm alive" messages of all other containers, and when one is missing (which means that this container crashed), then crash this container on purpose (e.g. <code>exit 1</code>)</li>
</ol>
<p>The effect of this is that when one container crashes, then all containers crash. When all containers crashed, the Pod is declared as <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase" rel="nofollow noreferrer">Failed</a> and the Job Controller restarts the entire Pod.</p>
<p>Note however that each restart counts against the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#jobspec-v1-batch" rel="nofollow noreferrer">backoffLimit</a> of the Job, so when this limit is reached, the Job is declared as failed and Pods won't be restarted anymore. Also note that this works only if the Pod template in the Job has a restartPolicy of Never, because with OnFailure (see <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy" rel="nofollow noreferrer">docs</a>), failed containers are restarted immediately and each container restart counts against the Job's backoffLimit (see <a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/#job-termination-and-cleanup" rel="nofollow noreferrer">docs</a>).</p>
<p>As mentioned, it's an abuse of what a Job is supposed to do and therefore I would <strong>not recommend</strong> to use this in production or for any serious workloads. But it would probably allow you to do what you want for playing around.</p>
|
<p>I have a server to server calls and I use GRPC (with .net core 5) It's working and test in local.</p>
<p>After that, I have moved all the services to Kubernetes Pod (Docker Desktop) and also tested through the flow (with swagger post-call) and it's working there too.</p>
<p>Now for monitoring, I added ISTIO and added the label to my namespace "<em>istio-injection=enabled</em>"
restarted all my pods and now all are having 2 containers inside each pod.</p>
<p>I tested the basic services (again swagger) and it's working. when it comes to testing the GRPC call. The call is failing from the caller side saying</p>
<p><strong>Grpc.Core.RpcException: Status(StatusCode="Unavailable", Detail="upstream connect error or disconnect/reset before headers. reset reason: protocol error")</strong></p>
<p>I checked the logs at GRPC server-side and it has no clue about this call and the service is just running. then I am kind of thinking that error is coming from the caller side whereas it is not able to or make a call to GRPC server.</p>
<p><a href="https://i.stack.imgur.com/Jgv0j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jgv0j.png" alt="enter image description here" /></a></p>
<p>The error detail:</p>
<pre><code>Grpc.Core.RpcException: Status(StatusCode="Unavailable", Detail="upstream connect error or disconnect/reset before headers. reset reason: protocol error")
at Basket.API.GrpcServices.DiscountGrpcService.GetDiscount(String productName) in /src/Services/Basket/Basket.API/GrpcServices/DiscountGrpcService.cs:line 21
at Basket.API.Controllers.BasketController.UpdateBasket(ShoppingCart basket) in /src/Services/Basket/Basket.API/Controllers/BasketController.cs:line 47 at lambda_method7(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Obje
</code></pre>
<p><em><strong>Again, I remove the Istio and tested and that's started working again (without changing anything) I added istio back and it started failing again. all other services are working with istio but not this call (This is only GRPC call I have).</strong></em></p>
| <p>I found a solution at <a href="https://istiobyexample.dev/grpc/" rel="nofollow noreferrer">https://istiobyexample.dev/grpc/</a> where it describes the missing item.</p>
<p>istio recommends using the name and version tag as Label but more importantly when working with GRPC, the service that exposes the GRPC needs to have the port name GRPC.</p>
<p>I have added that restarted the service and it got started working as expected.
Again it's not something I resolved. All credit goes to the link <a href="https://istiobyexample.dev/grpc/" rel="nofollow noreferrer">https://istiobyexample.dev/grpc/</a> and the image posted below.</p>
<p><a href="https://i.stack.imgur.com/NDvCp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NDvCp.png" alt="enter image description here" /></a></p>
|
<p>I am looking at how to make OpenVPN client work on a pod's container, I explain what I do, but you can skip all my explanation and offer your solution directly, I don't care replacing all the below with your steps if it works, I want to make my container to use a VPN (ExpressVPN for example) in a way that both external and internal networking works.</p>
<p>I have a docker image that is an OpenVPN Client, it works fine with the command:</p>
<pre class="lang-bash prettyprint-override"><code>docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun my-app /bin/bash
</code></pre>
<p>The docker image had an entry point bash script:</p>
<pre class="lang-bash prettyprint-override"><code>curl https://vpnvendor/configurations.zip -o /app/configurations.zip
mkdir -p /app/open_vpn/ip_vanish/config
unzip /app/configurations.zip -d /app/open_vpn/config
printf "username\npassword\n" > /app/open_vpn/vpn-auth.conf
cd /app/open_vpn/config
openvpn --config ./config.ovpn --auth-user-pass /app/open_vpn/vpn-auth.conf
</code></pre>
<p>It works fine, but when I deploy it as a container in a K8S Pod, it breaks, it is understandable, K8S clusters need internal network communication between the nodes, so the VPN breaks it ... how do I make it work? the Google search was frustrating, none of the solutions worked and there were just a few, there is one with similar issue: <a href="https://stackoverflow.com/questions/65494743/openvpn-client-pod-on-k8s-local-network-unreachable/65504666">OpenVPN-Client Pod on K8s - Local network unreachable</a>
But did not understand it very well, please help.</p>
<p>Since IPVanish is well known, let's take their ovpn example, I use other vendor but had access to an IPVanish account and it does not work either:</p>
<pre class="lang-bash prettyprint-override"><code>client
dev tun
proto udp
remote lon-a52.ipvanish.com 443
resolv-retry infinite
nobind
persist-key
persist-tun
persist-remote-ip
ca ca.ipvanish.com.crt
verify-x509-name lon-a52.ipvanish.com name
auth-user-pass
comp-lzo
verb 3
auth SHA256
cipher AES-256-CBC
keysize 256
tls-cipher TLS-DHE-RSA-WITH-AES-256-CBC-SHA:TLS-DHE-DSS-WITH-AES-256-CBC-SHA:TLS-RSA-WITH-AES-256-CBC-SHA
</code></pre>
<p>I accept responses in Golang or YAML it does not matter, although I use go-client, my code for pod creation is:</p>
<pre class="lang-golang prettyprint-override"><code>podObj := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "mypod",
Namespace: "default",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "worker1",
Image: "192.168.1.138:5000/myimage",
ImagePullPolicy: v1.PullAlways,
Stdin: true,
TTY: true,
/* Trying to simulate --device=/dev/net/tun I copied the below, but it does not work
// https://garunski.medium.com/openvpn-and-minikube-25511099f8de
VolumeMounts: []v1.VolumeMount{
{
ReadOnly: true,
Name: "dev-tun",
MountPath: "/dev/net/tun",
},
},*/
SecurityContext: &v1.SecurityContext{
// Taken from https://caveofcode.com/how-to-setup-a-vpn-connection-from-inside-a-pod-in-kubernetes/
Privileged: boolPtr(true),
Capabilities: &v1.Capabilities{
Add: []v1.Capability{
"NET_ADMIN",
},
},
},
},
},
NodeName: "worker-node01",
},
}
clientset.CoreV1().Pods("default").Create(context.Background(), podObj, metav1.CreateOptions{})
</code></pre>
<p>I can add the <code>NET_ADMIN</code> capability, but I need also to give access to the <code>/dev/net/tun</code> device and that's the problem, but even If I find a way, it will break internal networking.</p>
<h2>Update one</h2>
<p>I made external networking work, by adding the following two lines in my docker's entry point:</p>
<pre class="lang-bash prettyprint-override"><code># Taken from https://caveofcode.com/how-to-setup-a-vpn-connection-from-inside-a-pod-in-kubernetes/
mknod /dev/net/tun c 10 200
chmod 600 /dev/net/tun
</code></pre>
| <p>Here is a minimal example of a pod with OpenVPN client. I used <a href="https://github.com/kylemanna/docker-openvpn" rel="noreferrer">kylemanna/openvpn</a> as a server and to generate a basic client config. I only added two routes to the generated config to make it working. See below:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Pod
metadata:
name: ovpn
namespace: default
spec:
containers:
- name: ovpn
image: debian:buster
args:
- bash
- -c
# install OpenVPN and curl; use curl in an endless loop to print external IP
- apt update && apt install -y openvpn curl && cd /config && openvpn client & while sleep 5; do echo $(date; curl --silent ifconfig.me/ip); done
volumeMounts:
- mountPath: /dev/net/tun
readOnly: true
name: tun-device
- mountPath: /config
name: config
securityContext:
capabilities:
add: ["NET_ADMIN"]
volumes:
- name: tun-device
hostPath:
path: /dev/net/tun
- name: config
secret:
secretName: ovpn-config
---
apiVersion: v1
kind: Secret
metadata:
name: ovpn-config
namespace: default
stringData:
client: |
# A sample config generated by https://github.com/kylemanna/docker-openvpn server
client
nobind
dev tun
# Remote server params
remote PASTE.SERVER.IP.HERE 1194 udp
# Push all traffic through the VPN
redirect-gateway def1
# except these two k8s subnets
route 10.43.0.0 255.255.0.0 net_gateway
route 10.42.0.0 255.255.0.0 net_gateway
# Below goes irrelevant TLS config
remote-cert-tls server
<key>
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
</key>
<cert>
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
</cert>
<ca>
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
</ca>
key-direction 1
<tls-auth>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
-----END OpenVPN Static key V1-----
</tls-auth>
</code></pre>
|
<p>I want to get a list of the names of all namespaces in a Kubernetes cluster using a kubectl command.</p>
<p>Currently, I am running the below kubectl command which gives me a list of all namespaces.</p>
<p>However, I don't want to see the 'ACTIVE' and 'AGE' columns. I just want the NAME column.</p>
<p>The reason behind this is so that I can add all of the items from the NAME column into an array for further processing.</p>
<pre><code>> kubectl get namespaces
NAME STATUS AGE
dread-gorge Active 284d
dread-lagoon Active 210d
carncier-basin Active 164d
chantague-shallows Active 164d
hilraine-loch Active 311d
stangrave-waters Active 271d
</code></pre>
| <p><strong>Solution-1:</strong></p>
<p>Here is an alternate way:</p>
<pre><code> kubectl get ns --no-headers -o custom-columns=":metadata.name"
</code></pre>
<blockquote>
<p>-o=custom-columns= Print a table using a comma separated list of custom columns</p>
</blockquote>
<p><strong>Solution-2:</strong></p>
<p>Another way of getting the name <em><strong>with the type of resource</strong></em>:</p>
<pre><code>kubectl get ns -o name
</code></pre>
|
<p>After deploying a simple API, mongodb is started even without any configuration in the API.</p>
<p><strong>Log error in pod:</strong></p>
<pre><code>2021-11-23 14:45:46 INFO [,,] Located property source: [BootstrapPropertySource {name='bootstrapProperties-configmap.api-products.default'}]
2021-11-23 14:45:47 INFO [,,] The following profiles are active: kubernetes
2021-11-23 14:45:48 INFO [,,] Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-11-23 14:45:48 INFO [,,] Finished Spring Data repository scanning in 5 ms. Found 0 MongoDB repository interfaces.
2021-11-23 14:45:49 INFO [,,] BeanFactory id=15b1d6de-94f9-35c9-8f2b-4562a7a1e1e6
2021-11-23 14:45:49 INFO [,,] Bean 'io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsAutoConfiguration' of type [io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-11-23 14:45:49 INFO [,,] Bean 'io.kubernetes.client.spring.extended.network.config.KubernetesLoadBalancerAutoConfiguration' of type [io.kubernetes.client.spring.extended.network.config.KubernetesLoadBalancerAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-11-23 14:45:50 INFO [,,] Tomcat initialized with port(s): 8080 (http)
2021-11-23 14:45:50 INFO [,,] Starting service [Tomcat]
2021-11-23 14:45:50 INFO [,,] Starting Servlet engine: [Apache Tomcat/9.0.53]
2021-11-23 14:45:50 INFO [,,] Initializing Spring embedded WebApplicationContext
2021-11-23 14:45:50 INFO [,,] Root WebApplicationContext: initialization completed in 3348 ms
2021-11-23 14:45:52 INFO [,,] Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-11-23 14:45:52 INFO [,,] Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.2.3.jar!/:na]
at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]
at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.2.3.jar!/:na]
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.2.3.jar!/:na]
</code></pre>
<p>Besides, <strong>the API is configured to port 8000.</strong></p>
| <p>After some testing I found that the problem was the name of the environment variables in the Spring application's yaml file. The most strange was the error about "MongoDB" where i not used it!!!!!!</p>
<p><strong>The solution</strong> was change de variables names.</p>
<p><strong>Be careful the name variables. When similary the environments, can do strange errors</strong></p>
|
<p>I have a deployment YAML file and I have 4 different containers in a single pod.
I want to do this when one of the containers is crashes then I want to restart the pod.</p>
<p>Right now when the container is crashed, only that container restart but I want to restart all containers</p>
| <p>you can use preStop hook on each container to send a message to other ones to shutdown which will restart those containers. it is not the same as restarting pod, but might help with your use case</p>
|
<p>For some reason, my Pod in k8s could possibly labeled with <code>syscode</code> or <code>cib_syscode</code>, how can I relabel both of them to <code>cib_syscode</code>? That is to say if pod labeled with one of them, choose its label value as the result.
I have tried as follow, but it doesn't work because the target_label is duplicate.</p>
<pre class="lang-yaml prettyprint-override"><code> - job_name: ncr
honor_labels: true
scrape_interval: 30s
scrape_timeout: 30s
metrics_path: /metrics
scheme: http
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_syscode]
separator: ;
regex: (.*)
target_label: cib_syscode
replacement: ${1}
action: replace
- source_labels: [__meta_kubernetes_pod_label_cib_syscode]
separator: ;
regex: (.*)
target_label: cib_syscode
replacement: ${1}
action: replace
</code></pre>
<p>Looking forward to your reply, thank you!</p>
| <p>Try the following:</p>
<pre class="lang-yaml prettyprint-override"><code> - job_name: ncr
honor_labels: true
scrape_interval: 30s
scrape_timeout: 30s
metrics_path: /metrics
scheme: http
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_syscode, __meta_kubernetes_pod_label_cib_syscode]
separator: ;
regex: ([^;]+)
target_label: cib_syscode
replacement: ${1}
action: replace
</code></pre>
<p>If either <code>__meta_kubernetes_pod_label_syscode</code> or <code>__meta_kubernetes_pod_label_cib_syscode</code> is set, then the regex should select its value (i.e. a continuous string not containing the separator <code>;</code>) and assign it to the <code>cib_syscode</code> target label.</p>
|
<p>I have a powershell script, that take my variable and deliver it to the my helm upgrade command</p>
<pre><code>param
(
[Parameter(Mandatory = $false)]
$HELM_SET
)
helm upgrade --install myrelease -n dev my_service.tgz $HELM_SET
</code></pre>
<p>My HELM_SET var contains:<br />
<code>--set config.vali=x --set config.spring=v1</code></p>
<p>But helm said after upgrade:
Error: unknown flag: --set config.vali
helm.go:88: [debug] unknown flag: --set config.vali</p>
<p>if i'm add "--set" into
<code>helm upgrade --install myrelease -n dev my_service.tgz --set $HELM_SET </code>
and my HELM_SET var now contains:
<code>config.vali=x --set config.spring=v1</code></p>
<p>after upgrade i receive that my config:vali var is <code>x --set config.spring=v1</code></p>
<p>Can someone explain me what i'm doing wrong?</p>
|
<p><strong>If you're passing <code>$HELM_SET</code> as a <em>single string</em> encoding <em>multiple arguments</em>, you cannot pass it as-is to a command</strong>.</p>
<p>Instead, you'll need to parse this string into an <em>array</em> of <em>individual</em> arguments.</p>
<p>In the <strong><em>simplest</em> case</strong>, using the unary form of the <a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Split" rel="nofollow noreferrer"><code>-split</code> operator</a>, which splits the string into an array of tokens by whitespace:</p>
<pre class="lang-sh prettyprint-override"><code>helm upgrade --install myrelease -n dev my_service.tgz (-split $HELM_SET)
</code></pre>
<p>However, <strong>if your arguments include <em>quoted strings</em></strong> (e.g. <code>--set config.spring="v 1"</code>), more work is needed, because the quoted strings must be recognize as such, so as not to break them into multiple tokens by their <em>embedded</em> whitespace:</p>
<pre class="lang-sh prettyprint-override"><code># Note: Use of Invoke-Expression is safe here, but should generally be avoided.
$passThruArgs = (Invoke-Expression ('Write-Output -- ' + $HELM_SET -replace '\$', "`0")) -replace "`0", '$$'
helm upgrade --install myrelease -n dev my_service.tgz $passThruArgs
</code></pre>
<p>See <a href="https://stackoverflow.com/a/67423062/45375">this answer</a> for an explanation of this technique.</p>
<hr />
<p><strong>If you control the <em>invocation</em> of your script, a <em>simpler solution</em> is available:</strong></p>
<p>As <a href="https://stackoverflow.com/users/15339544/santiago-squarzon">Santiago Squarzon</a> points out, you can use the <code>ValueFromRemainingArguments</code> property of a parameter declaration to collect all arguments (that aren't bound to other parameters):</p>
<pre class="lang-sh prettyprint-override"><code>param
(
[Parameter(ValueFromRemainingArguments)]
$__passThruArgs # Choose an exotic name that won't be used in the actual arguments
)
helm upgrade --install myrelease -n dev my_service.tgz $__passThruArgs
</code></pre>
<p>Instead of passing the pass-through arguments <em>as a single string</em>, you would then pass them <em>as individual arguments</em>:</p>
<pre class="lang-sh prettyprint-override"><code>./yourScript.ps1 --set config.vali=x --set config.spring=v1
</code></pre>
|
<p>I'm trying to get the nginx ingress controller load balancer ip in Azure AKS. I figured I would use the kubernetes provider via:</p>
<pre><code>data "kubernetes_service" "nginx_service" {
metadata {
name = "${local.ingress_name}-ingress-nginx-controller"
namespace = local.ingress_ns
}
depends_on = [helm_release.ingress]
}
</code></pre>
<p>However, i'm not seeing the IP address, this is what i get back:</p>
<pre><code>nginx_service = [
+ {
+ cluster_ip = "10.0.165.249"
+ external_ips = []
+ external_name = ""
+ external_traffic_policy = "Local"
+ health_check_node_port = 31089
+ load_balancer_ip = ""
+ load_balancer_source_ranges = []
+ port = [
+ {
+ name = "http"
+ node_port = 30784
+ port = 80
+ protocol = "TCP"
+ target_port = "http"
},
+ {
+ name = "https"
+ node_port = 32337
+ port = 443
+ protocol = "TCP"
+ target_port = "https"
},
]
+ publish_not_ready_addresses = false
+ selector = {
+ "app.kubernetes.io/component" = "controller"
+ "app.kubernetes.io/instance" = "nginx-ingress-internal"
+ "app.kubernetes.io/name" = "ingress-nginx"
}
+ session_affinity = "None"
+ type = "LoadBalancer"
},
]
</code></pre>
<p>However when I pull down the service via <code>kubectl</code> I can get the IP address via:</p>
<pre><code> kubectl get svc nginx-ingress-internal-ingress-nginx-controller -n nginx-ingress -o json | jq -r '.status.loadBalancer.ingress[].ip'
10.141.100.158
</code></pre>
<p>Is this a limitation of kubernetes provider for AKS? If so, what is a workaround other people have used? My end goals is to use the IP to configure the application gateway backend.</p>
<p>I guess I can use <code>local-exec</code>, but that seem hacky. Howerver, this might be my only option at the moment.</p>
<p>Thanks,</p>
<p>Jerry</p>
| <p>although i strongly advise against creating resources inside Kubernetes with Terraform, you can do that:</p>
<p>Create a Public IP with Terraform -> Create the ingress-nginx inside Kubernetes with Terraform and pass <code>annotations</code> and <code>loadBalancerIP</code>with data from your Terraform resources. The final manifest should look like this:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
annotations:
service.beta.kubernetes.io/azure-load-balancer-resource-group: myResourceGroup
name: ingress-nginx-controller
spec:
loadBalancerIP: <YOUR_STATIC_IP>
type: LoadBalancer
</code></pre>
<p>Terraform could look like this:</p>
<pre><code>resource "kubernetes_service" "ingress_nginx" {
metadata {
name = "tingress-nginx-controller"
annotations {
"service.beta.kubernetes.io/azure-load-balancer-resource-group" = "${azurerm_resource_group.YOUR_RG.name}"
}
spec {
selector = {
app = <PLACEHOLDER>
}
port {
port = <PLACEHOLDER>
target_port = <PLACEHOLDER>
}
type = "LoadBalancer"
load_balancer_ip = "${azurerm_public_ip.YOUR_IP.ip_address}"
}
}
</code></pre>
|
<p>I am trying to write the nginx ingress config for my k8s cluster.</p>
<pre><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: blabla-data-api-ingress
annotations:
nginx.ingress.kubernetes.io/proxy-connect-timeout: "360"
nginx.ingress.kubernetes.io/proxy-send-timeout: "360"
nginx.ingress.kubernetes.io/proxy-read-timeout: "360"
nginx.ingress.kubernetes.io/proxy-body-size: 256m
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header Authorization $http_authorization;
proxy_pass_header Authorization;
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt
spec:
tls:
- hosts:
- blabla-data.api.staging.20-74-47-80.nip.io
secretName: blabla-data-api-certification-staging
rules:
- host: blabla-data.api.staging.20-74-47-80.nip.io
http:
paths:
- backend:
serviceName: blabla-data-api
servicePort: 80
path: /
- backend:
serviceName: blabla-data-api
servicePort: 443
path: /
</code></pre>
<p>When I apply this config, I get this error:</p>
<pre><code>for: "kubernetes/staging/blabla-data-api-ingress.staging.yaml": admission webhook "validate.nginx.ingress.kubernetes.io" denied the request: nginx.ingress.kubernetes.io/configuration-snippet annotation contains invalid word proxy_pass
</code></pre>
<p>In fact, this piece of code used to work in the past.</p>
<p>I tried to add <code>--set controller.admissionWebhooks.enabled=false</code> in my <code>helm install nginx-ingress ingress-nginx/ingress-nginx</code> like that:</p>
<pre><code>helm install nginx-ingress ingress-nginx/ingress-nginx \
--namespace ingress \
--set controller.replicaCount=2 \
--set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \
--set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux \
--set controller.admissionWebhooks.enabled=false
</code></pre>
<p>In this case, I don't get any error while applying this ingress config but then I get a <code>404</code> from nginx when I try to access my server through the external API.</p>
| <p>OP has confirmed, that the issue was solved in <a href="https://github.com/kubernetes/ingress-nginx/issues/7837" rel="nofollow noreferrer">this github topic</a></p>
<blockquote>
<p>it was exactly the issue you mentioned, thanks for your help</p>
</blockquote>
<p>This problem is related to <a href="https://nvd.nist.gov/vuln/detail/CVE-2021-25742" rel="nofollow noreferrer">CVE-2021-25742</a>. Problem is solved based on this message:</p>
<blockquote>
<p>Hi folks we just released <a href="https://github.com/kubernetes/ingress-nginx/releases/tag/controller-v1.0.5" rel="nofollow noreferrer">Ingress NGINX v1.0.5.</a> Thanks to <a href="https://github.com/rikatz" rel="nofollow noreferrer">@rikatz</a> who helped implement<br />
<a href="https://github.com/kubernetes/ingress-nginx/pull/7874" rel="nofollow noreferrer">#7874</a> which added the option to sanitize annotation inputs</p>
<p><code>annotation-value-word-blocklist</code> defaults are <code>"load_module,lua_package,_by_lua,location,root,proxy_pass,serviceaccount,{,},',\"</code></p>
<p>Users from mod_security and other features should be aware that some blocked values may be used by those features and must be manually unblocked by the Ingress Administrator.</p>
<p>For more details please check <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#annotation-value-word-blocklist" rel="nofollow noreferrer">https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#annotation-value-word-blocklist</a></p>
<p>If you have any issues with this new feature or the release please <a href="https://github.com/kubernetes/ingress-nginx/issues/new/choose" rel="nofollow noreferrer">open a new issue</a> so we can track it there.</p>
</blockquote>
|
<p>I am encountering a weird behavior when I try to attach <code>podAffinity</code> to the <strong>Scheduler deployment from the official Airflow helm chart</strong>, like:</p>
<pre><code> affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- postgresql
topologyKey: "kubernetes.io/hostname"
</code></pre>
<p>With an example Deployment to which the <code>podAffinity</code> should "hook up" to:</p>
<pre><code>metadata:
name: {{ template "postgresql.fullname" . }}
labels:
app: postgresql
chart: {{ template "postgresql.chart" . }}
release: {{ .Release.Name | quote }}
heritage: {{ .Release.Service | quote }}
spec:
serviceName: {{ template "postgresql.fullname" . }}-headless
replicas: 1
selector:
matchLabels:
app: postgresql
release: {{ .Release.Name | quote }}
template:
metadata:
name: {{ template "postgresql.fullname" . }}
labels:
app: postgresql
chart: {{ template "postgresql.chart" . }}
</code></pre>
<p>Which results in:</p>
<pre><code>NotTriggerScaleUp: pod didn't trigger scale-up: 1 node(s) didn't match pod affinity/anti-affinity, 1 node(s) didn't match pod affinity rules
</code></pre>
<p><strong>However, applying the same <code>podAffinity</code> config to the Webserver deployment works just fine. Plus, changing the example Deployment to a vanilla nginx manifested itself in the outcome.</strong></p>
<p>It does not seem to be any resource limitation issue since I already tried various configs, every time with the same result.
I do not use any custom configurations apart from node affinity.</p>
<p>Has anyone encounter the same or has any idea what I might do wrong?</p>
<p><strong>Setup:</strong></p>
<ul>
<li>AKS cluster</li>
<li>Airflow helm chart 1.1.0</li>
<li>Airflow 1.10.15 (but I don't think this matters)</li>
<li>kubectl client (1.22.1) and server (1.20.7)</li>
</ul>
<p><strong>Links to Airflow charts:</strong></p>
<ul>
<li><a href="https://github.com/apache/airflow/blob/main/chart/templates/scheduler/scheduler-deployment.yaml" rel="nofollow noreferrer">Scheduler</a></li>
<li><a href="https://github.com/apache/airflow/blob/main/chart/templates/webserver/webserver-deployment.yaml" rel="nofollow noreferrer">Webserver</a></li>
</ul>
| <p>I've recreated this scenario on my GKE cluster and I've decided to provide a Community Wiki answer to show that the <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity" rel="nofollow noreferrer">podAffinity</a> on the <a href="https://github.com/apache/airflow/blob/main/chart/templates/scheduler/scheduler-deployment.yaml" rel="nofollow noreferrer">Scheduler</a> works as expected.
I will describe step by step how I tested it below.</p>
<hr />
<ol>
<li>In the <code>values.yaml</code> file, I've configured the <code>podAffinity</code> as follows:</li>
</ol>
<pre><code>$ cat values.yaml
...
# Airflow scheduler settings
scheduler: affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- postgresql
topologyKey: "kubernetes.io/hostname"
...
</code></pre>
<ol start="2">
<li>I've installed the <a href="https://airflow.apache.org/docs/helm-chart/stable/index.html#installing-the-chart" rel="nofollow noreferrer">Airflow</a> on a Kubernetes cluster using the Helm package manager with the <code>values.yaml</code> file specified.</li>
</ol>
<pre><code>$ helm install airflow apache-airflow/airflow --values values.yaml
</code></pre>
<p>After a while we can check the status of the <code>scheduler</code>:</p>
<pre><code>$ kubectl get pods -owide | grep "scheduler"
airflow-scheduler-79bfb664cc-7n68f 0/2 Pending 0 8m6s <none> <none> <none> <none>
</code></pre>
<ol start="3">
<li>I've created an example Deployment with the <code>app: postgresql</code> label:</li>
</ol>
<pre><code>$ cat test.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: postgresql
name: test
spec:
replicas: 1
selector:
matchLabels:
app: postgresql
template:
metadata:
labels:
app: postgresql
spec:
containers:
- image: nginx
name: nginx
$ kubectl apply -f test.yaml
deployment.apps/test created
$ kubectl get pods --show-labels | grep test
test-7d4c9c654-7lqns 1/1 Running 0 2m app=postgresql,...
</code></pre>
<ol start="4">
<li>Finally, we can check that the <code>scheduler</code> was successfully created:</li>
</ol>
<pre><code>$ kubectl get pods -o wide | grep "scheduler\|test"
airflow-scheduler-79bfb664cc-7n68f 2/2 Running 0 14m 10.X.1.6 nodeA
test-7d4c9c654-7lqns 1/1 Running 0 2m27s 10.X.1.5 nodeA
</code></pre>
<hr />
<p>Additionally, detailed informtion on <code>pod affinity</code> and <code>pod anti-affinity</code> can be found in the <a href="https://docs.openshift.com/container-platform/4.9/nodes/scheduling/nodes-scheduler-pod-affinity.html#nodes-scheduler-pod-affinity-about_nodes-scheduler-pod-affinity" rel="nofollow noreferrer">Understanding pod affinity</a> documentation:</p>
<blockquote>
<p>Pod affinity and pod anti-affinity allow you to constrain which nodes your pod is eligible to be scheduled on based on the key/value labels on other pods.</p>
<p>Pod affinity can tell the scheduler to locate a new pod on the same node as other pods if the label selector on the new pod matches the label on the current pod.</p>
<p>Pod anti-affinity can prevent the scheduler from locating a new pod on the same node as pods with the same labels if the label selector on the new pod matches the label on the current pod.</p>
</blockquote>
|
<p>As <a href="https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer" rel="nofollow noreferrer">the kubernetes.io docs state about a <code>Service</code> of type <code>LoadBalancer</code></a>:</p>
<blockquote>
<p>On cloud providers which support external load balancers, setting the
type field to LoadBalancer provisions a load balancer for your
Service. The actual creation of the load balancer happens
asynchronously, and information about the provisioned balancer is
published in the Service's <code>.status.loadBalancer</code> field.</p>
</blockquote>
<p>On AWS Elastic Kubernetes Service (EKS) a an AWS Load Balancer is provisioned that load balances network traffic (<a href="https://docs.aws.amazon.com/eks/latest/userguide/network-load-balancing.html" rel="nofollow noreferrer">see AWS docs</a> & <a href="https://github.com/jonashackt/tekton-argocd-eks" rel="nofollow noreferrer">the example project on GitHub provisioning a EKS cluster with Pulumi</a>). Assuming we have a <code>Deployment</code> ready with the selector <code>app=tekton-dashboard</code> (it's the <a href="https://tekton.dev/docs/dashboard/#installation" rel="nofollow noreferrer">default Tekton dashboard you can deploy as stated in the docs</a>), a <code>Service</code> of type <code>LoadBalancer</code> defined in <code>tekton-dashboard-service.yml</code> could look like this:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: tekton-dashboard-external-svc-manual
spec:
selector:
app: tekton-dashboard
ports:
- protocol: TCP
port: 80
targetPort: 9097
type: LoadBalancer
</code></pre>
<p>If we create the Service in our cluster with <code>kubectl apply -f tekton-dashboard-service.yml -n tekton-pipelines</code>, the AWS ELB get's created automatically:</p>
<p><a href="https://i.stack.imgur.com/Iq6Mi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iq6Mi.png" alt="enter image description here" /></a></p>
<p>There's only one problem: The <code>.status.loadBalancer</code> field is populated with the <code>ingress[0].hostname</code> field asynchronously and is therefore not available immediately. We can check this, if we run the following commands together:</p>
<pre><code>kubectl apply -f tekton-dashboard-service.yml -n tekton-pipelines && \
kubectl get service/tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer}'
</code></pre>
<p>The output will be an empty field:</p>
<pre><code>{}%
</code></pre>
<p>So if we want to run this setup in a CI pipeline for example (e.g. <a href="https://github.com/jonashackt/tekton-argocd-eks/blob/main/.github/workflows/provision.yml" rel="nofollow noreferrer">GitHub Actions, see the example project's workflow <code>provision.yml</code></a>), <strong>we need to somehow wait until the <code>.status.loadBalancer</code> field got populated with the AWS ELB's hostname.</strong> How can we achieve this using <code>kubectl wait</code>?</p>
| <p><strong>TLDR;</strong></p>
<p><a href="https://github.com/kubernetes/kubernetes/pull/105776" rel="nofollow noreferrer">Prior to Kubernetes <code>v1.23</code></a> it's not possible using <code>kubectl wait</code>, but using <code>until</code> together with <code>grep</code> like this:</p>
<pre><code>until kubectl get service/tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done
</code></pre>
<p>or even enhance the command <a href="https://stackoverflow.com/a/58759974/4964553">using timeout</a> (<a href="https://stackoverflow.com/a/70109348/4964553"><code>brew install coreutils</code> on a Mac</a>) to prevent the command from running infinitely:</p>
<pre><code>timeout 10s bash -c 'until kubectl get service/tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done'
</code></pre>
<p><strong>Problem with kubectl wait & the solution explained in detail</strong></p>
<p>As stated in <a href="https://stackoverflow.com/questions/66114851/kubectl-wait-for-service-to-get-external-ip">this so Q&A</a> and the kubernetes issues <a href="https://github.com/kubernetes/kubernetes/issues/80828#issuecomment-517555879" rel="nofollow noreferrer">kubectl wait unable to not wait for service ready #80828</a> & <a href="https://github.com/kubernetes/kubernetes/issues/80828" rel="nofollow noreferrer">kubectl wait on arbitrary jsonpath #83094</a> using <code>kubectl wait</code> for this isn't possible in current Kubernetes versions right now.</p>
<p>The main reason is, that <code>kubectl wait</code> assumes that the <code>status</code> field of a Kubernetes resource queried with <code>kubectl get service/xyz --output=yaml</code> contains a <code>conditions</code> list. Which a <code>Service</code> doesn't have. Using jsonpath here would be a solution and will be possible from Kubernetes <code>v1.23</code> on (see <a href="https://github.com/kubernetes/kubernetes/pull/105776" rel="nofollow noreferrer">this merged PR</a>). But until this version is broadly available in managed Kubernetes clusters like EKS, we need another solution. And it should also be available as "one-liner" just as a <code>kubectl wait</code> would be.</p>
<p>A good starting point could be this superuser answer about <a href="https://superuser.com/a/375331/497608">"watching" the output of a command until a particular string is observed and then exit</a>:</p>
<pre><code>until my_cmd | grep "String Im Looking For"; do : ; done
</code></pre>
<p>If we use this approach together with a <code>kubectl get</code> we can craft a command which will wait until the field <code>ingress</code> gets populated into the <code>status.loadBalancer</code> field in our <code>Service</code>:</p>
<pre><code>until kubectl get service/tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done
</code></pre>
<p>This will wait until the <code>ingress</code> field got populated and then print out the AWS ELB address (e.g. via using <code>kubectl get service tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}'</code> thereafter):</p>
<pre><code>$ until kubectl get service/tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done
{"ingress":[{"hostname":"a74b078064c7d4ba1b89bf4e92586af0-18561896.eu-central-1.elb.amazonaws.com"}]}
</code></pre>
<p>Now we have a one-liner command that behaves just like a <code>kubectl wait</code> for our <code>Service</code> to become available through the AWS Loadbalancer. We can double check if this is working with the following commands combined (be sure to delete the Service using <code>kubectl delete service/tekton-dashboard-external-svc-manual -n tekton-pipelines</code> before you execute it, because otherwise the Service incl. the AWS LoadBalancer already exists):</p>
<pre><code>kubectl apply -f tekton-dashboard-service.yml -n tekton-pipelines && \
until kubectl get service/tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer}' | grep "ingress"; do : ; done && \
kubectl get service tekton-dashboard-external-svc-manual -n tekton-pipelines --output=jsonpath='{.status.loadBalancer.ingress[0].hostname}'
</code></pre>
<p><a href="https://github.com/jonashackt/tekton-argocd-eks/runs/4321961432?check_suite_focus=true" rel="nofollow noreferrer">Here's also a full GitHub Actions pipeline run</a> if you're interested.</p>
|
<p>I have applied kiali in Istio 1.10.2 by using <a href="https://raw.githubusercontent.com/istio/istio/1.10.2/samples/addons/kiali.yaml" rel="nofollow noreferrer">this</a>. Now I am trying to secure it by filtering source ip address. I tried using authorization policy but it didn't work. It keeps allowing everyone when <a href="https://istio.io/latest/docs/reference/config/security/authorization-policy/" rel="nofollow noreferrer">it should deny any request that is not in the ALLOW policy</a></p>
<p>AuthorizationPolicy:</p>
<pre><code>apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: kiali-ingress-policy-allow
namespace: istio-system
spec:
selector:
matchLabels:
app: kiali
action: ALLOW
rules:
- from:
- source:
remoteIpBlocks: ["10.43.212.247/32","10.43.212.242/32"]
</code></pre>
<p>VirtualService:</p>
<pre><code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: kiali
namespace: istio-system
spec:
hosts:
- "kiali.myinternaldomain.local"
gateways:
- istio-system/my-internal-gateway
http:
- match:
- uri:
prefix: /
route:
- destination:
host: kiali
port:
number: 20001
</code></pre>
<p>Installed ISTIO using default profile and these extra parameters:</p>
<pre><code>apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
spec:
meshConfig:
accessLogFile: /dev/stdout
components:
ingressGateways:
- name: istio-ingressgateway
enabled: true
k8s:
overlays:
- apiVersion: apps/v1
kind: Deployment
name: istio-ingressgateway
patches:
- path: kind
value: DaemonSet
- path: spec.strategy
- path: spec.updateStrategy
value:
rollingUpdate:
maxUnavailable: 50%
type: RollingUpdate
egressGateways:
- name: istio-egressgateway
enabled: true
k8s:
hpaSpec:
minReplicas: 2
pilot:
k8s:
hpaSpec:
minReplicas: 2
values:
gateways:
istio-ingressgateway:
autoscaleEnabled: false
env:
ISTIO_META_HTTP10: '1'
pilot:
env:
PILOT_HTTP10: '1'
</code></pre>
| <p>I manage to setup working <code>ALLOW</code> policy in the Istio 1.10.2 on <a href="https://cloud.google.com/compute" rel="nofollow noreferrer">GCP VMs</a>, the cluster is setup using kubeadm with Calico CNI plugin. I used this documentation - <a href="https://istio.io/latest/docs/tasks/security/authorization/authz-ingress/" rel="nofollow noreferrer">Ingress Gateway</a>.</p>
<p>Note: I changed <code>istio-ingressgateway</code> service type to <code>NodePort</code> service instead of <code>LoadBalancer</code>, but this does not matter in this case.</p>
<hr />
<p>My network design is following:</p>
<ul>
<li>First VM - Kubernetes node - 10.xxx.0.2 address</li>
<li>Second VM - 10.xxx.0.3 address</li>
<li>Third VM - 10.xxx.0.4 address - this address will be in the ALLOW policy</li>
</ul>
<p>I deployed the following NGINX service and deployment...</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
name: nginx-svc
labels:
app: nginx
spec:
ports:
- name: http
port: 80
targetPort: 80
selector:
app: nginx
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deply
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
version: v1
spec:
containers:
- image: nginx
imagePullPolicy: IfNotPresent
name: nginx
ports:
- containerPort: 80
</code></pre>
<p>... and following gateway and virtual service definitions:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: gateway
spec:
selector:
istio: ingressgateway
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: nginx-vs
spec:
hosts:
- "my-test.com"
gateways:
- gateway
http:
- route:
- destination:
host: nginx-svc
port:
number: 80
</code></pre>
<p>Take a look at the <code>nginx-svc</code> service name in virtual service definition (you should use the one that you want to configure).</p>
<p>From every VM in the network I can run following command:</p>
<pre><code>user@vm-istio:~$ curl 10.xxx.0.2:31756 -H "Host: my-test.com"
<!DOCTYPE html>
...
<title>Welcome to nginx!</title>
</code></pre>
<p>So it's working properly.</p>
<p>I <a href="https://istio.io/latest/docs/tasks/security/authorization/authz-ingress/#before-you-begin" rel="nofollow noreferrer">enabled RBAC debugging for the ingress gateway pod</a>...</p>
<pre><code>kubectl get pods -n istio-system -o name -l istio=ingressgateway | sed 's|pod/||' | while read -r pod; do istioctl proxy-config log "$pod" -n istio-system --level rbac:debug; done
</code></pre>
<p>...and I set <code>externalTrafficPolicy</code> to <code>Local</code> in service <code>istio-ingressgateway</code> to <a href="https://istio.io/latest/docs/tasks/security/authorization/authz-ingress/#source-ip-address-of-the-original-client" rel="nofollow noreferrer">preserve an IP address from the original client</a>:</p>
<pre><code>kubectl patch svc istio-ingressgateway -n istio-system -p '{"spec":{"externalTrafficPolicy":"Local"}}
</code></pre>
<p>In the logs of the istio ingress gateway controller I can the that requests are coming and they are being proceed:</p>
<pre><code>kubectl logs istio-ingressgateway-5d57955454-9mz4b -n istio-system -f
...
[2021-11-24T13:39:47.220Z] "GET / HTTP/1.1" 200 - via_upstream - "-" 0 615 1 0 "10.xxx.0.3" "curl/7.64.0" "69953f69-8a46-9e2a-a5a7-36861bae4a77" "my-test.com" "192.168.98.74:80" outbound|80||nginx-svc.default.svc.cluster.local 192.168.98.72:60168 192.168.98.72:8080 10.xxx.0.3:55160 - -
[2021-11-24T13:39:48.980Z] "GET / HTTP/1.1" 200 - via_upstream - "-" 0 615 1 0 "10.xxx.0.4" "curl/7.64.0" "89284e11-42f9-9e84-b256-d3ea37311e92" "my-test.com" "192.168.98.74:80" outbound|80||nginx-svc.default.svc.cluster.local 192.168.98.72:60192 192.168.98.72:8080 10.xxx.0.4:35800 - -
</code></pre>
<p>Now, I will apply IP-based allow list to allow only second VM address to host <code>my-test.com</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: ingress-policy
namespace: istio-system
spec:
selector:
matchLabels:
app: istio-ingressgateway
action: ALLOW
rules:
- from:
- source:
ipBlocks: ["10.xxx.0.4"]
to:
- operation:
hosts:
- "my-test.com"
</code></pre>
<p>On the VM with address 10.xxx.0.4 curl is working as before, but on the VM with address 10.xxx.0.3 we can notice following:</p>
<pre><code>user@vm-istio:~$ curl 10.xxx.0.2:31756 -H "Host: my-test.com"
RBAC: access denied
</code></pre>
<p>So it's working as expected.</p>
<p>In the logs of the istio ingress gateway controller we can notice that request is denied (look for the logs related to the RBAC):</p>
<pre><code>kubectl logs istio-ingressgateway-5d57955454-9mz4b -n istio-system -f
2021-11-24T14:05:11.382613Z debug envoy rbac checking request: requestedServerName: , sourceIP: 10.xxx.0.3:55194, directRemoteIP: 10.xxx.0.3:55194, remoteIP: 10.xxx.0.3:55194,localAddress: 192.168.98.72:8080, ssl: none, headers: ':authority', 'my-test.com'
':path', '/'
':method', 'GET'
':scheme', 'http'
'user-agent', 'curl/7.64.0'
'accept', '*/*'
'x-forwarded-for', '10.xxx.0.3'
'x-forwarded-proto', 'http'
'x-envoy-internal', 'true'
'x-request-id', '63c0f55c-5545-92a0-80fc-aa2a5a63bf04'
'x-envoy-decorator-operation', 'nginx-svc.default.svc.cluster.local:80/*'
'x-envoy-peer-metadata', '...'
'x-envoy-peer-metadata-id', 'router~192.168.98.72~istio-ingressgateway-5d57955454-9mz4b.istio-system~istio-system.svc.cluster.local'
, dynamicMetadata:
2021-11-24T14:05:11.382662Z debug envoy rbac enforced denied, matched policy none
[2021-11-24T14:05:11.382Z] "GET / HTTP/1.1" 403 - rbac_access_denied_matched_policy[none] - "-" 0 19 0 - "10.xxx.0.3" "curl/7.64.0" "63c0f55c-5545-92a0-80fc-aa2a5a63bf04" "my-test.com" "-" outbound|80||nginx-svc.default.svc.cluster.local - 192.168.98.72:8080 10.xxx.0.3:55194 - -
</code></pre>
<p>Especially this part:</p>
<pre><code>[2021-11-24T14:05:11.382Z] "GET / HTTP/1.1" 403 - rbac_access_denied_matched_policy[none]
</code></pre>
<p>It clearly shows that our policy is working.</p>
<p>Example of the log that allowed our request:</p>
<pre><code>2021-11-25T10:58:34.717495Z debug envoy rbac enforced allowed, matched policy ns[istio-system]-policy[ingress-policy]-rule[0]
[2021-11-25T10:58:34.717Z] "GET / HTTP/1.1" 200 - via_upstream - "-" 0 615 25 23 "10.xxx.0.4" "curl/7.64.0" "889e3326-093c-94b1-b856-777c06cbe2b7" "my-test.com" "192.168.98.75:80" outbound|80||nginx-svc.default.svc.cluster.local 192.168.98.72:46190 192.168.98.72:8080 10.xxx.0.4:37148 - -
</code></pre>
<p>What's important:</p>
<ul>
<li>make sure that in logs of the pod <code>istio-ingressgateway-{..}</code> you can notice the source IP address of the other VM so the policy can allow / block</li>
<li>my advice is to setup AuthorizationPolicy <strong>for external traffic</strong> at the edge of service mesh - which is istio ingress gateway, that’s why my AuthorizationPolicy is using “selector” matching label <code>app: ingress-istio-ingressgateway</code> (not the kiali)</li>
<li><a href="https://istio.io/latest/docs/tasks/security/authorization/authz-ingress/#ip-based-allow-list-and-deny-list" rel="nofollow noreferrer">use a proper type of IPs - <code>ipBlocks</code> vs <code>remoteIpBlocks</code></a>. Base on your setup, it should be <code>ipBlocks</code>:</li>
</ul>
<blockquote>
<p><strong>When to use <code>ipBlocks</code> vs. <code>remoteIpBlocks</code>:</strong> If you are using the X-Forwarded-For HTTP header or the Proxy Protocol to determine the original client IP address, then you should use <code>remoteIpBlocks</code> in your <code>AuthorizationPolicy</code>. If you are using <code>externalTrafficPolicy: Local</code>, then you should use <code>ipBlocks</code> in your <code>AuthorizationPolicy</code>.</p>
</blockquote>
|
<p>The <a href="https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions" rel="nofollow noreferrer">Kubernetes docs</a> state the following about the <code>metadata.resourceVersion</code> of a K8s object</p>
<blockquote>
<p>You must not assume resource versions are numeric or collatable. API clients may only compare two resource versions for equality (this means that you must not compare resource versions for greater-than or less-than relationships).</p>
</blockquote>
<p>I'm glad I read this because I was about to do exactly the thing it says not to do (comparison with <code>></code> or <code><</code> to check consistency).</p>
<p>My question is: Why not? Why are clients not allowed to do this?</p>
<p>Edits: To clarify, the resource version this question refers to is the <code>metadata.resourceVersion</code> of K8s objects, not the <code>apiVersion</code>.</p>
<p>In my experience, the resource version is an integer, increasing monotonically in time (incremented each time the resource is modified). It seems the docs say this is not a guarantee.</p>
| <p>Posting this as a community wiki, feel free to edit and expand.</p>
<hr />
<p><strong>resourceVersion</strong></p>
<p>I think most correct answer will be:</p>
<blockquote>
<p>Kubernetes leverages the concept of resource versions to achieve
optimistic concurrency. All Kubernetes resources have a
"resourceVersion" field as part of their metadata. This
resourceVersion is a string that identifies the internal version of an
object that can be used by clients to determine when objects have
changed. When a record is about to be updated, it's version is checked
against a pre-saved value, and if it doesn't match, the update fails
with a StatusConflict (HTTP status code 409).</p>
<p>The resourceVersion is changed by the server every time an object is
modified. If resourceVersion is included with the PUT operation the
system will verify that there have not been other successful mutations
to the resource during a read/modify/write cycle, by verifying that
the current value of resourceVersion matches the specified value.</p>
<p>The resourceVersion is currently backed by etcd's modifiedIndex.
However, it's important to note that the application should not rely
on the implementation details of the versioning system maintained by
Kubernetes. We may change the implementation of resourceVersion in the
future, such as to change it to a timestamp or per-object counter.</p>
<p>The only way for a client to know the expected value of
resourceVersion is to have received it from the server in response to
a prior operation, typically a GET. This value MUST be treated as
opaque by clients and passed unmodified back to the server. Clients
should not assume that the resource version has meaning across
namespaces, different kinds of resources, or different servers.
Currently, the value of resourceVersion is set to match etcd's
sequencer. You could think of it as a logical clock the API server can
use to order requests. However, we expect the implementation of
resourceVersion to change in the future, such as in the case we shard
the state by kind and/or namespace, or port to another storage system.</p>
</blockquote>
<p>Since there are chances that this logic can be changed, it's better to follow what kubernetes developers offer since they know further changes better than anyone else do.</p>
<p>Also in API documentation it's said that it's a <code>string</code> type, not <code>integer</code> or <code>date</code>, see <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#objectmeta-v1-meta" rel="nofollow noreferrer">here</a>.</p>
<p>Please find more details <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency" rel="nofollow noreferrer">about Concurrency Control and Consistency</a>.</p>
<hr />
<p><strong>apiVersion</strong></p>
<p>Simple and short answer - because versions are not numeric and sometimes it can be changed very significantly.</p>
<p>Below is a couple of examples that I know/used which will show the difference:</p>
<ul>
<li><p><code>ingress</code>:</p>
<p>used to be - <code>extensions/v1beta1</code></p>
<p>actual version - <code>networking.k8s.io/v1</code></p>
</li>
<li><p><code>istio</code> uses both versions at the moment:</p>
<p><code>networking.istio.io/v1alpha3</code> and <code>networking.istio.io/v1beta1</code></p>
</li>
</ul>
<p>So at this point comparison with <code>></code> or <code><</code> won't work. And much more precise method is to check whether API version is same or not.</p>
|
<p>Revisiting the data locality for Spark on Kubernetes question: if the Spark pods are colocated on the same nodes as the HDFS data node pods then does data locality work ?</p>
<p>The Q&A session here: <a href="https://www.youtube.com/watch?v=5-4X3HylQQo" rel="nofollow noreferrer">https://www.youtube.com/watch?v=5-4X3HylQQo</a> seems to suggest it doesn't.</p>
| <p>Locality is an issue Spark on Kubernetes. Basic Data locality does work if the Kubernetes provider provides a network topology plugins that are required to resolve where the data is and where the spark nodes should be run. <em>and you have built kubernetes to include the <a href="https://github.com/apache-spark-on-k8s/kubernetes-HDFS" rel="nofollow noreferrer">code here</a></em></p>
<p>There is a method to test <a href="https://github.com/apache-spark-on-k8s/kubernetes-HDFS/blob/master/topology/README.md" rel="nofollow noreferrer">this data locality</a>. I have copied it here for completeness:</p>
<p>Here's how one can check if data locality in the namenode works.</p>
<p>Launch a HDFS client pod and go inside the pod.</p>
<pre><code>$ kubectl run -i --tty hadoop --image=uhopper/hadoop:2.7.2
--generator="run-pod/v1" --command -- /bin/bash
</code></pre>
<p>Inside the pod, create a simple text file on HDFS.</p>
<pre><code>$ hadoop fs
-fs hdfs://hdfs-namenode-0.hdfs-namenode.default.svc.cluster.local
-cp file:/etc/hosts /hosts
</code></pre>
<p>Set the number of replicas for the file to the number of your cluster nodes. This ensures that there will be a copy of the file in the cluster node that your client pod is running on. Wait some time until this happens.</p>
<pre><code> `$ hadoop fs -setrep NUM-REPLICAS /hosts`
</code></pre>
<p>Run the following hdfs cat command. From the debug messages, see which datanode is being used. Make sure it is your local datanode. (You can get this from $ kubectl get pods hadoop -o json | grep hostIP. Do this outside the pod)</p>
<pre><code>$ hadoop --loglevel DEBUG fs
-fs hdfs://hdfs-namenode-0.hdfs-namenode.default.svc.cluster.local
-cat /hosts ... 17/04/24 20:51:28 DEBUG hdfs.DFSClient: Connecting to datanode 10.128.0.4:50010 ...
</code></pre>
<p>If no, you should check if your local datanode is even in the list from the debug messsages above. If it is not, then this is because step (3) did not finish yet. Wait more. (You can use a smaller cluster for this test if that is possible)</p>
<pre><code>`17/04/24 20:51:28 DEBUG hdfs.DFSClient: newInfo = LocatedBlocks{ fileLength=199 underConstruction=false blocks=[LocatedBlock{BP-347555225-10.128.0.2-1493066928989:blk_1073741825_1001; getBlockSize()=199; corrupt=false; offset=0; locs=[DatanodeInfoWithStorage[10.128.0.4:50010,DS-d2de9d29-6962-4435-a4b4-aadf4ea67e46,DISK], DatanodeInfoWithStorage[10.128.0.3:50010,DS-0728ffcf-f400-4919-86bf-af0f9af36685,DISK], DatanodeInfoWithStorage[10.128.0.2:50010,DS-3a881114-af08-47de-89cf-37dec051c5c2,DISK]]}] lastLocatedBlock=LocatedBlock{BP-347555225-10.128.0.2-1493066928989:blk_1073741825_1001;`
</code></pre>
<p>Repeat the hdfs cat command multiple times. Check if the same datanode is being consistently used.</p>
|
<p><strong><em>Update</em></strong>
The issue is resolved. </p>
<ol>
<li>I shutdown docker desktop.</li>
<li>Deleted C:\ProgramData\DockerDesktop and .kube folder</li>
<li>Restarted docker desktop</li>
<li>reset docker desktop to factory defaults</li>
<li>and restarted it again and it worked.</li>
</ol>
<p>I have started learning Kubernetes and Dockers yesterday. I installed Docker-Desktop today and my docker container is running. When i check the enable kubernetes option on Docker-Desktop it's not running. It just shows me a loading and below it just shows kubernete starting.<br>
<a href="https://i.stack.imgur.com/eJcyo.png" rel="nofollow noreferrer">Photo of my Docker Desktop</a>
<strong>What i have tried:</strong></p>
<ol>
<li>Uninstalling Docker Desktop and reinstalling it</li>
<li>Reset Kubernetes Cluster</li>
<li>Reset to Factory default</li>
</ol>
<p>I have tried other solutions too which i found here on stackflow like:</p>
<ol>
<li>Running it as an Administrator</li>
<li>Run this on powershell and then try to start kubernetes
<code>[Environment]::SetEnvironmentVariable("KUBECONFIG", $HOME + "\.kube\config", [EnvironmentVariableTarget]::Machine)</code></li>
</ol>
<p>But None of the solutions is trying to fix the problem im having.</p>
<p><strong>Addition Information:</strong></p>
<ol>
<li>Im running Docker Desktop on Windows 10 pro</li>
<li>Docker Version: 2.2.0.5 Kubernetes version: v1.15.5</li>
</ol>
| <h2>Just follow these steps</h2>
<ol>
<li>stop docker for desktop</li>
<li>remove the folder <code>~/Library/Group\ Containers/group.com.docker/pki</code></li>
</ol>
<pre><code> rm -rf ~/Library/Group\ Containers/group.com.docker/pki
</code></pre>
<ol start="3">
<li>start docker for destkop</li>
</ol>
<p>Found <a href="https://github.com/docker/for-mac/issues/3594#issuecomment-621487150" rel="nofollow noreferrer">the solution here</a></p>
<p>And given that every time I try to start "Docker for Desktop" Kubernetes get stuck, to better investigate for me was useful remove the kube autostart from the configuration.</p>
<p>Just edit the file:</p>
<pre><code>~/Library/Group\ Containers/group.com.docker/settings.json
</code></pre>
<p>And change <code>kubernetesEnabled</code> value to <code>false</code></p>
|
<p>I'm looking for a way to quickly run/restart a Job/Pod from the command line and override the command to be executed in the created container.</p>
<p>For context, I have a Kubernetes Job that gets executed as a part of our deploy process. Sometimes that Job crashes and I need to run certain commands <em>inside the container the Job creates</em> to debug and fix the problem (subsequent Jobs then succeed).</p>
<p>The way I have done this so far is:</p>
<ul>
<li>Copy the YAML of the Job, save into a file</li>
<li>Clean up the YAML (delete Kubernetes-managed fields)</li>
<li>Change the <code>command:</code> field to <code>tail -f /dev/null</code> (so that the container stays alive)</li>
<li><code>kubectl apply -f job.yaml && kubectl get all && kubectl exec -ti pod/foobar bash</code></li>
<li>Run commands inside the container</li>
<li><code>kubectl delete job/foobar</code> when I am done</li>
</ul>
<p>This is very tedious. I am looking for a way to do something like the following</p>
<pre><code>kubectl restart job/foobar --command "tail -f /dev/null"
# or even better
kubectl run job/foobar --exec --interactive bash
</code></pre>
<hr />
<p>I cannot use the <code>run</code> command to create a Pod:</p>
<pre class="lang-sh prettyprint-override"><code>kubectl run --image xxx -ti
</code></pre>
<p>because the Job I am trying to restart has certain <code>volumeMounts</code> and other configuration I need to reuse. So I would need something like <code>kubectl run --from-config job/foobar</code>.</p>
<hr />
<p>Is there a way to achieve this or am I stuck with juggling the YAML definition file?</p>
<hr />
<p>Edit: the Job YAML looks approx. like this:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: batch/v1
kind: Job
metadata:
name: database-migrations
labels:
app: myapp
service: myapp-database-migrations
spec:
backoffLimit: 0
template:
metadata:
labels:
app: myapp
service: myapp-database-migrations
spec:
restartPolicy: Never
containers:
- name: migrations
image: registry.example.com/myapp:977b44c9
command:
- "bash"
- "-c"
- |
set -e -E
echo "Running database migrations..."
do-migration-stuff-here
echo "Migrations finished at $(date)"
imagePullPolicy: Always
volumeMounts:
- mountPath: /home/example/myapp/app/config/conf.yml
name: myapp-config-volume
subPath: conf.yml
- mountPath: /home/example/myapp/.env
name: myapp-config-volume
subPath: .env
volumes:
- name: myapp-config-volume
configMap:
name: myapp
imagePullSecrets:
- name: k8s-pull-project
</code></pre>
| <p>The commands you suggested don't exist. Take a look at <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands" rel="noreferrer">this reference</a> where you can find all available commands.</p>
<p>Based on <a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/" rel="noreferrer">that documentation</a> the task of the <a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/" rel="noreferrer"><em>Job</em></a> is to create one or more Pods and continue retrying execution them until the specified number of successfully terminated ones will be achieved. Then the <em>Job</em> tracks the successful completions. You cannot just update the Job because these fields are not updatable. To do what's you want you should delete current job and create one once again.</p>
<hr />
<p>I recommend you to keep all your configurations in files. If you have a problem with configuring job commands, practice says that you should modify these settings in yaml and apply to the cluster - if your deployment crashes - by storing the configuration in files, you have a backup.</p>
<p>If you are interested how to improve this task, you can try those 2 examples describe below:</p>
<p>Firstly I've created several files:</p>
<p>example job (<code>job.yaml</code>):</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: batch/v1
kind: Job
metadata:
name: test1
spec:
template:
spec:
containers:
- name: test1
image: busybox
command: ["/bin/sh", "-c", "sleep 300"]
volumeMounts:
- name: foo
mountPath: "/script/foo"
volumes:
- name: foo
configMap:
name: my-conf
defaultMode: 0755
restartPolicy: OnFailure
</code></pre>
<p><code>patch-file.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>spec:
template:
spec:
containers:
- name: test1
image: busybox
command: ["/bin/sh", "-c", "echo 'patching test' && sleep 500"]
</code></pre>
<p>and <code>configmap.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: ConfigMap
metadata:
name: my-conf
data:
test: |
#!/bin/sh
echo "skrypt test"
</code></pre>
<hr />
<ol>
<li>If you want to automate this process you can use <a href="https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/" rel="noreferrer"><code>plugin</code></a></li>
</ol>
<blockquote>
<p>A plugin is a standalone executable file, whose name begins with <code>kubectl-</code>. To install a plugin, move its executable file to anywhere on your <code>PATH</code>.</p>
<p>There is no plugin installation or pre-loading required. Plugin executables receive the inherited environment from the <code>kubectl</code> binary. A plugin determines which command path it wishes to implement based on its name.</p>
</blockquote>
<p>Here is the file that can replace your job</p>
<blockquote>
<p>A plugin determines the command path that it will implement based on its filename.</p>
</blockquote>
<p><code>kubectl-job</code>:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
kubectl patch -f job.yaml -p "$(cat patch-job.yaml)" --dry-run=client -o yaml | kubectl replace --force -f - && kubectl wait --for=condition=ready pod -l job-name=test1 && kubectl exec -it $(kubectl get pod -l job-name=test1 --no-headers -o custom-columns=":metadata.name") -- /bin/sh
</code></pre>
<p>This command uses an additional file (<code>patch-job.yaml</code>, see this <a href="https://kubernetes.io/docs/tasks/manage-kubernetes-objects/update-api-object-kubectl-patch/" rel="noreferrer">link</a>) - within we can put our changes for <code>job</code>.</p>
<p>Then you should change the permissions of this file and move it:</p>
<pre><code>sudo chmod +x .kubectl-job
sudo mv ./kubectl-job /usr/local/bin
</code></pre>
<p>It's all done. Right now you can use it.</p>
<pre><code>$ kubectl job
job.batch "test1" deleted
job.batch/test1 replaced
pod/test1-bdxtm condition met
pod/test1-nh2pv condition met
/ #
</code></pre>
<p>As you can see <code>Job</code> has been replaced (deleted and created).</p>
<hr />
<ol start="2">
<li>You can also use single-line command, here is the example:</li>
</ol>
<pre><code>kubectl get job test1 -o json | jq "del(.spec.selector)" | jq "del(.spec.template.metadata.labels)" | kubectl patch -f - --patch '{"spec": {"template": {"spec": {"containers": [{"name": "test1", "image": "busybox", "command": ["/bin/sh", "-c", "sleep 200"]}]}}}}' --dry-run=client -o yaml | kubectl replace --force -f -
</code></pre>
<p>With this command you can change your job entering parameters "by hand". Here is the output:</p>
<pre><code>job.batch "test1" deleted
job.batch/test1 replaced
</code></pre>
<p>As you can see this solution works as well.</p>
|
<p>I am using Istio 1.10.0 with minikube. Kubernetes server version is 1.19.8.</p>
<p>How to add multiple headers in http request? Is it possible to place dynamic values like <code>request.headers["Host"]</code>?</p>
<pre><code>X-Forwarded-Host $host;
X-Forwarded-Port 9090;
X-Forwarded-Proto http;
</code></pre>
<p>Below sample is working fine for adding response header.</p>
<pre><code>apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
annotations:
helm.sh/hook: pre-install, pre-upgrade
creationTimestamp: "2021-11-22T13:01:36Z"
generation: 8
name: direct-vs
namespace: cvrm
resourceVersion: "72069"
selfLink: /apis/networking.istio.io/v1beta1/namespaces/cvrm/virtualservices/cvrm-direct-vs
uid: d398a13e-fd81-4ada-8e36-617287cae1bc
spec:
gateways:
- gateway.istio-system.svc.cluster.local
hosts:
- '*'
http:
- match:
- uri:
prefix: /console
route:
- destination:
host: console-bs.cvrm.svc.cluster.local
port:
number: 8087
headers:
response:
add:
Custom-Header: test
</code></pre>
| <p>You add headers to requests the same way you did with response.</p>
<pre class="lang-yaml prettyprint-override"><code>...
headers:
request:
add:
foo: bar
...
</code></pre>
<p>If you want to add multiple headers added you can try</p>
<pre class="lang-yaml prettyprint-override"><code>...
headers:
request:
add:
foo: foo
bar: bar
...
</code></pre>
<p>It's not possible to add dynamic values in Istio manifests.</p>
|
<p>My application is running within a pod container in a kubernetes cluster. Every time it is started in the container it allocates a random port. I would like to access my application from outside (from another pod or node for example) but since it allocates a random port I cannot create a serivce (NodePort or LoadBalancer) to map the application port to a specific port to be able to access it.</p>
<p>What are the options to handle this case in a kubernetes cluster?</p>
| <p>Not supported, checkout the issue <a href="https://github.com/kubernetes/enhancements/pull/2611" rel="nofollow noreferrer">here</a>. Even with docker, if your range is overly broad, you can hit <a href="https://github.com/moby/moby/issues/11185" rel="nofollow noreferrer">issue</a> as well.</p>
|
<p>I'd like to retrieve all of the ingresses that act on a Kubernetes service.</p>
<p>I can get the ingresses in a namespace with the command <code>kubectl get ingress -n <namespace></code>.</p>
<p>Is there a command in kubectl that lets me fetch the ingresses that act on a specific Kubernetes service?</p>
| <p>To get all ingress rules in the cluster, you can run:</p>
<pre><code>kubectl get ingress -A
</code></pre>
<p>To get a summary of all ingress rules (including their used services), you can run this:</p>
<pre><code>kubectl describe ingress -A
</code></pre>
<p>To get the full ingress objects but in json format, you can run this:</p>
<pre><code>kubectl get ingress -A -o json
</code></pre>
<p>You could then parse that json to get the used services.</p>
|
<p>I'm trying to deploy an Application Load Balancer to AWS using Terraform's <code>kubernetes_ingress</code> resource:</p>
<p>I'm using <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.3/" rel="nofollow noreferrer">aws-load-balancer-controller</a> which I've installed using <code>helm_release</code> resource to my cluster.</p>
<p>Now I'm trying to deploy a <code>deployment</code> with a <code>service</code> and <code>ingress</code>.</p>
<p>This is how my <code>service</code> looks like:</p>
<pre><code>resource "kubernetes_service" "questo-server-service" {
metadata {
name = "questo-server-service-${var.env}"
namespace = kubernetes_namespace.app-namespace.metadata.0.name
}
spec {
selector = {
"app.kubernetes.io/name" = lookup(kubernetes_deployment.questo-server.metadata.0.labels, "app.kubernetes.io/name")
}
port {
port = 80
target_port = 4000
}
type = "LoadBalancer"
}
}
</code></pre>
<p>And this is how my <code>ingress</code> looks like:</p>
<pre><code>resource "kubernetes_ingress" "questo-server-ingress" {
wait_for_load_balancer = true
metadata {
name = "questo-server-ingress-${var.env}"
namespace = kubernetes_namespace.app-namespace.metadata.0.name
annotations = {
"kubernetes.io/ingress.class" = "alb"
"alb.ingress.kubernetes.io/target-type" = "instance"
}
}
spec {
rule {
http {
path {
path = "/*"
backend {
service_name = kubernetes_service.questo-server-service.metadata.0.name
service_port = 80
}
}
}
}
}
}
</code></pre>
<p>The issue is that when I run <code>terraform apply</code> it creates a Classic Load Balancer instead of an Application Load Balancer.</p>
<p>I've tried changing <code>service</code>'s type to <code>NodePort</code> but it didn't help.</p>
<p>I've also tried with adding more annotations to <code>ingress</code> like <code>"alb.ingress.kubernetes.io/load-balancer-name" = "${name}"</code> but then the it created two load balancers at once! One internal ALB and one internet facing CLB.</p>
<p>Any ideas how I can create an internet facing Application Load Balancer using this setup?</p>
<p>--- Update ----</p>
<p>I've noticed, that actually, the <code>service</code> is the Classic Load Balancer via which I can connect to my <code>deployment</code>.</p>
<p>Ingress creates an ALB, but it's prefixed with <code>internal</code>, so my questions here is, how to create an internet facing ALB?</p>
<p>Thanks!</p>
| <p>Answering my own question, like most of the times :)</p>
<p>This is the proper setup, just in case someone come across it:</p>
<p>The <code>service</code>'s type has to be <code>NodePort</code>:</p>
<pre><code>resource "kubernetes_service" "questo-server-service" {
metadata {
name = "questo-server-service-${var.env}"
namespace = kubernetes_namespace.app-namespace.metadata.0.name
}
spec {
selector = {
"app.kubernetes.io/name" = lookup(kubernetes_deployment.questo-server.metadata.0.labels, "app.kubernetes.io/name")
}
port {
port = 80
target_port = 4000
}
type = "NodePort"
}
}
</code></pre>
<p>And <code>ingress</code>'s annotation has to be set as follows: (you can ingnore <code>load-balancer-name</code> and <code>healthcheck-pass</code> as they are not relevant to the question:</p>
<pre><code>resource "kubernetes_ingress" "questo-server-ingress" {
wait_for_load_balancer = true
metadata {
name = "questo-server-ingress-${var.env}"
namespace = kubernetes_namespace.app-namespace.metadata.0.name
annotations = {
"kubernetes.io/ingress.class" = "alb"
"alb.ingress.kubernetes.io/target-type" = "ip"
"alb.ingress.kubernetes.io/scheme" = "internet-facing"
"alb.ingress.kubernetes.io/load-balancer-name" = "questo-server-alb-${var.env}"
"alb.ingress.kubernetes.io/healthcheck-path" = "/health"
}
}
spec {
rule {
http {
path {
path = "/*"
backend {
service_name = kubernetes_service.questo-server-service.metadata.0.name
service_port = 80
}
}
}
}
}
}
</code></pre>
|
<p>I have a scenario like below,
Have two releases - Release-A and Release-B.</p>
<p>Currently, I am on Release-A and need an upgrade of all the microservices to Release-B.
I tried performing the helm upgrade of microservice - "mymicroservice" with the below command to deliver Release-B.</p>
<pre><code>helm --kubeconfig /home/config upgrade --namespace testing --install --wait mymicroservice mymicroservice-release-b.tgz
</code></pre>
<p>Because of some issue, the deployment object got failed to install and went into an error state.</p>
<p>Observing this, I perform the below rollback command.</p>
<pre><code>helm --kubeconfig /home/config --namespace testing rollback mymicroservice
</code></pre>
<p>Due to some issue(may be an intermittent system failure or user behavior), the Release-A's deployment object also went into failed/Crashloopbackoff state.Although this will result in helm rollback success, the deployment object is still not entered the running state.</p>
<p>Once I made the necessary corrections, I will retry the rollback. As the deployment spec is already updated with helm, it never attempts to re-install the deployment objects even if it is in the failed state.</p>
<p>Is there any option with Helm to handle the above scenarios ?.</p>
<p>Tried with <code>--force</code> flag, but there are other errors related to Service object replace in the microservice when used the --force flag approach.</p>
<pre><code>Rollback "mymicroservice -monitoring" failed: failed to replace object: Service "mymicroservice-monitoring" is invalid: spec.clusterIP: Invalid value: "": field is immutable
</code></pre>
| <p>Maybe this can help u out:</p>
<ul>
<li>Always use the helm <strong>upgrade --install</strong> command. I've seen you're using so you're doing well. This installs the charts if they're not present and upgrades them if they're present.</li>
<li>Use --atomic flag to rollback changes in the event of a failed operation during helm upgrade.</li>
<li>And the flag --cleanup-on-fail: It allows that Helm deletes newly created resources during a rollback in case the rollback fails.</li>
</ul>
<p>From doc:</p>
<p>--atomic: if set, upgrade process rolls back changes made in case of failed upgrade. The --wait flag will be set automatically if --atomic is used</p>
<p>--cleanup-on-fail allow deletion of new resources created in this upgrade when upgrade fails</p>
<p>There are cases where an upgrade creates a resource that was not present in the last release. Setting this flag allows Helm to remove those new resources if the release fails. The default is to not remove them (Helm tends to avoid destruction-as-default, and give users explicit control over this)</p>
<p><a href="https://helm.sh/docs/helm/helm_upgrade/" rel="noreferrer">https://helm.sh/docs/helm/helm_upgrade/</a></p>
|
<p>I'm trying to deploy an Application Load Balancer to AWS using Terraform's <code>kubernetes_ingress</code> resource:</p>
<p>I'm using <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.3/" rel="nofollow noreferrer">aws-load-balancer-controller</a> which I've installed using <code>helm_release</code> resource to my cluster.</p>
<p>Now I'm trying to deploy a <code>deployment</code> with a <code>service</code> and <code>ingress</code>.</p>
<p>This is how my <code>service</code> looks like:</p>
<pre><code>resource "kubernetes_service" "questo-server-service" {
metadata {
name = "questo-server-service-${var.env}"
namespace = kubernetes_namespace.app-namespace.metadata.0.name
}
spec {
selector = {
"app.kubernetes.io/name" = lookup(kubernetes_deployment.questo-server.metadata.0.labels, "app.kubernetes.io/name")
}
port {
port = 80
target_port = 4000
}
type = "LoadBalancer"
}
}
</code></pre>
<p>And this is how my <code>ingress</code> looks like:</p>
<pre><code>resource "kubernetes_ingress" "questo-server-ingress" {
wait_for_load_balancer = true
metadata {
name = "questo-server-ingress-${var.env}"
namespace = kubernetes_namespace.app-namespace.metadata.0.name
annotations = {
"kubernetes.io/ingress.class" = "alb"
"alb.ingress.kubernetes.io/target-type" = "instance"
}
}
spec {
rule {
http {
path {
path = "/*"
backend {
service_name = kubernetes_service.questo-server-service.metadata.0.name
service_port = 80
}
}
}
}
}
}
</code></pre>
<p>The issue is that when I run <code>terraform apply</code> it creates a Classic Load Balancer instead of an Application Load Balancer.</p>
<p>I've tried changing <code>service</code>'s type to <code>NodePort</code> but it didn't help.</p>
<p>I've also tried with adding more annotations to <code>ingress</code> like <code>"alb.ingress.kubernetes.io/load-balancer-name" = "${name}"</code> but then the it created two load balancers at once! One internal ALB and one internet facing CLB.</p>
<p>Any ideas how I can create an internet facing Application Load Balancer using this setup?</p>
<p>--- Update ----</p>
<p>I've noticed, that actually, the <code>service</code> is the Classic Load Balancer via which I can connect to my <code>deployment</code>.</p>
<p>Ingress creates an ALB, but it's prefixed with <code>internal</code>, so my questions here is, how to create an internet facing ALB?</p>
<p>Thanks!</p>
| <p>Try using the <code>alb.ingress.kubernetes.io/scheme: internet-facing</code> annotation.</p>
<p>You find a list of all available annotations here: <a href="https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.2/guide/ingress/annotations/" rel="nofollow noreferrer">https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.2/guide/ingress/annotations/</a></p>
|
<p>command below gives an error: <code>error: flag key is required</code></p>
<pre><code>kubectl create secret tls k8-secret2 \
-n ingress-tls-test1 \
--cert ingress-tls-test1.pfx
</code></pre>
<p>I am able to create the secret using .crt and .key file:</p>
<pre><code>kubectl create secret tls aks-ingress-tls \
--namespace ingress-basic \
--key aks-ingress-tls.key \
--cert aks-ingress-tls.crt
</code></pre>
| <p>I needed to create a kube tls secret from .pfx file today
Credits to: <a href="https://adolfi.dev/blog/tls-kubernetes/" rel="noreferrer">https://adolfi.dev/blog/tls-kubernetes/</a></p>
<pre class="lang-bash prettyprint-override"><code>## you will enter the pfx PW on on the CMD/terminal
openssl pkcs12 -in pfx-filename.pfx -nocerts -out key-filename.key
openssl rsa -in key-filename.key -out key-filename-decrypted.key
openssl pkcs12 -in pfx-filename.pfx -clcerts -nokeys -out crt-filename.crt ##remove clcerts to get the full chain in your cert
kubectl create secret tls your-secret-name --cert crt-filename.crt --key key-filename-decrypted.key
</code></pre>
|
<p>I am in the learning phase of Kubernetes and want to set up the CI/Cd pipeline for my project. I am using google cloud and have the following elements are ready</p>
<ol>
<li>3 Node cluster is deployed on google cloud</li>
<li>Github has been integrated with google cloud build to trigger the build.</li>
<li>I am using <code>helm</code> to maintain my K8s templates.</li>
<li><code>cloudbuilld.yaml</code> is developed to compile the docker image and push it to google container registry.</li>
</ol>
<p>I am stuck at - Once my cloudbuild.yaml is done with building the docker image and pushed it to the registry, how do I use helm to upgrade the chart?</p>
<p>Here is my sample <code>cloudbuild.yaml</code></p>
<pre><code>steps:
- name: 'gcr.io/cloud-builders/docker'
args: ["build", "-t", "gcr.io/kubernetes-amit-test/github.com/0xvoila/apache/phoenix:$SHORT_SHA", "."]
- name: "gcr.io/cloud-builders/docker"
args: ["push", "gcr.io/kubernetes-amit-test/github.com/0xvoila/apache/phoenix:$SHORT_SHA"]
- name: "alpine/helm:latest". --- It is not working
args: ["helm","upgrade","mychart","image", "gcr.io/kubernetes-amit-test/github.com/0xvoila/apache/phoenix:$SHORT_SHA"]
</code></pre>
<p>My Question is</p>
<ol>
<li>How can I use helm to upgrade the latest charts.</li>
<li>As I am new to Kubernetes, it is even the best practice for K8s deployment? Do people even use helm?</li>
</ol>
| <blockquote>
<p>How can I use helm to upgrade the latest charts.</p>
</blockquote>
<p>There is already default helm exist : <strong>gcr.io/$PROJECT_ID/cloud-builders-helm</strong></p>
<pre><code>- name: 'gcr.io/$PROJECT_ID/cloud-builders-helm'
args: ['upgrade', '--install', 'filebeat', '--namespace', 'filebeat', 'stable/filebeat']
</code></pre>
<p>For managing chart version you should check the : <a href="https://cloud.google.com/artifact-registry/docs/helm/manage-charts" rel="noreferrer">https://cloud.google.com/artifact-registry/docs/helm/manage-charts</a></p>
<p>Helm cloud builder <a href="https://github.com/GoogleCloudPlatform/cloud-builders-community/tree/master/helm" rel="noreferrer">Github</a></p>
<blockquote>
<p>As I am new to Kubernetes, it is even the best practice for K8s
deployment? Do people even use helm?</p>
</blockquote>
<p>Helm is the best way to manage it instead of using any other.</p>
<p>i would suggest checking out the <code>helm atomic</code></p>
<pre><code>helm upgrade --install --atomic
</code></pre>
<p>which will also auto rollback deployment if it's failing in K8s.</p>
<blockquote>
<p>--atomic if set, upgrade process rolls back changes made in case of failed upgrade. The --wait flag will be set
automatically if --atomic is used</p>
</blockquote>
<p><a href="https://helm.sh/docs/helm/helm_upgrade/" rel="noreferrer">Read more</a></p>
<p><strong>Extra :</strong></p>
<p>Instead of fixing the GCR name, you can also use variables this template will work across the <strong>branches</strong> of across repo also.</p>
<pre><code>- id: 'build test core image'
name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA', '.']
- id: 'push test core image'
name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA']
</code></pre>
<p><strong>Update :</strong></p>
<p>Adding GKE cluster details to Cloud build</p>
<pre><code>- name: 'gcr.io/cloud-builders/kubectl'
args: ['apply', '-f', 'deployment.yaml']
env:
- 'CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}'
- 'CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}'
</code></pre>
<p>i am using the <strong>kubectl</strong> <strong>apply</strong> but you can add these <strong>environment</strong> <strong>variables</strong> to your <strong>helm</strong> step.</p>
<p><a href="https://github.com/harsh4870/basic-ci-cd-cloudbuild/blob/main/cloudbuild-deployment.yaml" rel="noreferrer">File location</a></p>
<p><strong>Full file</strong></p>
<pre><code>substitutions:
_CLOUDSDK_COMPUTE_ZONE: us-central1-c # default value
_CLOUDSDK_CONTAINER_CLUSTER: standard-cluster-1 # default value
steps:
- id: 'set test core image in yamls'
name: 'ubuntu'
args: ['bash','-c','sed -i "s,TEST_IMAGE_NAME,gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA," deployment.yaml']
- name: 'gcr.io/cloud-builders/kubectl'
args: ['apply', '-f', 'deployment.yaml']
env:
- 'CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}'
- 'CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}'
</code></pre>
|
<p>I'm working with prometheus to scrape k8s service metrics.</p>
<p>I created a service monitor for my service as below :</p>
<pre><code>apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: scmpoll-service-monitor-{{ .Release.Name }}
namespace: {{ .Release.Namespace }}
labels:
app: scmpoll-{{ template "jenkins-exporter.name" . }}
chart: {{ template "jenkins-exporter.chart" . }}
release: {{ .Release.Name }}
heritage: {{ .Release.Service }}
spec:
namespaceSelector:
matchNames:
- {{ .Release.Namespace }}
selector:
matchLabels:
app: scmpoll-{{ template "jenkins-exporter.name" . }}
chart: {{ template "jenkins-exporter.chart" . }}
release: {{ .Release.Name }}
endpoints:
- interval: 1440m
targetPort: 9759
path: /metrics
port: http
</code></pre>
<p>I set interval: 1440m because I want prometheus to scrape data once a day.</p>
<p>After deploying the chart, the service monitor was added to prometheus targets but with status unknown and scrape duration 0s. The screenshot below:</p>
<p><a href="https://i.stack.imgur.com/JBXzy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBXzy.png" alt="enter image description here" /></a></p>
<p>Also I have the service monitor added to prometheus config:</p>
<pre><code>- job_name: monitoring/scmpoll-service-monitor-my-release/0
honor_timestamps: true
scrape_interval: 1d
scrape_timeout: 10s
metrics_path: /metrics
scheme: http
</code></pre>
<p>I can see that scrape-intervel is set to 1d (24h) but the state is unknown in the screenshot above. Do I have to wait for the next 24h and check or does this mean the configuration is wrong?</p>
<p>Test : i made test with scrape 20minutes and it was the same thing : status unknow with no metrics until the 20 minutes passed and status became UP and metrics were scraped.</p>
<p>I'm not working on prometheus-operator chart, it's an independent chart.</p>
| <p>It's not recommended to use Prometheus for such long <code>scrape_interval</code>. 2 minutes is suggested by many. Read this for details- <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/#staleness" rel="nofollow noreferrer">Staleness</a>.</p>
<p>If you want to scrape data with interval exceeding 2 minutes, you can use <a href="https://github.com/VictoriaMetrics/VictoriaMetrics/" rel="nofollow noreferrer">VictoriaMetrics</a>. It supports time series with arbitrary long scrape intervals.</p>
|
<h2><strong>Edited with new data after complete Kubernetes wipe-out.</strong></h2>
<p>Lately I am trying to do a test deploy of a Blazor server app on locally hosted Kubernetes instance running on docker desktop.</p>
<p>I managed to correctly spin up the app in a container, migrations were applied etc, logs are telling me that the app is running and waiting.</p>
<p><strong>Steps taken after resetting Kubernetes using <code>Reset Kubernetes Kluster</code> in Docker Desktop:</strong></p>
<ul>
<li><p>Modified <code>hosts</code> file to include <code>127.0.0.1 scp.com</code></p>
</li>
<li><p>Added secret containing key to mssql</p>
</li>
<li><p>Installed Ngnix controller using <code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.0/deploy/static/provider/cloud/deploy.yaml</code></p>
</li>
<li><p>Applied local volume claim - <code>local-pvc.yaml</code></p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mssql-claim
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 250Mi
</code></pre>
</li>
<li><p>Applied mssql instance and cluster ip - <code>mssql-scanapp-depl.yaml</code></p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: mssql-depl
spec:
replicas: 1
selector:
matchLabels:
app: mssql
template:
metadata:
labels:
app: mssql
spec:
containers:
- name: mssql
image: mcr.microsoft.com/mssql/server:2019-latest
ports:
- containerPort: 1433
env:
- name: MSSQL_PID
value: "Express"
- name: ACCEPT_EULA
value: "Y"
- name: SA_PASSWORD
valueFrom:
secretKeyRef:
name: mssql
key: SA_PASSWORD
volumeMounts:
- mountPath: /var/opt/mssql/data
name: mssqldb
volumes:
- name: mssqldb
persistentVolumeClaim:
claimName: mssql-claim
---
apiVersion: v1
kind: Service
metadata:
name: mssql-clusterip-srv
spec:
type: ClusterIP
selector:
app: mssql
ports:
- name: mssql
protocol: TCP
port: 1433
targetPort: 1433
---
apiVersion: v1
kind: Service
metadata:
name: mssql-loadbalancer
spec:
type: LoadBalancer
selector:
app: mssql
ports:
- protocol: TCP
port: 1433
targetPort: 1433
</code></pre>
</li>
<li><p>Applied Blazor application and cluster ip - <code>scanapp-depl.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: scanapp-depl
spec:
replicas: 1
selector:
matchLabels:
app: scanapp
template:
metadata:
labels:
app: scanapp
spec:
containers:
- name: scanapp
image: scanapp:1.0
---
apiVersion: v1
kind: Service
metadata:
name: scanapp-clusterip-srv
spec:
type: ClusterIP
selector:
app: scanapp
ports:
- name: ui
protocol: TCP
port: 8080
targetPort: 80
- name: ui2
protocol: TCP
port: 8081
targetPort: 443
- name: scanapp0
protocol: TCP
port: 5000
targetPort: 5000
- name: scanapp1
protocol: TCP
port: 5001
targetPort: 5001
- name: scanapp5
protocol: TCP
port: 5005
targetPort: 5005
</code></pre>
</li>
<li><p>Applied Ingress - <code>ingress-srv.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-srv
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/affinity: "cookie"
nginx.ingress.kubernetes.io/session-cookie-name: "affinity"
nginx.ingress.kubernetes.io/session-cookie-expires: "14400"
nginx.ingress.kubernetes.io/session-cookie-max-age: "14400"
spec:
ingressClassName: nginx
rules:
- host: scp.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: scanapp-clusterip-srv
port:
number: 8080
</code></pre>
</li>
</ul>
<p>After all of this, Blazor app starts good, connects to mssql instance, seeds database and awaits for clients. Logs are as follows:</p>
<blockquote>
<p>[15:18:53 INF] Starting up...<br />
[15:18:53 WRN] Storing keys in a directory '/root/.aspnet
/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.<br />
[15:18:55 INF] AuthorizationPolicy Configuration started ...<br />
[15:18:55 INF] Policy 'LocationMustBeSady' was configured \successfully.
[15:18:55 INF] AuthorizationPolicy Configuration completed.
[15:18:55 INF] Now listening on: http://[::]:80
[15:18:55 INF] Application started. Press Ctrl+C to shut down.
[15:18:55 INF] Hosting environment: docker
[15:18:55 INF] Content root path: /app</p>
</blockquote>
<h1><strong>As stated in the beginning - I cannot, for the love of all, get into my blazor app from browser - I tried:</strong></h1>
<ul>
<li>scp.com</li>
<li>scp.com:8080</li>
<li>scp.com:5000</li>
<li>scp.com:5001</li>
<li>scp.com:5005</li>
</ul>
<p><strong>Also, <code>kubectl get ingress</code> now does not display ADDRESS value like before and <code>kubectl get services</code> now says <em>pending</em> for <code>mssql-loadbalancer</code> and <code>ingress-nginx-controller</code> EXTERNAL-IP - detailed logs at the end of this post</strong></p>
<p>Nothing seems to work, so there must be something wrong with my config files and I have no idea what could it be.
Also, note that there is no <code>NodePort</code> configured this time.</p>
<p>In addition, Dockerfile for Blazor app:</p>
<pre class="lang-yaml prettyprint-override"><code> # https://hub.docker.com/_/microsoft-dotnet
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /source
EXPOSE 5000
EXPOSE 5001
EXPOSE 5005
EXPOSE 80
EXPOSE 443
LABEL name="ScanApp"
# copy csproj and restore as distinct layers
COPY ScanApp/*.csproj ScanApp/
COPY ScanApp.Application/*.csproj ScanApp.Application/
COPY ScanApp.Common/*.csproj ScanApp.Common/
COPY ScanApp.Domain/*.csproj ScanApp.Domain/
COPY ScanApp.Infrastructure/*.csproj ScanApp.Infrastructure/
COPY ScanApp.Tests/*.csproj ScanApp.Tests/
Run ln -sf /usr/share/zoneinfo/posix/Europe/Warsaw /etc/localtime
RUN dotnet restore ScanApp/ScanApp.csproj
# copy and build app and libraries
COPY ScanApp/ ScanApp/
COPY ScanApp.Application/ ScanApp.Application/
COPY ScanApp.Common/ ScanApp.Common/
COPY ScanApp.Domain/ ScanApp.Domain/
COPY ScanApp.Infrastructure/ ScanApp.Infrastructure/
COPY ScanApp.Tests/ ScanApp.Tests/
WORKDIR /source/ScanApp
RUN dotnet build -c release --no-restore
# test stage -- exposes optional entrypoint
# target entrypoint with: docker build --target test
FROM build AS test
WORKDIR /source/ScanApp.Tests
COPY tests/ .
ENTRYPOINT ["dotnet", "test", "--logger:trx"]
FROM build AS publish
RUN dotnet publish -c release --no-build -o /app
# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish /app .
ENV ASPNETCORE_ENVIRONMENT="docker"
ENTRYPOINT ["dotnet", "ScanApp.dll"]
</code></pre>
<h2><strong>kubectl outputs</strong></h2>
<p><code>kubectl get ingress</code> output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>NAME</th>
<th>CLASS</th>
<th>HOSTS</th>
<th>ADDRESS</th>
<th>PORTS</th>
<th>AGE</th>
</tr>
</thead>
<tbody>
<tr>
<td>ingress-srv</td>
<td>nginx</td>
<td>scp.com</td>
<td></td>
<td>80</td>
<td>35m</td>
</tr>
</tbody>
</table>
</div>
<p><br />
<br />
<code>kubectl get pods --all-namespaces</code> output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;"><strong>NAME</strong></th>
<th style="text-align: center;"><strong>READY</strong></th>
<th style="text-align: center;"><strong>STATUS</strong></th>
<th style="text-align: center;"><strong>RESTARTS</strong></th>
<th style="text-align: center;"><strong>AGE</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">mssql-depl-7f46b5c696-7hhbr</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">scanapp-depl-76f56bc6df-4jcq4</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">ingress-nginx</td>
<td style="text-align: center;">ingress-nginx-admission-create-qdnck</td>
<td style="text-align: center;">0/1</td>
<td style="text-align: center;">Completed</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">ingress-nginx</td>
<td style="text-align: center;">ingress-nginx-admission-patch-chxqn</td>
<td style="text-align: center;">0/1</td>
<td style="text-align: center;">Completed</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">ingress-nginx</td>
<td style="text-align: center;">ingress-nginx-controller-54bfb9bb-f6gsf</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">coredns-558bd4d5db-mr8p7</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">coredns-558bd4d5db-rdw2d</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">etcd-docker-desktop</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">kube-apiserver-docker-desktop</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">kube-controller-manager-docker-desktop</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">kube-proxy-pws8f</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">kube-scheduler-docker-desktop</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">storage-provisioner</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">vpnkit-controller</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">Running</td>
<td style="text-align: center;">6</td>
</tr>
</tbody>
</table>
</div>
<p><br />
<br />
<code>kubectl get deployments --all-namespaces</code> output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;"><strong>NAME</strong></th>
<th style="text-align: center;"><strong>READY</strong></th>
<th style="text-align: center;"><strong>UP-TO-DATE</strong></th>
<th style="text-align: center;"><strong>AVAILABLE</strong></th>
<th style="text-align: center;"><strong>AGE</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">mssql-depl</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">scanapp-depl</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">ingress-nginx</td>
<td style="text-align: center;">ingress-nginx-controller</td>
<td style="text-align: center;">1/1</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">coredns</td>
<td style="text-align: center;">2/2</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">2</td>
</tr>
</tbody>
</table>
</div>
<p><br />
<br />
<code>kubectl get services --all-namespaces</code> output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;"><strong>NAME</strong></th>
<th style="text-align: center;"><strong>TYPE</strong></th>
<th style="text-align: center;"><strong>CLUSTER-IP</strong></th>
<th style="text-align: center;"><strong>EXTERNAL-IP</strong></th>
<th style="text-align: center;"><strong>PORT(S)</strong></th>
<th style="text-align: center;"><strong>AGE</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">kubernetes</td>
<td style="text-align: center;">ClusterIP</td>
<td style="text-align: center;">10.96.0.1</td>
<td style="text-align: center;">none</td>
<td style="text-align: center;">443/TCP</td>
</tr>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">mssql-clusterip-srv</td>
<td style="text-align: center;">ClusterIP</td>
<td style="text-align: center;">10.97.96.94</td>
<td style="text-align: center;">none</td>
<td style="text-align: center;">1433/TCP</td>
</tr>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">mssql-loadbalancer</td>
<td style="text-align: center;">LoadBalancer</td>
<td style="text-align: center;">10.107.235.49</td>
<td style="text-align: center;">pending</td>
<td style="text-align: center;">1433:30149/TCP</td>
</tr>
<tr>
<td style="text-align: center;">default</td>
<td style="text-align: center;">scanapp-clusterip-srv</td>
<td style="text-align: center;">ClusterIP</td>
<td style="text-align: center;">10.109.116.183</td>
<td style="text-align: center;">none</td>
<td style="text-align: center;">8080/TCP,8081/TCP,5000/TCP,5001/TCP,5005/TCP</td>
</tr>
<tr>
<td style="text-align: center;">ingress-nginx</td>
<td style="text-align: center;">ingress-nginx-controller</td>
<td style="text-align: center;">LoadBalancer</td>
<td style="text-align: center;">10.103.89.226</td>
<td style="text-align: center;">pending</td>
<td style="text-align: center;">80:30562/TCP,443:31733/TCP</td>
</tr>
<tr>
<td style="text-align: center;">ingress-nginx</td>
<td style="text-align: center;">ingress-nginx-controller-admission</td>
<td style="text-align: center;">ClusterIP</td>
<td style="text-align: center;">10.111.235.243</td>
<td style="text-align: center;">none</td>
<td style="text-align: center;">443/TCP</td>
</tr>
<tr>
<td style="text-align: center;">kube-system</td>
<td style="text-align: center;">kube-dns</td>
<td style="text-align: center;">ClusterIP</td>
<td style="text-align: center;">10.96.0.10</td>
<td style="text-align: center;">none</td>
<td style="text-align: center;">53/UDP,53/TCP,9153/TCP</td>
</tr>
</tbody>
</table>
</div><h2>Ingress logs:</h2>
<blockquote>
<hr />
<p>NGINX Ingress controller</p>
<p>Release: v1.1.0</p>
<p>Build: cacbee86b6ccc45bde8ffc184521bed3022e7dee</p>
<p>Repository: <a href="https://github.com/kubernetes/ingress-nginx" rel="nofollow noreferrer">https://github.com/kubernetes/ingress-nginx</a></p>
<p>nginx version: nginx/1.19.9</p>
<hr />
<p>W1129 15:00:51.705331 8 client_config.go:615] Neither
--kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.</p>
<p>I1129 15:00:51.705452 8 main.go:223] "Creating API client"
host="https://10.96.0.1:443"</p>
<p>I1129 15:00:51.721575 8 main.go:267] "Running in Kubernetes
cluster" major="1" minor="21" git="v1.21.5" state="clean"
commit="aea7bbadd2fc0cd689de94a54e5b7b758869d691"
platform="linux/amd64"</p>
<p>I1129 15:00:51.872964 8 main.go:104] "SSL fake certificate
created"
file="/etc/ingress-controller/ssl/default-fake-certificate.pem"</p>
<p>I1129 15:00:51.890273 8 ssl.go:531] "loading tls certificate"
path="/usr/local/certificates/cert" key="/usr/local/certificates/key"</p>
<p>I1129 15:00:51.910104 8 nginx.go:255] "Starting NGINX Ingress
controller"</p>
<p>I1129 15:00:51.920821 8 event.go:282]
Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx",
Name:"ingress-nginx-controller",
UID:"51060a85-d3a0-40de-b549-cf59e8fa7b08", APIVersion:"v1",
ResourceVersion:"733", FieldPath:""}): type: 'Normal' reason: 'CREATE'
ConfigMap ingress-nginx/ingress-nginx-controller</p>
<p>I1129 15:00:53.112043 8 nginx.go:297] "Starting NGINX process"</p>
<p>I1129 15:00:53.112213 8 leaderelection.go:248] attempting to
acquire leader lease ingress-nginx/ingress-controller-leader...</p>
<p>I1129 15:00:53.112275 8 nginx.go:317] "Starting validation
webhook" address=":8443" certPath="/usr/local/certificates/cert"
keyPath="/usr/local/certificates/key"</p>
<p>I1129 15:00:53.112468 8 controller.go:155] "Configuration
changes detected, backend reload required"</p>
<p>I1129 15:00:53.118295 8 leaderelection.go:258] successfully
acquired lease ingress-nginx/ingress-controller-leader</p>
<p>I1129 15:00:53.119467 8 status.go:84] "New leader elected"
identity="ingress-nginx-controller-54bfb9bb-f6gsf"</p>
<p>I1129 15:00:53.141609 8 controller.go:172] "Backend successfully
reloaded"</p>
<p>I1129 15:00:53.141804 8 controller.go:183] "Initial sync,
sleeping for 1 second"</p>
<p>I1129 15:00:53.141908 8 event.go:282]
Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx",
Name:"ingress-nginx-controller-54bfb9bb-f6gsf",
UID:"54e0c0c6-40ea-439e-b1a2-7787f1b37e7a", APIVersion:"v1",
ResourceVersion:"766", FieldPath:""}): type: 'Normal' reason: 'RELOAD'
NGINX reload triggered due to a change in configuration</p>
<p>I1129 15:04:25.107359 8 admission.go:149] processed ingress via
admission controller {testedIngressLength:1 testedIngressTime:0.022s
renderingIngressLength:1 renderingIngressTime:0s admissionTime:17.9kBs
testedConfigurationSize:0.022}</p>
<p>I1129 15:04:25.107395 8 main.go:101] "successfully validated
configuration, accepting" ingress="ingress-srv/default"</p>
<p>I1129 15:04:25.110109 8 store.go:424] "Found valid IngressClass"
ingress="default/ingress-srv" ingressclass="nginx"</p>
<p>I1129 15:04:25.110698 8 controller.go:155] "Configuration
changes detected, backend reload required"</p>
<p>I1129 15:04:25.111057 8 event.go:282]
Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default",
Name:"ingress-srv", UID:"6c15d014-ac14-404e-8b5e-d8526736c52a",
APIVersion:"networking.k8s.io/v1", ResourceVersion:"1198",
FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync</p>
<p>I1129 15:04:25.143417 8 controller.go:172] "Backend successfully
reloaded"</p>
<p>I1129 15:04:25.143767 8 event.go:282]
Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx",
Name:"ingress-nginx-controller-54bfb9bb-f6gsf",
UID:"54e0c0c6-40ea-439e-b1a2-7787f1b37e7a", APIVersion:"v1",
ResourceVersion:"766", FieldPath:""}): type: 'Normal' reason: 'RELOAD'
NGINX reload triggered due to a change in configuration</p>
<p>I1129 15:06:11.447313 8 admission.go:149] processed ingress via
admission controller {testedIngressLength:1 testedIngressTime:0.02s
renderingIngressLength:1 renderingIngressTime:0s admissionTime:17.9kBs
testedConfigurationSize:0.02}</p>
<p>I1129 15:06:11.447349 8 main.go:101] "successfully validated
configuration, accepting" ingress="ingress-srv/default"</p>
<p>I1129 15:06:11.449266 8 event.go:282]
Event(v1.ObjectReference{Kind:"Ingress", Namespace:"default",
Name:"ingress-srv", UID:"6c15d014-ac14-404e-8b5e-d8526736c52a",
APIVersion:"networking.k8s.io/v1", ResourceVersion:"1347",
FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync</p>
<p>I1129 15:06:11.449669 8 controller.go:155] "Configuration
changes detected, backend reload required"</p>
<p>I1129 15:06:11.499772 8 controller.go:172] "Backend successfully
reloaded"</p>
<p>I1129 15:06:11.500210 8 event.go:282]
Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx",
Name:"ingress-nginx-controller-54bfb9bb-f6gsf",
UID:"54e0c0c6-40ea-439e-b1a2-7787f1b37e7a", APIVersion:"v1",
ResourceVersion:"766", FieldPath:""}): type: 'Normal' reason: 'RELOAD'
NGINX reload triggered due to a change in configuration</p>
</blockquote>
| <h2><strong>AFTER COMPLETE RESET OF KUBERNETES THIS SOLUTION DOES NOT WORK!</strong></h2>
<p><strong>Will re-edit main question<br />
Leaving post for future use</strong></p>
<p>I solved the problem, or at least I think so.<br />
In addition to <a href="https://stackoverflow.com/questions/70115934/problem-with-deploying-blazor-server-app-to-kubernetes?noredirect=1#comment123954982_70115934">@moonkotte</a> suggestion to add the <code>ingressClassName: nginx</code> to <code>ingress-srv.yaml</code> I also changed the ingress port configuration so that it points to port <code>80</code> now.</p>
<p>Thanks to those changes using <code>scp.com</code> now correctly opens my app.
Also, using NodePort access I can visit my app using <code>localhost:30080</code>, where the 30080 port was set automatically (I removed the <code>nodePort</code> configuration line from <code>scanapp-np-srv.yaml</code>)</p>
<p>Why does the port in <code>ingress-srv.yaml</code> have to be set to 80 if <code>clusterIp</code> configuration states to set port <code>8080</code> to target port <code>80</code> - I don't know, I do not fully understand the inner workings of Kubernetes configuration - <strong>All explanations are more than welcome.</strong></p>
<p>Current state of main configuration files:</p>
<p><code>ingress-srv.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-srv
annotations:
nginx.ingress.kubernetes.io/affinity: "cookie"
nginx.ingress.kubernetes.io/session-cookie-name: "affinity"
nginx.ingress.kubernetes.io/session-cookie-expires: "14400"
nginx.ingress.kubernetes.io/session-cookie-max-age: "14400"
spec:
ingressClassName: nginx
rules:
- host: scp.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: scanapp-clusterip-srv
port:
number: 80
</code></pre>
<p><br />
<br />
<code>scanapp-np-srv.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
name: scanappnpservice-srv
spec:
type: NodePort
selector:
app: scanapp
ports:
- name: ui
port: 8080
targetPort: 80
- name: scanapp0
protocol: TCP
port: 5000
targetPort: 5000
- name: scanapp1
protocol: TCP
port: 5001
targetPort: 5001
- name: scanapp5
protocol: TCP
port: 5005
targetPort: 5005
</code></pre>
<p><br />
<br />
<code>scanapp-depl.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: scanapp-depl
spec:
replicas: 1
selector:
matchLabels:
app: scanapp
template:
metadata:
labels:
app: scanapp
spec:
containers:
- name: scanapp
image: scanapp:1.0
---
apiVersion: v1
kind: Service
metadata:
name: scanapp-clusterip-srv
spec:
type: ClusterIP
selector:
app: scanapp
ports:
- name: ui
protocol: TCP
port: 8080
targetPort: 80
- name: ui2
protocol: TCP
port: 8081
targetPort: 443
- name: scanapp0
protocol: TCP
port: 5000
targetPort: 5000
- name: scanapp1
protocol: TCP
port: 5001
targetPort: 5001
- name: scanapp5
protocol: TCP
port: 5005
targetPort: 5005
</code></pre>
<p>Rest of files remained untouched.</p>
|
<p>I'm trying to deploy <code>mongo</code> in <code>Kubernetes</code>, but before I run the <code>mongo</code> itself, it should do some prerequisites in init containers.</p>
<p>This is the list of <code>configMaps</code></p>
<pre><code>mongo-auth-env 4 16m
mongo-config 1 16m
mongo-config-env 7 16m
mongo-scripts 10 16m
</code></pre>
<p><code>StatefulSet</code> looks like:</p>
<pre><code>apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongo
labels:
component: mongo
spec:
selector:
matchLabels:
component: mongo
serviceName: mongo
replicas: 1
template:
metadata:
labels:
component: mongo
spec:
initContainers:
- name: mongo-init
image: curlimages/curl:latest
volumeMounts:
- mountPath: /mongodb/mongodb-config.sh
name: mongo-config
subPath: mongodb-config.sh
- mountPath: /mongo/scripts
name: mongo-scripts
containers:
- name: mongo
image: bitnami/mongodb:latest
command: [ "/bin/sh", "-c" ]
args:
- /scripts/mongo-run.sh
livenessProbe:
exec:
command:
- '[ -f /data/health.check ] && exit 0 || exit 1'
failureThreshold: 300
periodSeconds: 2
timeoutSeconds: 60
ports:
- containerPort: 27017
imagePullPolicy: Always
volumeMounts:
- name: mongo-persistent-storage
mountPath: /data/db
- name: mongo-scripts
mountPath: /mongo/scripts
env:
- name: MONGO_USER_APP_NAME
valueFrom:
configMapKeyRef:
key: MONGO_USER_APP_NAME
name: mongo-auth-env
- name: MONGO_USER_APP_PASSWORD
valueFrom:
configMapKeyRef:
key: MONGO_USER_APP_PASSWORD
name: mongo-auth-env
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
configMapKeyRef:
key: MONGO_USER_ROOT_NAME
name: mongo-auth-env
- name: MONGO_INITDB_ROOT_PASSWORD
valueFrom:
configMapKeyRef:
key: MONGO_USER_ROOT_PASSWORD
name: mongo-auth-env
- name: MONGO_WIREDTIGER_CACHE_SIZE
valueFrom:
configMapKeyRef:
key: MONGO_WIREDTIGER_CACHE_SIZE
name: mongo-config-env
restartPolicy: Always
volumes:
- name: mongo-scripts
configMap:
name: mongo-scripts
defaultMode: 0777
- name: mongo-config
configMap:
name: mongo-config
defaultMode: 0777
volumeClaimTemplates:
- metadata:
name: mongo-persistent-storage
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
</code></pre>
<p>Pod description:</p>
<pre><code>Init Containers:
mongo-init:
Container ID: docker://9a4c20c9b67470af03ee4f60a24eabc428ecafd3875b398ac52a54fe3b2b7b96
Image: curlimages/curl:latest
Image ID: docker-pullable://curlimages/curl@sha256:d588ff348c251f8e4d1b2053125c34d719a98ff3ef20895c49684b3743995073
Port: <none>
Host Port: <none>
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Error
Exit Code: 2
Started: Fri, 19 Nov 2021 02:04:16 +0100
Finished: Fri, 19 Nov 2021 02:04:16 +0100
Ready: False
Restart Count: 8
Environment: <none>
Mounts:
/mongo/scripts from mongo-scripts (rw)
/mongodb/mongodb-config.sh from mongo-config (rw,path="mongodb-config.sh")
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-9jwkz (ro)
Containers:
mongo:
Container ID:
Image: mongo:4.2.12-bionic
Image ID:
Port: 27017/TCP
Host Port: 0/TCP
Command:
/bin/sh
-c
Args:
/scripts/mongo-run.sh
State: Waiting
Reason: PodInitializing
Ready: False
Restart Count: 0
Liveness: exec [[ -f /data/health.check ] && exit 0 || exit 1] delay=0s timeout=60s period=2s #success=1 #failure=300
Environment:
MONGO_USER_APP_NAME: <set to the key 'MONGO_USER_APP_NAME' of config map 'mongo-auth-env'> Optional: false
MONGO_USER_APP_PASSWORD: <set to the key 'MONGO_USER_APP_PASSWORD' of config map 'mongo-auth-env'> Optional: false
MONGO_INITDB_ROOT_USERNAME: <set to the key 'MONGO_USER_ROOT_NAME' of config map 'mongo-auth-env'> Optional: false
MONGO_INITDB_ROOT_PASSWORD: <set to the key 'MONGO_USER_ROOT_PASSWORD' of config map 'mongo-auth-env'> Optional: false
MONGO_WIREDTIGER_CACHE_SIZE: <set to the key 'MONGO_WIREDTIGER_CACHE_SIZE' of config map 'mongo-config-env'> Optional: false
Mounts:
/data/db from mongo-persistent-storage (rw)
/mongo/scripts from mongo-scripts (rw)
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-9jwkz (ro)
Conditions:
Type Status
Initialized False
Ready False
ContainersReady False
PodScheduled True
Volumes:
mongo-persistent-storage:
Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
ClaimName: mongo-persistent-storage-mongo-0
ReadOnly: false
mongo-scripts:
Type: ConfigMap (a volume populated by a ConfigMap)
Name: mongo-scripts
Optional: false
mongo-config:
Type: ConfigMap (a volume populated by a ConfigMap)
Name: mongo-config
Optional: false
</code></pre>
<p>After all files/folders are mounted, there is a <code>run.sh</code> script in the <code>scripts</code> directory which should spin things up, but I can't get to that part because the init container is crashing. Is there any other way of doing this, I tried with <code>Jobs</code> but without success. Am I missing something obvious again, because I can see <code>configMaps</code> in the description, but unfortunately can't get logs because Pod is always initializing, and can't exec into the container because of the same reason? I followed some ideas from <a href="https://github.com/markpeterfejes/mongo-repl-init-container" rel="nofollow noreferrer">this repo</a>. Any input would be appreciated.</p>
| <p>To clarify I am posting Community Wiki answer.</p>
<p>The problem here was small mistake - incorrect path (<code>/scripts/mongo-run.sh</code>) - the correct one: <code>/mongodb/scripts/mongo-run.sh</code></p>
<blockquote>
<p>@dejanmarich: correct path s /mongodb/scripts/mongo-run.sh, i just missed that, fixed now</p>
</blockquote>
|
<p>As of now i do</p>
<pre><code> kubectl --context <cluster context> get pod -A
</code></pre>
<p>to get pod in specific cluster</p>
<p>is there a python way to set kubernetes context for a virtual env , so we can use multiple context at the same time
example :</p>
<pre><code>Terminal 1:
(cluster context1) user@machine #
Terminal 2:
(cluster context2) user@machine #
</code></pre>
<p>This should be equivalent of</p>
<pre><code>Terminal 1:
user@machine # kubectl --context <cluster context1> get pod -A
Terminal 2:
user@machine # kubectl --context <cluster context1> get pod -A
</code></pre>
| <p>This isn't probably a rational solution, but anyway... At some time I used different <code>kubectl</code> versions for different clusters and I came up with a venv-like solution to switch between them. I wrote text files like this:</p>
<pre class="lang-sh prettyprint-override"><code>export KUBECONFIG="/path/to/kubeconfig"
export PATH="/path/including/the/right/kubectl"
</code></pre>
<p>And activated them in the same fashion as venv: <code>source the_file</code>. If you can split your contexts to separate files, you can add <code>export KUBECONFIG="/path/to/kubeconfig"</code> to your <code>venv/bin/activate</code> and it will use the desired config when you activate the <code>venv</code>.</p>
|
<p>I'm working with prometheus to scrape k8s service metrics.</p>
<p>I created a service monitor for my service as below :</p>
<pre><code>apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: scmpoll-service-monitor-{{ .Release.Name }}
namespace: {{ .Release.Namespace }}
labels:
app: scmpoll-{{ template "jenkins-exporter.name" . }}
chart: {{ template "jenkins-exporter.chart" . }}
release: {{ .Release.Name }}
heritage: {{ .Release.Service }}
spec:
namespaceSelector:
matchNames:
- {{ .Release.Namespace }}
selector:
matchLabels:
app: scmpoll-{{ template "jenkins-exporter.name" . }}
chart: {{ template "jenkins-exporter.chart" . }}
release: {{ .Release.Name }}
endpoints:
- interval: 1440m
targetPort: 9759
path: /metrics
port: http
</code></pre>
<p>I set interval: 1440m because I want prometheus to scrape data once a day.</p>
<p>After deploying the chart, the service monitor was added to prometheus targets but with status unknown and scrape duration 0s. The screenshot below:</p>
<p><a href="https://i.stack.imgur.com/JBXzy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBXzy.png" alt="enter image description here" /></a></p>
<p>Also I have the service monitor added to prometheus config:</p>
<pre><code>- job_name: monitoring/scmpoll-service-monitor-my-release/0
honor_timestamps: true
scrape_interval: 1d
scrape_timeout: 10s
metrics_path: /metrics
scheme: http
</code></pre>
<p>I can see that scrape-intervel is set to 1d (24h) but the state is unknown in the screenshot above. Do I have to wait for the next 24h and check or does this mean the configuration is wrong?</p>
<p>Test : i made test with scrape 20minutes and it was the same thing : status unknow with no metrics until the 20 minutes passed and status became UP and metrics were scraped.</p>
<p>I'm not working on prometheus-operator chart, it's an independent chart.</p>
| <p>As mentioned, in general it's not advisable to use scrape intervals of more than 2 minutes in Prometheus (e.g. see <a href="https://stackoverflow.com/a/40233721/4747193">here</a>). This is due to the default <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/#staleness" rel="nofollow noreferrer">staleness</a> period of 5 minutes, which means that a scrape interval of 2 minutes allows for one failed scrape without the metrics being treated as stale.</p>
<p>There's nothing wrong with scraping a target more often. So, you can leave the scrape interval at e.g. 60 seconds, even if the metrics don't change often.</p>
<p>If you can't scrape the target so often for some reason, you can use a <a href="https://github.com/prometheus/pushgateway" rel="nofollow noreferrer">Pushgateway</a>. The target pushes its metrics to the Pushgateway at its own pace (e.g. once per day) and Prometheus scrapes the metrics from the Pushgateway in its own interval (e.g. every 60 seconds).</p>
|
<p>The k8s scheduling implementation comes in two forms: <a href="https://v1-18.docs.kubernetes.io/docs/reference/scheduling/" rel="nofollow noreferrer">Scheduling Policies and Scheduling Profiles</a>.</p>
<p><strong>What is the relationship between the two?</strong> They seem to overlap but have some differences. For example, there is a <code>NodeUnschedulable</code> in the <code>profiles</code> but not in the <code>policy</code>. <code>CheckNodePIDPressure</code> is in the <code>policy</code>, but not in the <code>profiles</code></p>
<p>In addition, there is a default startup option in the scheduling configuration, but it is not specified in the scheduling policy. How can I know about the default startup policy?</p>
<p>I really appreciate any help with this.</p>
| <p>The difference is simple: Kubernetes does't support 'Scheduling policies' from v1.19 or later. Kubernetes v1.19 supports <a href="https://kubernetes.io/docs/reference/scheduling/config/#multiple-profiles" rel="nofollow noreferrer">configuring multiple scheduling policies</a> with a single scheduler. We are using this to define a bin-packing scheduling policy in all v1.19 clusters by default. 'Scheduling profiles' can be used to define a bin-packing scheduling policy in all v1.19 clusters by default.</p>
<p>To use that scheduling policy, all that is required is to specify the scheduler name bin-packing-scheduler in the Pod spec. For example:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 5
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
schedulerName: bin-packing-scheduler
containers:
- name: nginx
image: nginx:1.17.8
resources:
requests:
cpu: 200m
</code></pre>
<p>The pods of this deployment will be scheduled onto the nodes which already have the highest resource utilisation, to optimise for autoscaling or ensuring efficient pod placement when mixing large and small pods in the same cluster.</p>
<p>If a scheduler name is not specified then the default spreading algorithm will be used to distribute pods across all nodes.</p>
|
<p>I’m trying to set up a nginx ingress controller to help validate a configuration. I’m trying to remove all the pieces and re-add the ingress controller to make sure everything I’ve documented works. The Ingress is removed, the service is removed, and pods successfully delete but they come back. The logs complain about the missing pieces I removed (backend-service, lb/service, ingress). Thoughts? Was I supposed to remove this in a different order? --force has the same result.</p>
| <p>Easiest way to cleanup a namespace is to supply <code>-n namespace</code> with <code>all --all</code></p>
<pre><code>kubectl delete all --all -n ingress-nginx
</code></pre>
|
<p>We are running our kafka stream application on Azure kubernetes written in java. We are new to kubernetes. To debug an issue we want to take thread dump of the running pod.</p>
<p>Below are the steps we are following to take the dump.</p>
<ol>
<li><p>Building our application with below docker file.</p>
<pre><code>FROM mcr.microsoft.com/java/jdk:11-zulu-alpine
RUN apk update && apk add --no-cache gcompat
RUN addgroup -S user1 && adduser -S user1 -G user1
USER user1
WORKDIR .
COPY target/my-application-1.0.0.0.jar .
</code></pre>
</li>
<li><p>Submitting the image with below deployment yaml file</p>
</li>
</ol>
<p>apiVersion: apps/v1
kind: Deployment
metadata:
name: my-application-v1.0.0.0
spec:
replicas: 1
selector:
matchLabels:
name: my-application-pod
app: my-application-app
template:
metadata:
name: my-application-pod
labels:
name: my-application-pod
app: my-application-app
spec:
nodeSelector:
agentpool: agentpool1
containers:
- name: my-application-0
image: myregistry.azurecr.io/my-application:v1.0.0.0
imagePullPolicy: Always
command: ["java","-jar","my-application-1.0.0.0.jar","input1","$(connection_string)"]
env:
- name: connection_string
valueFrom:
configMapKeyRef:
name: my-application-configmap
key: connectionString
resources:
limits:
cpu: "4"
requests:
cpu: "0.5"</p>
<ol start="3">
<li><p>To get a shell to a Running container you can run the command below:</p>
<p>kubectl exec -it <POD_NAME> -- sh</p>
</li>
<li><p>To get thread dump running below command</p>
<p>jstack PID > threadDump.tdump</p>
</li>
</ol>
<p>but getting permission denied error
<a href="https://i.stack.imgur.com/TKfeE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TKfeE.png" alt="enter image description here" /></a></p>
<p>Can some one suggest how to solve this or steps to take thread/heap dumps.
Thanks in advance</p>
| <p>Since you likely need the thread dump locally, you can bypass creating the file in the pod and just stream it directly to a file on your local computer:</p>
<pre><code>kubectl exec -i POD_NAME -- jstack 1 > threadDump.tdump
</code></pre>
<p>If your thread dumps are large you may want to consider piping to <code>pv</code> first to get a nice progress bar.</p>
|
<p>Trying to make the app in kubernetes with walkthrough of
Docker and Kubernetes - Full Course for Beginners
<a href="https://www.youtube.com/watch?v=Wf2eSG3owoA&t=14992s&ab_channel=freeCodeCamp.org" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Wf2eSG3owoA&t=14992s&ab_channel=freeCodeCamp.org</a></p>
<p>After the comands:</p>
<pre><code>wendel@wendel-VirtualBox:~/Docker-Kub-MongoDB$ kubectl apply -f mongo-configmap.yaml
configmap/mongodb-configmap created
wendel@wendel-VirtualBox:~/Docker-Kub-MongoDB$ kubectl apply -f mongo-express.yaml
deployment.apps/mongo-express created
wendel@wendel-VirtualBox:~/Docker-Kub-MongoDB$ kubectl logs mongo-express-78fcf796b8-t9lqj
Welcome to mongo-express
------------------------
(...)
(node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated,
and will be removed in a future version.
To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true }
to the MongoClient constructor.
Mongo Express server listening at http://0.0.0.0:8081
Server is open to allow connections from anyone (0.0.0.0)
basicAuth credentials are "admin:pass", it is recommended you change this in your config.js!
</code></pre>
<p><a href="https://i.stack.imgur.com/KhcMi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhcMi.png" alt="enter image description here" /></a>
list of yamls:</p>
<p><a href="https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo-configmap.yaml" rel="nofollow noreferrer">https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo-configmap.yaml</a></p>
<p><a href="https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo-express.yaml" rel="nofollow noreferrer">https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo-express.yaml</a></p>
<p><a href="https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo-secret.yaml" rel="nofollow noreferrer">https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo-secret.yaml</a></p>
<p><a href="https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo.yaml" rel="nofollow noreferrer">https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo.yaml</a></p>
<p>What I missed to apear this warning message?</p>
| <p>This warning message is not related to k8s. This is related to change in js driver for mongodb server discovery. In your code where you instantiate mongodb client you should specify the flag suggested in the warning message:</p>
<p><code>const driver = MongoClient(<connection string>, { useUnifiedTopology: true })</code></p>
<p>The warning should go away then.</p>
|
<p>I am trying to migrate the PostgreSQL database from a performance NAS service to a cheaper General NAS service. Now I want to created a new PV and PVC and make my kubernetes statefulset to binding to the new PVC. I tried to edit the PVC binding in statefulset but give me this error:</p>
<pre><code>The StatefulSet "reddwarf-postgresql-postgresql" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden
</code></pre>
<p>So It is impossible to change the legacy statefulset to binding to a new PVC? I have to create a new statefulset and delete the legacy PostgreSQL statefulset? what is the most smooth way to migrate the statefulset storage? I have copied all data and file structure from the legacy performance NAS service to the new NAS service.</p>
| <p>Most fields become immutable once deployed, you can only delete and re-deploy for immutable fields. But this is not necessary a bad thing for your case. You can leverage the fact that when you delete StatefulSet, the PVC/PC are not automatically deleted. So you can consider create new StatefulSet which back by new PVC/PV using your new storage, then you move backup data to these newly created volumes. Then you delete the StatefulSet and update it with command for your Postgresql to run. Finally you re-deploy your StatefulSet and it will reuse the populated PVC/PV.</p>
<p>Other common approach is write <code>initContainers</code> to check if your pod is fresh and populate the volume with backup data if needed. You need to make sure your restore script is idempotent in this case.</p>
|
<p>Today I want to change the PostgreSQL statefulset PVC name, to my surprise, I did not found any clain about the PVC in the kubernetes deployment define, this is the kubernetes deployment define of PostgreSQL:</p>
<pre><code>apiVersion: apps/v1
kind: StatefulSet
metadata:
name: reddwarf-postgresql-postgresql
namespace: reddwarf-storage
uid: 787a18c8-f6fb-4deb-bb07-3c3d123cf6f9
resourceVersion: '21931453'
generation: 30
creationTimestamp: '2021-08-05T05:29:03Z'
labels:
app.kubernetes.io/component: primary
app.kubernetes.io/instance: reddwarf-postgresql
app.kubernetes.io/managed-by: Helm
app.kubernetes.io/name: postgresql
helm.sh/chart: postgresql-10.9.1
annotations:
kubectl.kubernetes.io/last-applied-configuration: >
{"apiVersion":"apps/v1","kind":"StatefulSet","metadata":{"annotations":{"meta.helm.sh/release-name":"reddwarf-postgresql","meta.helm.sh/release-namespace":"reddwarf-storage"},"creationTimestamp":"2021-08-05T05:29:03Z","generation":12,"labels":{"app.kubernetes.io/component":"primary","app.kubernetes.io/instance":"reddwarf-postgresql","app.kubernetes.io/managed-by":"Helm","app.kubernetes.io/name":"postgresql","helm.sh/chart":"postgresql-10.9.1"},"managedFields":[{"apiVersion":"apps/v1","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{".":{},"f:meta.helm.sh/release-name":{},"f:meta.helm.sh/release-namespace":{}},"f:labels":{".":{},"f:app.kubernetes.io/component":{},"f:app.kubernetes.io/instance":{},"f:app.kubernetes.io/managed-by":{},"f:app.kubernetes.io/name":{},"f:helm.sh/chart":{}}},"f:spec":{"f:podManagementPolicy":{},"f:replicas":{},"f:revisionHistoryLimit":{},"f:selector":{},"f:serviceName":{},"f:template":{"f:metadata":{"f:labels":{".":{},"f:app.kubernetes.io/component":{},"f:app.kubernetes.io/instance":{},"f:app.kubernetes.io/managed-by":{},"f:app.kubernetes.io/name":{},"f:helm.sh/chart":{},"f:role":{}},"f:name":{}},"f:spec":{"f:affinity":{".":{},"f:podAntiAffinity":{".":{},"f:preferredDuringSchedulingIgnoredDuringExecution":{}}},"f:automountServiceAccountToken":{},"f:containers":{"k:{\"name\":\"reddwarf-postgresql\"}":{".":{},"f:env":{".":{},"k:{\"name\":\"BITNAMI_DEBUG\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"PGDATA\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_CLIENT_MIN_MESSAGES\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_ENABLE_LDAP\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_ENABLE_TLS\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_LOG_CONNECTIONS\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_LOG_DISCONNECTIONS\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_LOG_HOSTNAME\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_PGAUDIT_LOG_CATALOG\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_PORT_NUMBER\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_SHARED_PRELOAD_LIBRARIES\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRESQL_VOLUME_DIR\"}":{".":{},"f:name":{},"f:value":{}},"k:{\"name\":\"POSTGRES_PASSWORD\"}":{".":{},"f:name":{},"f:valueFrom":{".":{},"f:secretKeyRef":{".":{},"f:key":{},"f:name":{}}}},"k:{\"name\":\"POSTGRES_USER\"}":{".":{},"f:name":{},"f:value":{}}},"f:imagePullPolicy":{},"f:livenessProbe":{".":{},"f:exec":{".":{},"f:command":{}},"f:failureThreshold":{},"f:initialDelaySeconds":{},"f:periodSeconds":{},"f:successThreshold":{},"f:timeoutSeconds":{}},"f:name":{},"f:ports":{".":{},"k:{\"containerPort\":5432,\"protocol\":\"TCP\"}":{".":{},"f:containerPort":{},"f:name":{},"f:protocol":{}}},"f:readinessProbe":{".":{},"f:exec":{".":{},"f:command":{}},"f:failureThreshold":{},"f:initialDelaySeconds":{},"f:periodSeconds":{},"f:successThreshold":{},"f:timeoutSeconds":{}},"f:resources":{".":{},"f:requests":{".":{},"f:cpu":{},"f:memory":{}}},"f:securityContext":{".":{},"f:runAsUser":{}},"f:terminationMessagePath":{},"f:terminationMessagePolicy":{},"f:volumeMounts":{".":{},"k:{\"mountPath\":\"/bitnami/postgresql\"}":{".":{},"f:mountPath":{},"f:name":{}},"k:{\"mountPath\":\"/dev/shm\"}":{".":{},"f:mountPath":{},"f:name":{}}}}},"f:dnsPolicy":{},"f:restartPolicy":{},"f:schedulerName":{},"f:securityContext":{".":{},"f:fsGroup":{}},"f:terminationGracePeriodSeconds":{},"f:volumes":{".":{},"k:{\"name\":\"dshm\"}":{".":{},"f:emptyDir":{".":{},"f:medium":{}},"f:name":{}}}}},"f:updateStrategy":{"f:type":{}},"f:volumeClaimTemplates":{}}},"manager":"Go-http-client","operation":"Update","time":"2021-08-05T05:29:03Z"},{"apiVersion":"apps/v1","fieldsType":"FieldsV1","fieldsV1":{"f:spec":{"f:template":{"f:spec":{"f:containers":{"k:{\"name\":\"reddwarf-postgresql\"}":{"f:image":{}}}}}}},"manager":"kubectl-client-side-apply","operation":"Update","time":"2021-08-10T16:50:45Z"},{"apiVersion":"apps/v1","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{"f:kubectl.kubernetes.io/last-applied-configuration":{}}},"f:spec":{"f:template":{"f:spec":{"f:containers":{"k:{\"name\":\"reddwarf-postgresql\"}":{"f:args":{}}}}}}},"manager":"kubectl","operation":"Update","time":"2021-08-11T01:46:21Z"},{"apiVersion":"apps/v1","fieldsType":"FieldsV1","fieldsV1":{"f:status":{"f:collisionCount":{},"f:currentReplicas":{},"f:currentRevision":{},"f:observedGeneration":{},"f:replicas":{},"f:updateRevision":{},"f:updatedReplicas":{}}},"manager":"kube-controller-manager","operation":"Update","time":"2021-08-11T02:24:07Z"}],"name":"reddwarf-postgresql-postgresql","namespace":"reddwarf-storage","selfLink":"/apis/apps/v1/namespaces/reddwarf-storage/statefulsets/reddwarf-postgresql-postgresql","uid":"787a18c8-f6fb-4deb-bb07-3c3d123cf6f9"},"spec":{"podManagementPolicy":"OrderedReady","replicas":1,"revisionHistoryLimit":10,"selector":{"matchLabels":{"app.kubernetes.io/instance":"reddwarf-postgresql","app.kubernetes.io/name":"postgresql","role":"primary"}},"serviceName":"reddwarf-postgresql-headless","template":{"metadata":{"creationTimestamp":null,"labels":{"app.kubernetes.io/component":"primary","app.kubernetes.io/instance":"reddwarf-postgresql","app.kubernetes.io/managed-by":"Helm","app.kubernetes.io/name":"postgresql","helm.sh/chart":"postgresql-10.9.1","role":"primary"},"name":"reddwarf-postgresql"},"spec":{"affinity":{"podAntiAffinity":{"preferredDuringSchedulingIgnoredDuringExecution":[{"podAffinityTerm":{"labelSelector":{"matchLabels":{"app.kubernetes.io/component":"primary","app.kubernetes.io/instance":"reddwarf-postgresql","app.kubernetes.io/name":"postgresql"}},"namespaces":["reddwarf-storage"],"topologyKey":"kubernetes.io/hostname"},"weight":1}]}},"automountServiceAccountToken":false,"containers":[{"env":[{"name":"BITNAMI_DEBUG","value":"false"},{"name":"POSTGRESQL_PORT_NUMBER","value":"5432"},{"name":"POSTGRESQL_VOLUME_DIR","value":"/bitnami/postgresql"},{"name":"PGDATA","value":"/bitnami/postgresql/data"},{"name":"POSTGRES_USER","value":"postgres"},{"name":"POSTGRES_PASSWORD","valueFrom":{"secretKeyRef":{"key":"postgresql-password","name":"reddwarf-postgresql"}}},{"name":"POSTGRESQL_ENABLE_LDAP","value":"no"},{"name":"POSTGRESQL_ENABLE_TLS","value":"no"},{"name":"POSTGRESQL_LOG_HOSTNAME","value":"false"},{"name":"POSTGRESQL_LOG_CONNECTIONS","value":"false"},{"name":"POSTGRESQL_LOG_DISCONNECTIONS","value":"false"},{"name":"POSTGRESQL_PGAUDIT_LOG_CATALOG","value":"off"},{"name":"POSTGRESQL_CLIENT_MIN_MESSAGES","value":"error"},{"name":"POSTGRESQL_SHARED_PRELOAD_LIBRARIES","value":"pgaudit"}],"image":"docker.io/bitnami/postgresql:13.3.0-debian-10-r75","imagePullPolicy":"IfNotPresent","livenessProbe":{"exec":{"command":["/bin/sh","-c","exec
pg_isready -U \"postgres\" -h 127.0.0.1 -p
5432"]},"failureThreshold":6,"initialDelaySeconds":30,"periodSeconds":10,"successThreshold":1,"timeoutSeconds":5},"name":"reddwarf-postgresql","ports":[{"containerPort":5432,"name":"tcp-postgresql","protocol":"TCP"}],"readinessProbe":{"exec":{"command":["/bin/sh","-c","-e","exec
pg_isready -U \"postgres\" -h 127.0.0.1 -p 5432\n[ -f
/opt/bitnami/postgresql/tmp/.initialized ] || [ -f
/bitnami/postgresql/.initialized
]\n"]},"failureThreshold":6,"initialDelaySeconds":5,"periodSeconds":10,"successThreshold":1,"timeoutSeconds":5},"resources":{"requests":{"cpu":"250m","memory":"256Mi"}},"securityContext":{"runAsUser":1001},"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","volumeMounts":[{"mountPath":"/dev/shm","name":"dshm"},{"mountPath":"/bitnami/postgresql","name":"data"}]}],"dnsPolicy":"ClusterFirst","restartPolicy":"Always","schedulerName":"default-scheduler","securityContext":{"fsGroup":1001},"terminationGracePeriodSeconds":30,"volumes":[{"emptyDir":{"medium":"Memory"},"name":"dshm"}]}},"updateStrategy":{"type":"RollingUpdate"},"volumeClaimTemplates":[{"apiVersion":"v1","kind":"PersistentVolumeClaim","metadata":{"creationTimestamp":null,"name":"data"},"spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"8Gi"}},"volumeMode":"Filesystem"},"status":{"phase":"Pending"}}]}}
meta.helm.sh/release-name: reddwarf-postgresql
meta.helm.sh/release-namespace: reddwarf-storage
managedFields:
- manager: Go-http-client
operation: Update
apiVersion: apps/v1
time: '2021-08-05T05:29:03Z'
fieldsType: FieldsV1
fieldsV1:
'f:metadata':
'f:annotations':
.: {}
'f:meta.helm.sh/release-name': {}
'f:meta.helm.sh/release-namespace': {}
'f:labels':
.: {}
'f:app.kubernetes.io/component': {}
'f:app.kubernetes.io/instance': {}
'f:app.kubernetes.io/managed-by': {}
'f:app.kubernetes.io/name': {}
'f:helm.sh/chart': {}
'f:spec':
'f:podManagementPolicy': {}
'f:replicas': {}
'f:revisionHistoryLimit': {}
'f:selector': {}
'f:serviceName': {}
'f:template':
'f:metadata':
'f:labels':
.: {}
'f:app.kubernetes.io/component': {}
'f:app.kubernetes.io/instance': {}
'f:app.kubernetes.io/managed-by': {}
'f:app.kubernetes.io/name': {}
'f:helm.sh/chart': {}
'f:role': {}
'f:name': {}
'f:spec':
'f:affinity':
.: {}
'f:podAntiAffinity':
.: {}
'f:preferredDuringSchedulingIgnoredDuringExecution': {}
'f:automountServiceAccountToken': {}
'f:containers':
'k:{"name":"reddwarf-postgresql"}':
.: {}
'f:env':
.: {}
'k:{"name":"BITNAMI_DEBUG"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"PGDATA"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_CLIENT_MIN_MESSAGES"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_ENABLE_LDAP"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_ENABLE_TLS"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_LOG_CONNECTIONS"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_LOG_DISCONNECTIONS"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_LOG_HOSTNAME"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_PGAUDIT_LOG_CATALOG"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_PORT_NUMBER"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_SHARED_PRELOAD_LIBRARIES"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRESQL_VOLUME_DIR"}':
.: {}
'f:name': {}
'f:value': {}
'k:{"name":"POSTGRES_PASSWORD"}':
.: {}
'f:name': {}
'f:valueFrom':
.: {}
'f:secretKeyRef':
.: {}
'f:key': {}
'f:name': {}
'k:{"name":"POSTGRES_USER"}':
.: {}
'f:name': {}
'f:value': {}
'f:imagePullPolicy': {}
'f:livenessProbe':
.: {}
'f:exec':
.: {}
'f:command': {}
'f:failureThreshold': {}
'f:initialDelaySeconds': {}
'f:periodSeconds': {}
'f:successThreshold': {}
'f:timeoutSeconds': {}
'f:name': {}
'f:ports':
.: {}
'k:{"containerPort":5432,"protocol":"TCP"}':
.: {}
'f:containerPort': {}
'f:name': {}
'f:protocol': {}
'f:readinessProbe':
.: {}
'f:exec':
.: {}
'f:command': {}
'f:failureThreshold': {}
'f:initialDelaySeconds': {}
'f:periodSeconds': {}
'f:successThreshold': {}
'f:timeoutSeconds': {}
'f:resources':
.: {}
'f:requests':
.: {}
'f:cpu': {}
'f:memory': {}
'f:securityContext':
.: {}
'f:runAsUser': {}
'f:terminationMessagePath': {}
'f:terminationMessagePolicy': {}
'f:volumeMounts':
.: {}
'k:{"mountPath":"/bitnami/postgresql"}':
.: {}
'f:mountPath': {}
'f:name': {}
'k:{"mountPath":"/dev/shm"}':
.: {}
'f:mountPath': {}
'f:name': {}
'f:dnsPolicy': {}
'f:restartPolicy': {}
'f:schedulerName': {}
'f:securityContext':
.: {}
'f:fsGroup': {}
'f:terminationGracePeriodSeconds': {}
'f:volumes':
.: {}
'k:{"name":"dshm"}':
.: {}
'f:emptyDir':
.: {}
'f:medium': {}
'f:name': {}
'f:updateStrategy':
'f:type': {}
'f:volumeClaimTemplates': {}
- manager: kubectl-client-side-apply
operation: Update
apiVersion: apps/v1
time: '2021-08-10T16:50:45Z'
fieldsType: FieldsV1
fieldsV1:
'f:spec':
'f:template':
'f:spec':
'f:containers':
'k:{"name":"reddwarf-postgresql"}':
'f:image': {}
- manager: kubectl
operation: Update
apiVersion: apps/v1
time: '2021-08-11T02:29:20Z'
fieldsType: FieldsV1
fieldsV1:
'f:metadata':
'f:annotations':
'f:kubectl.kubernetes.io/last-applied-configuration': {}
- manager: kube-controller-manager
operation: Update
apiVersion: apps/v1
time: '2021-11-27T03:07:58Z'
fieldsType: FieldsV1
fieldsV1:
'f:status':
'f:collisionCount': {}
'f:currentRevision': {}
'f:observedGeneration': {}
'f:replicas': {}
'f:updateRevision': {}
selfLink: >-
/apis/apps/v1/namespaces/reddwarf-storage/statefulsets/reddwarf-postgresql-postgresql
status:
observedGeneration: 30
replicas: 0
currentRevision: reddwarf-postgresql-postgresql-5695cb9676
updateRevision: reddwarf-postgresql-postgresql-5695cb9676
collisionCount: 0
spec:
replicas: 0
selector:
matchLabels:
app.kubernetes.io/instance: reddwarf-postgresql
app.kubernetes.io/name: postgresql
role: primary
template:
metadata:
name: reddwarf-postgresql
creationTimestamp: null
labels:
app.kubernetes.io/component: primary
app.kubernetes.io/instance: reddwarf-postgresql
app.kubernetes.io/managed-by: Helm
app.kubernetes.io/name: postgresql
helm.sh/chart: postgresql-10.9.1
role: primary
spec:
volumes:
- name: dshm
emptyDir:
medium: Memory
containers:
- name: reddwarf-postgresql
image: 'docker.io/bitnami/postgresql:13.3.0-debian-10-r75'
ports:
- name: tcp-postgresql
containerPort: 5432
protocol: TCP
env:
- name: BITNAMI_DEBUG
value: 'false'
- name: POSTGRESQL_PORT_NUMBER
value: '5432'
- name: POSTGRESQL_VOLUME_DIR
value: /bitnami/postgresql
- name: PGDATA
value: /bitnami/postgresql/data
- name: POSTGRES_USER
value: postgres
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: reddwarf-postgresql
key: postgresql-password
- name: POSTGRESQL_ENABLE_LDAP
value: 'no'
- name: POSTGRESQL_ENABLE_TLS
value: 'no'
- name: POSTGRESQL_LOG_HOSTNAME
value: 'false'
- name: POSTGRESQL_LOG_CONNECTIONS
value: 'false'
- name: POSTGRESQL_LOG_DISCONNECTIONS
value: 'false'
- name: POSTGRESQL_PGAUDIT_LOG_CATALOG
value: 'off'
- name: POSTGRESQL_CLIENT_MIN_MESSAGES
value: error
- name: POSTGRESQL_SHARED_PRELOAD_LIBRARIES
value: pgaudit
resources:
requests:
cpu: 250m
memory: 256Mi
volumeMounts:
- name: dshm
mountPath: /dev/shm
- name: data
mountPath: /bitnami/postgresql
livenessProbe:
exec:
command:
- /bin/sh
- '-c'
- exec pg_isready -U "postgres" -h 127.0.0.1 -p 5432
initialDelaySeconds: 30
timeoutSeconds: 5
periodSeconds: 10
successThreshold: 1
failureThreshold: 6
readinessProbe:
exec:
command:
- /bin/sh
- '-c'
- '-e'
- >
exec pg_isready -U "postgres" -h 127.0.0.1 -p 5432
[ -f /opt/bitnami/postgresql/tmp/.initialized ] || [ -f
/bitnami/postgresql/.initialized ]
initialDelaySeconds: 5
timeoutSeconds: 5
periodSeconds: 10
successThreshold: 1
failureThreshold: 6
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
imagePullPolicy: IfNotPresent
securityContext:
runAsUser: 1001
restartPolicy: Always
terminationGracePeriodSeconds: 30
dnsPolicy: ClusterFirst
automountServiceAccountToken: false
securityContext:
fsGroup: 1001
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
podAffinityTerm:
labelSelector:
matchLabels:
app.kubernetes.io/component: primary
app.kubernetes.io/instance: reddwarf-postgresql
app.kubernetes.io/name: postgresql
namespaces:
- reddwarf-storage
topologyKey: kubernetes.io/hostname
schedulerName: default-scheduler
volumeClaimTemplates:
- kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: data
creationTimestamp: null
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 8Gi
volumeMode: Filesystem
status:
phase: Pending
serviceName: reddwarf-postgresql-headless
podManagementPolicy: OrderedReady
updateStrategy:
type: RollingUpdate
revisionHistoryLimit: 10
</code></pre>
<p>this statefulset bind the PVC named <code>data-reddwarf-postgresql-postgresql-0</code> right now, but I did not found the PVC define in this statefulset yaml. where is the PVC bind define? what should I do to change the PVC to bind to a new one? I install this PostgreSQL into kubernetes from helm chart.</p>
| <p>pvc thats gets created as a part of statefulset will have a name which is an amalgamation of 3 components joined by <code>-</code> :</p>
<ol>
<li>Name defined in the <code>volumeClaimTemplates</code> section <code>data</code></li>
<li>Name of the <code>statefulset</code> in the metadata section which is <code>reddwarf-postgresql-postgresql</code></li>
<li>Its replica number , if it is first replica then it would be <code>0</code></li>
</ol>
<p>So finally the name of the pvc that gets created when you create this statefulset is
<code>data-reddwarf-postgresql-postgresql-0</code>.which is the pvc name that you also seeing in your setup.</p>
<p>please note when you delete the statefulset , pvc does not deleted automatically we need to pvc separately. When you recreate/scaleup the stateful set and if the pvc which matches above naming convention& spec does not exists then it will create a pvc.</p>
<p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#stable-network-id" rel="nofollow noreferrer">From kubernetes documentation</a></p>
|
<p>I'm trying to deploy a knative service in my local Kubernetes cluster (Docker Desktop for windows).
I could create a knative service when I use images from the google cloud container registry (gcr.io/knative-samples/helloworld-go) but I'm facing an issue when I use images from the docker hub. Please note that I not using any private repository in the Docker registry.</p>
<p>The revision.serving will be in status <strong>unknown</strong> for the first 10 minutes and later changes to false with the reason <strong>ProgressDeadlineExceeded</strong>. The knative service fails with reason <strong>RevisionMissing</strong>. I have tried using the official hello-world image from docker hub and the response is the same.
The issue is only when I'm using images from the docker official registry but now when GCR is used.</p>
<p>Below is the Kubernetes manifest file I used to create a knative service.</p>
<pre><code>apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: **********
spec:
template:
metadata:
# This is the name of our new "Revision," it must follow the convention {service-name}-{revision-name}
name: *******-rev1
spec:
containers:
- image: docker.io/*****/****:v1
imagePullPolicy: IfNotPresent
ports:
- containerPort: 3007
</code></pre>
<p><a href="https://i.stack.imgur.com/dHT0w.png" rel="nofollow noreferrer">screenshot of kubernetes resources</a></p>
<p>Note: I'm using knative-serving version 1.0
Edit: (I have hidden image name)</p>
<p><a href="https://i.stack.imgur.com/xaqY1.png" rel="nofollow noreferrer">status of revision.serving</a></p>
| <p>Finally, I resolved the issue by removing the ports session in the YAML file. If the container port is included, the application gets started in a container (I have verified the logs) but it never receives the traffic and fails with the ProgressDeadlineExceeded error.</p>
|
<p>I've tried everything on stack overflow and beyond and can't find a solution that works to redirect http to https. My current config is below.</p>
<p>My ingress is:</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress
annotations:
kubernetes.io/ingress.class: "nginx"
kubernetes.io/ingress.global-static-ip-name: my-address
networking.gke.io/managed-certificates: my-certificate
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
spec:
rules:
- host: mydomain.com
http:
paths:
- path: /*
pathType: ImplementationSpecific
backend:
service:
name: my-service
port:
number: 2400
</code></pre>
<p>And my service is:</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: NodePort
selector:
app: nodeweb
ports:
- name: my-service-port
protocol: TCP
port: 2400
targetPort: 2400
</code></pre>
| <p>For GKE (<code>1.17.13-gke.2600+</code>), find <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/ingress-features#https_redirect" rel="nofollow noreferrer">this document</a> explaining how to configure FrontendConfig with http-to-https redirect. Then you <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/ingress-features#associating_frontendconfig_with_your_ingress" rel="nofollow noreferrer">associate</a> the FrontendConfig with your Ingress using <code>networking.gke.io/v1beta1.FrontendConfig</code> annotation.</p>
|
<p>I have a Kubernetes Cluster with pods autoscalables using Autopilot. Suddenly they stop to autoscale, I'm new at Kubernetes and I don't know exactly what to do or what is supposed to put in the console to show for help.</p>
<p>The pods automatically are Unschedulable and inside the cluster put his state at Pending instead of running and doesn't allow me to enter or interact.</p>
<p>Also I can't delete or stop them at GCP Console. There's no issue regarding memory or insufficient CPU because there's not much server running on it.</p>
<p>The cluster was working as expected before this issue I have.</p>
<pre><code>Namespace: default
Priority: 0
Node: <none>
Labels: app=odoo-service
pod-template-hash=5bd88899d7
Annotations: seccomp.security.alpha.kubernetes.io/pod: runtime/default
Status: Pending
IP:
IPs: <none>
Controlled By: ReplicaSet/odoo-cluster-dev-5bd88899d7
Containers:
odoo-service:
Image: us-central1-docker.pkg.dev/adams-dev/adams-odoo/odoo-service:v58
Port: <none>
Host Port: <none>
Limits:
cpu: 2
ephemeral-storage: 1Gi
memory: 8Gi
Requests:
cpu: 2
ephemeral-storage: 1Gi
memory: 8Gi
Environment:
ODOO_HTTP_SOCKET_TIMEOUT: 30
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-zqh5r (ro)
cloud-sql-proxy:
Image: gcr.io/cloudsql-docker/gce-proxy:1.17
Port: <none>
Host Port: <none>
Command:
/cloud_sql_proxy
-instances=adams-dev:us-central1:odoo-test=tcp:5432
Limits:
cpu: 1
ephemeral-storage: 1Gi
memory: 2Gi
Requests:
cpu: 1
ephemeral-storage: 1Gi
memory: 2Gi
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-zqh5r (ro)
Conditions:
Type Status
PodScheduled False
Volumes:
kube-api-access-zqh5r:
Type: Projected (a volume that contains injected data from multiple sources)
TokenExpirationSeconds: 3607
ConfigMapName: kube-root-ca.crt
ConfigMapOptional: <nil>
DownwardAPI: true
QoS Class: Guaranteed
Node-Selectors: <none>
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 NotTriggerScaleUp 28m (x248 over 3h53m) cluster-autoscaler pod didn't trigger scale-up (it wouldn't fit if a new node is added): 4 in backoff after failed scale-up, 2 Insufficient cpu, 2 Insufficient memory
Normal NotTriggerScaleUp 8m1s (x261 over 3h55m) cluster-autoscaler pod didn't trigger scale-up (it wouldn't fit if a new node is added): 2 Insufficient memory, 4 in backoff after failed scale-up, 2 Insufficient cpu
Normal NotTriggerScaleUp 3m (x1646 over 3h56m) cluster-autoscaler pod didn't trigger scale-up (it wouldn't fit if a new node is added): 2 Insufficient cpu, 2 Insufficient memory, 4 in backoff after failed scale-up
Warning FailedScheduling 20s (x168 over 3h56m) gke.io/optimize-utilization-scheduler 0/2 nodes are available: 2 Insufficient cpu, 2 Insufficient memory.
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal NotTriggerScaleUp 28m (x250 over 3h56m) cluster-autoscaler pod didn't trigger scale-up (it wouldn't fit if a new node is added): 2 Insufficient memory, 4 in backoff after failed scale-up, 2 Insufficient cpu
Normal NotTriggerScaleUp 8m2s (x300 over 3h55m) cluster-autoscaler pod didn't trigger scale-up (it wouldn't fit if a new node is added): 4 in backoff after failed scale-up, 2 Insufficient cpu, 2 Insufficient memory
Warning FailedScheduling 5m21s (x164 over 3h56m) gke.io/optimize-utilization-scheduler 0/2 nodes are available: 2 Insufficient cpu, 2 Insufficient memory.
Normal NotTriggerScaleUp 3m1s (x1616 over 3h55m) cluster-autoscaler pod didn't trigger scale-up (it wouldn't fit if a new node is added): 2 Insufficient cpu, 2 Insufficient memory, 4 in backoff after failed scale-up
</code></pre>
<p>I don't know how much I can debug or fix it.</p>
| <p>Pods failed to schedule on any node because none of the nodes have cpu available.</p>
<p>Cluster autoscaler tried to scale up but it backoff after failed scale-up attempt which indicates possible issues with scaling up managed instance groups which are part of the node pool.</p>
<p>Cluster autoscaler tried to scale up but as the quota limit is reached no new nodes can be added.</p>
<p>You can't see the Autopilot GKE VMs that are being counted against your quota.</p>
<p>Try by creating the autopilot cluster in another region. If your needs are not no longer fulfilled by an autopilot cluster then go for a standard cluster.</p>
|
<p>I know there have been already a lot of questions about this, and I read already most of them, but my problem does not seem to fit them.</p>
<p>I am running a postgresql from bitnami using a helm chart as described below. A clean setup is no problem and everything starts fine. But after some time, until now I could not find any pattern, the pod goes into CrashLoopBackOff and I cannot recover it whatever I try!</p>
<p>Helm uninstall/install does not fix the problem. The PVs seem to be the problem, but I do not know why. <em>And</em> I do not get any error message, which is the weird and scary part of it.</p>
<p>I use a minikube to run the k8s and helm v3.</p>
<ul>
<li>Helm chart: <a href="https://artifacthub.io/packages/helm/bitnami/postgresql/10.9.5" rel="nofollow noreferrer">https://artifacthub.io/packages/helm/bitnami/postgresql/10.9.5</a></li>
</ul>
<p>Here are the definitions and logs:</p>
<pre><code># Source: aposphere/charts/sessiondb/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
name: sessiondb
labels:
app.kubernetes.io/name: sessiondb
helm.sh/chart: sessiondb-10.9.6
app.kubernetes.io/instance: asdf
app.kubernetes.io/managed-by: Helm
annotations:
namespace: default
spec:
type: ClusterIP
ports:
- name: tcp-postgresql
port: 5432
targetPort: tcp-postgresql
selector:
app.kubernetes.io/name: sessiondb
app.kubernetes.io/instance: asdf
role: primary
---
# Source: aposphere/charts/sessiondb/templates/statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: sessiondb
labels:
app.kubernetes.io/name: sessiondb
helm.sh/chart: sessiondb-10.9.6
app.kubernetes.io/instance: asdf
app.kubernetes.io/managed-by: Helm
app.kubernetes.io/component: primary
annotations:
namespace: default
spec:
serviceName: sessiondb-headless
replicas: 1
updateStrategy:
type: RollingUpdate
selector:
matchLabels:
app.kubernetes.io/name: sessiondb
app.kubernetes.io/instance: asdf
role: primary
template:
metadata:
name: sessiondb
labels:
app.kubernetes.io/name: sessiondb
helm.sh/chart: sessiondb-10.9.6
app.kubernetes.io/instance: asdf
app.kubernetes.io/managed-by: Helm
role: primary
app.kubernetes.io/component: primary
spec:
affinity:
podAffinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- podAffinityTerm:
labelSelector:
matchLabels:
app.kubernetes.io/name: sessiondb
app.kubernetes.io/instance: asdf
app.kubernetes.io/component: primary
namespaces:
- "default"
topologyKey: kubernetes.io/hostname
weight: 1
nodeAffinity:
securityContext:
fsGroup: 1001
automountServiceAccountToken: false
containers:
- name: sessiondb
image: docker.io/bitnami/postgresql:11.13.0-debian-10-r33
imagePullPolicy: "IfNotPresent"
resources:
requests:
cpu: 250m
memory: 256Mi
securityContext:
runAsUser: 1001
env:
- name: BITNAMI_DEBUG
value: "false"
- name: POSTGRESQL_PORT_NUMBER
value: "5432"
- name: POSTGRESQL_VOLUME_DIR
value: "/bitnami/postgresql"
- name: PGDATA
value: "/bitnami/postgresql/data"
- name: POSTGRES_USER
value: "postgres"
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgresql-root-password
key: postgresql-password
- name: POSTGRES_DB
value: "session"
- name: POSTGRESQL_ENABLE_LDAP
value: "no"
- name: POSTGRESQL_ENABLE_TLS
value: "no"
- name: POSTGRESQL_LOG_HOSTNAME
value: "false"
- name: POSTGRESQL_LOG_CONNECTIONS
value: "false"
- name: POSTGRESQL_LOG_DISCONNECTIONS
value: "false"
- name: POSTGRESQL_PGAUDIT_LOG_CATALOG
value: "off"
- name: POSTGRESQL_CLIENT_MIN_MESSAGES
value: "error"
- name: POSTGRESQL_SHARED_PRELOAD_LIBRARIES
value: "pgaudit"
ports:
- name: tcp-postgresql
containerPort: 5432
livenessProbe:
exec:
command:
- /bin/sh
- -c
- exec pg_isready -U "postgres" -d "dbname=session" -h 127.0.0.1 -p 5432
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 6
readinessProbe:
exec:
command:
- /bin/sh
- -c
- -e
- |
exec pg_isready -U "postgres" -d "dbname=session" -h 127.0.0.1 -p 5432
[ -f /opt/bitnami/postgresql/tmp/.initialized ] || [ -f /bitnami/postgresql/.initialized ]
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 6
volumeMounts:
- name: custom-init-scripts
mountPath: /docker-entrypoint-initdb.d/
- name: dshm
mountPath: /dev/shm
- name: data
mountPath: /bitnami/postgresql
subPath:
volumes:
- name: custom-init-scripts
configMap:
name: sessiondb-scheme
- name: dshm
emptyDir:
medium: Memory
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes:
- "ReadWriteOnce"
resources:
requests:
storage: "8Gi"
</code></pre>
<p>Logs of the container:</p>
<pre><code>% kubectl logs sessiondb-0
postgresql 10:09:01.48
postgresql 10:09:01.48 Welcome to the Bitnami postgresql container
postgresql 10:09:01.49 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-postgresql
postgresql 10:09:01.49 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-postgresql/issues
postgresql 10:09:01.49
postgresql 10:09:01.50 DEBUG ==> Configuring libnss_wrapper...
postgresql 10:09:01.51 INFO ==> ** Starting PostgreSQL setup **
postgresql 10:09:01.54 INFO ==> Validating settings in POSTGRESQL_* env vars..
postgresql 10:09:01.55 INFO ==> Loading custom pre-init scripts...
postgresql 10:09:01.55 INFO ==> Initializing PostgreSQL database...
postgresql 10:09:01.56 DEBUG ==> Ensuring expected directories/files exist...
postgresql 10:09:01.57 INFO ==> pg_hba.conf file not detected. Generating it...
postgresql 10:09:01.58 INFO ==> Generating local authentication configuration
postgresql 10:09:01.58 INFO ==> Deploying PostgreSQL with persisted data...
postgresql 10:09:01.60 INFO ==> Configuring replication parameters
postgresql 10:09:01.65 INFO ==> Configuring fsync
postgresql 10:09:01.71 INFO ==> Loading custom scripts...
postgresql 10:09:01.72 INFO ==> Loading user's custom files from /docker-entrypoint-initdb.d ...
postgresql 10:09:01.72 INFO ==> Starting PostgreSQL in background...
pg_ctl: directory "/bitnami/postgresql/data" is not a database cluster directory
</code></pre>
<p><em>Afterwards the container terminates, no more logs!</em></p>
<p>Logs of the init container:</p>
<pre><code>% kubectl logs sessiondb-0 init-chmod-data
+ chown 1001:1001 /bitnami/postgresql
+ mkdir -p /bitnami/postgresql/data
+ chmod 700 /bitnami/postgresql/data
+ find /bitnami/postgresql -mindepth 1 -maxdepth 1 -not -name conf -not -name .snapshot -not -name lost+found
+ xargs chown -R 1001:1001
+ chmod -R 777 /dev/shm
</code></pre>
<p>Permissions:</p>
<pre><code>I have no name!@sessiondb-0:/$ stat /bitnami/postgresql/data
File: /bitnami/postgresql/data
Size: 207 Blocks: 0 IO Block: 4096 directory
Device: 10301h/66305d Inode: 712929 Links: 12
Access: (0700/drwx------) Uid: ( 1001/ UNKNOWN) Gid: ( 1001/ UNKNOWN)
Access: 2021-11-10 15:16:13.958633094 +0000
Modify: 2021-11-26 08:40:42.621884636 +0000
Change: 2021-11-26 10:37:47.844490933 +0000
Birth: -
</code></pre>
<p>Describe the resources:</p>
<pre><code>Name: sessiondb-0
Namespace: default
Priority: 0
Node: ip-10-0-1-112.eu-central-1.compute.internal/10.0.1.112
Start Time: Fri, 26 Nov 2021 10:40:02 +0100
Labels: app.kubernetes.io/component=primary
app.kubernetes.io/instance=asdf
app.kubernetes.io/managed-by=Helm
app.kubernetes.io/name=sessiondb
controller-revision-hash=sessiondb-578ddf476b
helm.sh/chart=sessiondb-10.9.6
role=primary
statefulset.kubernetes.io/pod-name=sessiondb-0
Annotations: <none>
Status: Running
IP: 172.17.0.4
IPs:
IP: 172.17.0.4
Controlled By: StatefulSet/sessiondb
Containers:
sessiondb:
Container ID: docker://a94f894687f0813196a94afe88f64723f238eb7d2cb061e4c7ef17354f27dee8
Image: docker.io/bitnami/postgresql:11.13.0-debian-10-r33
Image ID: docker-pullable://bitnami/postgresql@sha256:205e1c5a1d4b56d0d63f6579557652f958e321006c4cb5325d031d40313e4ea2
Port: 5432/TCP
Host Port: 0/TCP
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Error
Exit Code: 1
Started: Fri, 26 Nov 2021 10:50:45 +0100
Finished: Fri, 26 Nov 2021 10:50:46 +0100
Ready: False
Restart Count: 7
Requests:
cpu: 250m
memory: 256Mi
Liveness: exec [/bin/sh -c exec pg_isready -U "postgres" -d "dbname=session" -h 127.0.0.1 -p 5432] delay=30s timeout=5s period=10s #success=1 #failure=6
Readiness: exec [/bin/sh -c -e exec pg_isready -U "postgres" -d "dbname=session" -h 127.0.0.1 -p 5432
[ -f /opt/bitnami/postgresql/tmp/.initialized ] || [ -f /bitnami/postgresql/.initialized ]
] delay=5s timeout=5s period=10s #success=1 #failure=6
Environment:
BITNAMI_DEBUG: false
POSTGRESQL_PORT_NUMBER: 5432
POSTGRESQL_VOLUME_DIR: /bitnami/postgresql
PGDATA: /bitnami/postgresql/data
POSTGRES_USER: postgres
POSTGRES_PASSWORD: <set to the key 'postgresql-password' in secret 'postgresql-root-password'> Optional: false
POSTGRES_DB: session
POSTGRESQL_ENABLE_LDAP: no
POSTGRESQL_ENABLE_TLS: no
POSTGRESQL_LOG_HOSTNAME: false
POSTGRESQL_LOG_CONNECTIONS: false
POSTGRESQL_LOG_DISCONNECTIONS: false
POSTGRESQL_PGAUDIT_LOG_CATALOG: off
POSTGRESQL_CLIENT_MIN_MESSAGES: error
POSTGRESQL_SHARED_PRELOAD_LIBRARIES: pgaudit
Mounts:
/bitnami/postgresql from data (rw)
/dev/shm from dshm (rw)
/docker-entrypoint-initdb.d/ from custom-init-scripts (rw)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
data:
Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
ClaimName: data-sessiondb-0
ReadOnly: false
custom-init-scripts:
Type: ConfigMap (a volume populated by a ConfigMap)
Name: sessiondb-scheme
Optional: false
dshm:
Type: EmptyDir (a temporary directory that shares a pod's lifetime)
Medium: Memory
SizeLimit: <unset>
QoS Class: Burstable
Node-Selectors: <none>
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 11m default-scheduler Successfully assigned default/sessiondb-0 to ip-10-0-1-112.eu-central-1.compute.internal
Normal Created 11m (x4 over 11m) kubelet Created container sessiondb
Normal Started 11m (x4 over 11m) kubelet Started container sessiondb
Normal Pulled 10m (x5 over 11m) kubelet Container image "docker.io/bitnami/postgresql:11.13.0-debian-10-r33" already present on machine
Warning BackOff 110s (x57 over 11m) kubelet Back-off restarting failed container
---
% kubectl describe pvc data-sessiondb-0
Name: data-sessiondb-0
Namespace: default
StorageClass: standard
Status: Bound
Volume: pvc-6b56b20c-3e56-4a92-9278-794bf6cda4de
Labels: app.kubernetes.io/instance=asdf
app.kubernetes.io/name=sessiondb
role=primary
Annotations: pv.kubernetes.io/bind-completed: yes
pv.kubernetes.io/bound-by-controller: yes
volume.beta.kubernetes.io/storage-provisioner: k8s.io/minikube-hostpath
Finalizers: [kubernetes.io/pvc-protection]
Capacity: 8Gi
Access Modes: RWO
VolumeMode: Filesystem
Used By: sessiondb-0
Events: <none>
---
% kubectl describe pvc data-sessiondb-0
Name: data-sessiondb-0
Namespace: default
StorageClass: standard
Status: Bound
Volume: pvc-6b56b20c-3e56-4a92-9278-794bf6cda4de
Labels: app.kubernetes.io/instance=asdf
app.kubernetes.io/name=sessiondb
role=primary
Annotations: pv.kubernetes.io/bind-completed: yes
pv.kubernetes.io/bound-by-controller: yes
volume.beta.kubernetes.io/storage-provisioner: k8s.io/minikube-hostpath
Finalizers: [kubernetes.io/pvc-protection]
Capacity: 8Gi
Access Modes: RWO
VolumeMode: Filesystem
Used By: sessiondb-0
Events: <none>
cyrill@CyrillsMBP4380 core % kubectl describe pv pvc-6b56b20c-3e56-4a92-9278-794bf6cda4de
Name: pvc-6b56b20c-3e56-4a92-9278-794bf6cda4de
Labels: <none>
Annotations: hostPathProvisionerIdentity: 10bfa079-1086-4a77-849e-7d00de8e34dc
pv.kubernetes.io/provisioned-by: k8s.io/minikube-hostpath
Finalizers: [kubernetes.io/pv-protection]
StorageClass: standard
Status: Bound
Claim: default/data-sessiondb-0
Reclaim Policy: Delete
Access Modes: RWO
VolumeMode: Filesystem
Capacity: 8Gi
Node Affinity: <none>
Message:
Source:
Type: HostPath (bare host directory volume)
Path: /tmp/hostpath-provisioner/default/data-sessiondb-0
HostPathType:
Events: <none>
</code></pre>
<p>EDIT: Add logs with DEBUG level
--> Looking to fix: <code>directory "/bitnami/postgresql/data" is not a database cluster directory</code></p>
<p>EDIT2: Add logs of the init container <code>volumePermissions.enabled</code> and permissions</p>
<p>EDIT3: Ok, so I created a fresh version to compare the old and the new one. I am wondering, why there is such a difference in the files as both were working until one didn't anymore. (During regular business, no upgrades, nothing.)</p>
<p><a href="https://i.stack.imgur.com/eMZTO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eMZTO.jpg" alt="Logs" /></a></p>
| <p>I really hope nobody else runs across this, but finally I found the problem and for once it was not only between the chair and the monitor, but also RTFM was involved.</p>
<p>As mentioned I am using minikube to run my k8s cluster which provides PVs stored on the host disk. Where it is stored you may ask? Exaclty, here: <code>/tmp/hostpath-provisioner/default/data-sessiondb-0/data/</code>. You find the problem? No, I also took some time to figure it out. WHY ON EARTH does minikube use the <code>tmp</code> folder to store <strong>persistant</strong> volume claims?</p>
<p><a href="https://i.stack.imgur.com/4L5oh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4L5oh.png" alt="tmp folder" /></a></p>
<p>This folder gets autom. cleared every now and so on.</p>
<p>SOLUTION: Change the path and DO NOT STORE PVs IN
<code>tmp</code> FOLDERS.</p>
<p>They mention this here: <a href="https://minikube.sigs.k8s.io/docs/handbook/persistent_volumes/#a-note-on-mounts-persistence-and-minikube-hosts" rel="nofollow noreferrer">https://minikube.sigs.k8s.io/docs/handbook/persistent_volumes/#a-note-on-mounts-persistence-and-minikube-hosts</a> and give an example.</p>
<p>But why use the "dangerous" <code>tmp</code> path per default and not, let's say, <code>data</code> without putting a <em>Warning</em> banner there?</p>
<p>Sigh. Closing this question ^^</p>
<p>--> Workaround: <a href="https://github.com/kubernetes/minikube/issues/7511#issuecomment-612099413" rel="nofollow noreferrer">https://github.com/kubernetes/minikube/issues/7511#issuecomment-612099413</a></p>
<hr />
<p>Github issues to this topic:</p>
<ul>
<li><a href="https://github.com/kubernetes/minikube/issues/7511" rel="nofollow noreferrer">https://github.com/kubernetes/minikube/issues/7511</a></li>
<li><a href="https://github.com/kubernetes/minikube/issues/13038" rel="nofollow noreferrer">https://github.com/kubernetes/minikube/issues/13038</a></li>
<li><a href="https://github.com/kubernetes/minikube/issues/3318" rel="nofollow noreferrer">https://github.com/kubernetes/minikube/issues/3318</a></li>
<li><a href="https://github.com/kubernetes/minikube/issues/5144" rel="nofollow noreferrer">https://github.com/kubernetes/minikube/issues/5144</a></li>
</ul>
<p>My Github issue for clarification in the docs: <a href="https://github.com/kubernetes/minikube/issues/13038#issuecomment-981821696" rel="nofollow noreferrer">https://github.com/kubernetes/minikube/issues/13038#issuecomment-981821696</a></p>
|
<p>I see istio is adding <code>x-b3-traceid</code>, <code>x-b3-spanid</code> and other headers to the incoming request when tracing is enabled. But none of them are returned to the caller.</p>
<p>I am able to capture the <code>x-b3-traceid</code> in the log and can find it out in Tempo/Grafana.
I can see the <code>traceid</code> at the istio envoy proxy (sidecar), I am able to access the header using <code>EnvoyFilter</code>.</p>
<p>Can someone let me know where it is filtered?</p>
| <p><strong>TL;DR</strong>
these are the headers so that <code>jaeger</code> or <code>zipkin</code> can track individual requests. This application is responsible for their proper propagation. Additionally, they are <strong>request headers</strong> and <strong>not response header</strong>, so everything works fine.</p>
<hr />
<p>Explanation:</p>
<p>It looks okay. First, let's start with <a href="https://docs.oracle.com/cd/F17999_01/docs.10/SCP/GUID-3DD925E4-A4C9-49F1-A6D8-323DB637056F.htm" rel="nofollow noreferrer">what these requests are</a>:</p>
<pre><code>
Field Name Request/ Response Type Description
x-request-id request The x-request-idheader is used by Envoy to uniquely identify a request as well as perform stable access logging and tracing
x-b3-traceid request The x-b3-traceidHTTP header is used by the Zipkin tracer in Envoy. The TraceId is 64-bit in length and indicates the overall ID of the trace. Every span in a trace shares this ID
x-b3-spanid request The x-b3-spanidHTTP header is used by the Zipkin tracer in Envoy. The SpanId is 64-bit in length and indicates the position of the current operation in the trace tree
x-b3-sampled request The x-b3-sampledHTTP header is used by the Zipkin tracer in Envoy. When the Sampled flag is either not specified or set to 1, the span will be reported to the tracing system
</code></pre>
<p>On the github you can find the question: <a href="https://github.com/Nike-Inc/riposte/issues/54" rel="nofollow noreferrer">What is the usage of X-B3-TraceId, traceId, parentSpanId and spanId ?</a>:</p>
<blockquote>
<p>http headers contain only a small amount of data: IDs and sampling flags these go synchronously with your application requests, and allow the other side to continue the trace. <a href="https://github.com/openzipkin/b3-propagation#overall-process" rel="nofollow noreferrer">https://github.com/openzipkin/b3-propagation#overall-process</a> If zipkin is enabled, details including these IDs and other data like duration send asynchronously to zipkin after a request completes. you can see a diagram about that here under "Example Flow" <a href="http://zipkin.io/pages/architecture.html" rel="nofollow noreferrer">http://zipkin.io/pages/architecture.html</a></p>
</blockquote>
<blockquote>
<blockquote>
<p>X-B3-TraceId is same or different from every call of the same client? different per overall request. each top-level request into your system has</p>
</blockquote>
<p>a different trace id. Each step in that request has a different span id</p>
</blockquote>
<blockquote>
<blockquote>
<p>X-B3-SpanId is not send back to the caller, then how could i set the parent(which show be the X-B3-SpanId of the the present call) of the next call? Here is a response shows the absent of X-B3-SpanId in the header: I don't quite understand. The parent is only used when creating a span.</p>
</blockquote>
<p><strong>The span is created before a request is sent. So, there's no relevance to response headers in span creation.</strong></p>
</blockquote>
<p>In <a href="https://istio.io/latest/docs/tasks/observability/distributed-tracing/overview/" rel="nofollow noreferrer">this doc</a> you can find information about headers from istio site:</p>
<blockquote>
<p>Distributed tracing enables users to track a request through mesh that is distributed across multiple services. This allows a deeper understanding about request latency, serialization and parallelism via visualization.</p>
<p>Istio leverages Envoy’s distributed tracing feature to provide tracing integration out of the box. Specifically, Istio provides options to install various tracing backend and configure proxies to send trace spans to them automatically. See Zipkin, Jaeger and Lightstep task docs about how Istio works with those tracing systems.</p>
</blockquote>
<p>If you want to full understand how it works you should read <a href="https://www.envoyproxy.io/docs/envoy/v1.12.0/intro/arch_overview/observability/tracing" rel="nofollow noreferrer">this envoyproxy documentation</a>:</p>
<blockquote>
<p>Distributed tracing allows developers to obtain visualizations of call flows in large service oriented architectures. It can be invaluable in understanding serialization, parallelism, and sources of latency. Envoy supports three features related to system wide tracing:</p>
<ul>
<li><p><strong>Request ID generation</strong>: Envoy will generate UUIDs when needed and populate the <a href="https://www.envoyproxy.io/docs/envoy/v1.12.0/configuration/http/http_conn_man/headers#config-http-conn-man-headers-x-request-id" rel="nofollow noreferrer">x-request-id</a> HTTP header. Applications can forward the x-request-id header for unified logging as well as tracing.</p>
</li>
<li><p><strong>Client trace ID joining</strong>: The <a href="https://www.envoyproxy.io/docs/envoy/v1.12.0/configuration/http/http_conn_man/headers#config-http-conn-man-headers-x-client-trace-id" rel="nofollow noreferrer">x-client-trace-id</a> header can be used to join untrusted request IDs to the trusted internal <a href="https://www.envoyproxy.io/docs/envoy/v1.12.0/configuration/http/http_conn_man/headers#config-http-conn-man-headers-x-request-id" rel="nofollow noreferrer">x-request-id</a>.</p>
</li>
<li><p><strong>External trace service integration</strong>: Envoy supports pluggable external trace visualization providers, that are divided into two subgroups:</p>
</li>
<li><p>External tracers which are part of the Envoy code base, like <a href="https://lightstep.com/" rel="nofollow noreferrer">LightStep</a>, <a href="https://zipkin.io/" rel="nofollow noreferrer">Zipkin</a> or any Zipkin compatible backends (e.g. <a href="https://github.com/jaegertracing/" rel="nofollow noreferrer">Jaeger</a>), and <a href="https://datadoghq.com/" rel="nofollow noreferrer">Datadog</a>.</p>
</li>
<li><p>External tracers which come as a third party plugin, like <a href="https://www.instana.com/blog/monitoring-envoy-proxy-microservices/" rel="nofollow noreferrer">Instana</a>.</p>
</li>
</ul>
</blockquote>
<p>Answering your question:</p>
<blockquote>
<p>Can someone let me know where it is filtered?</p>
</blockquote>
<p>They do this by default. It is the application (zipkin, jaeger) that is responsible for acting on these headers. Additionally, they are <strong>request headers</strong> and <strong>not response header</strong>, so everything works fine.</p>
|
<p>We're already using <a href="https://hub.tekton.dev/tekton/task/gitlab-set-status" rel="nofollow noreferrer">the <code>gitlab-set-status</code> Task from Tekton Hub</a> to report our Tekton Pipeline's status back into our GitLab instance (here's <a href="https://github.com/jonashackt/tekton-argocd-eks" rel="nofollow noreferrer">our EKS setup & Tekton installment</a> and <a href="https://gitlab.com/jonashackt/microservice-api-spring-boot" rel="nofollow noreferrer">a example project on gitlab.com</a>). Our <a href="https://github.com/jonashackt/tekton-argocd-eks/blob/main/pipelines/pipeline.yml" rel="nofollow noreferrer"><code>pipeline.yml</code></a> looks like this and currently reports the <code>STATE</code> success every time the Tekton Pipeline runs:</p>
<pre><code>apiVersion: tekton.dev/v1beta1
kind: Pipeline
metadata:
name: buildpacks-test-pipeline
spec:
params:
- name: IMAGE
type: string
description: image URL to push
- name: SOURCE_URL
type: string
description: A git repo url where the source code resides.
- name: REPO_PATH_ONLY
type: string
description: GitLab group & repo name only (e.g. jonashackt/microservice-api-spring-boot)
- name: SOURCE_REVISION
description: The branch, tag or SHA to checkout.
default: ""
- name: GITLAB_HOST
type: string
description: Your GitLabs host only (e.g. gitlab.com)
- name: TEKTON_DASHBOARD_HOST
type: string
description: The Tekton dashboard host name only
workspaces:
- name: source-workspace # Directory where application source is located. (REQUIRED)
- name: cache-workspace # Directory where cache is stored (OPTIONAL)
tasks:
- name: fetch-repository # This task fetches a repository from github, using the `git-clone` task you installed
taskRef:
name: git-clone
workspaces:
- name: output
workspace: source-workspace
params:
- name: url
value: "$(params.SOURCE_URL)"
- name: revision
value: "$(params.SOURCE_REVISION)"
- name: subdirectory
value: ""
- name: deleteExisting
value: "true"
- name: buildpacks # This task uses the `buildpacks` task to build the application
taskRef:
name: buildpacks
runAfter:
- fetch-repository
workspaces:
- name: source
workspace: source-workspace
- name: cache
workspace: cache-workspace
params:
- name: APP_IMAGE
value: "$(params.IMAGE)"
- name: BUILDER_IMAGE
value: paketobuildpacks/builder:base # This is the builder we want the task to use (REQUIRED)
- name: report-pipeline-end-to-gitlab
taskRef:
name: "gitlab-set-status"
runAfter:
- buildpacks
params:
- name: "STATE"
value: "success"
- name: "GITLAB_HOST_URL"
value: "$(params.GITLAB_HOST)"
- name: "REPO_FULL_NAME"
value: "$(params.REPO_PATH_ONLY)"
- name: "GITLAB_TOKEN_SECRET_NAME"
value: "gitlab-api-secret"
- name: "GITLAB_TOKEN_SECRET_KEY"
value: "token"
- name: "SHA"
value: "$(params.SOURCE_REVISION)"
- name: "TARGET_URL"
value: "$(params.TEKTON_DASHBOARD_HOST)/#/namespaces/default/pipelineruns/$(context.pipelineRun.name)"
- name: "CONTEXT"
value: "tekton-pipeline"
- name: "DESCRIPTION"
value: "Finished building your commit in Tekton"
</code></pre>
<p>How can we enhance our Tekton Pipeline to report the status correctly and regardless of any failure or success to GitLab?</p>
| <p><a href="https://github.com/tektoncd/pipeline/releases/tag/v0.14.0" rel="nofollow noreferrer">In v0.14 Tekton introduced the so called <code>finally</code> Tasks</a>, which run at the end of every <code>Pipeline</code> - regardless which Task failed or succeeded. <a href="https://tekton.dev/docs/pipelines/pipelines/#adding-finally-to-the-pipeline" rel="nofollow noreferrer">As the docs state</a>:</p>
<blockquote>
<p>finally tasks are guaranteed to be executed in parallel after all PipelineTasks under tasks have completed regardless of success or error.</p>
</blockquote>
<p>In general <code>finally</code> tasks look like this:</p>
<pre class="lang-yaml prettyprint-override"><code>spec:
tasks:
- name: tests
taskRef:
name: integration-test
finally:
- name: cleanup-test
taskRef:
name: cleanup
</code></pre>
<p><strong>But how do we create the corresponding <code>STATE</code> in our <code>gitlab-set-status</code> Task?</strong> With <a href="https://tekton.dev/docs/pipelines/pipelines/#guard-finally-task-execution-using-when-expressions" rel="nofollow noreferrer">using <code>when</code> expressions inside our <code> finally</code> tasks</a> we can run our <code>gitlab-set-status</code> Task based on <a href="https://tekton.dev/docs/pipelines/pipelines/#when-expressions-using-aggregate-execution-status-of-tasks-in-finally-tasks" rel="nofollow noreferrer">the overall Pipeline status (or Aggregate Pipeline status)</a>:</p>
<pre><code>finally:
- name: notify-any-failure # executed only when one or more tasks fail
when:
- input: $(tasks.status)
operator: in
values: ["Failed"]
taskRef:
name: notify-failure
</code></pre>
<p>We grab the <a href="https://tekton.dev/docs/pipelines/pipelines/#using-aggregate-execution-status-of-all-tasks" rel="nofollow noreferrer">Aggregate Execution Status</a> by simply using <code>$(tasks.status)</code>. This variable is stated to have those 4 possible status:</p>
<ul>
<li><code>Succeeded</code> ("all tasks have succeeded")</li>
<li><code>Completed</code> ("all tasks completed successfully including one or more skipped tasks")</li>
</ul>
<p>-> which could be translated into the <code>gitlab-set-status</code> Tasks <code>STATE</code> value <code>success</code>.</p>
<ul>
<li><code>Failed</code> ("one ore more tasks failed")</li>
<li><code>None</code> ("no aggregate execution status available (i.e. none of the above), one or more tasks could be pending/running/cancelled/timedout")</li>
</ul>
<p>-> which could both be translated into the <code>gitlab-set-status</code> Tasks <code>STATE</code> value <code>failed</code>. For <code>None</code> this is only valid, since we're in a <code>finally task</code>, since <code>pending/running</code> could otherwise also mean that a Pipeline is in a good state.</p>
<p>Having 4 states we need to check in our <code>when</code> expressions, do we need to implement a separate finally Task for each of them? No, since luckily the <code>when</code> expressions <a href="https://tekton.dev/docs/pipelines/pipelines/#guard-task-execution-using-when-expressions" rel="nofollow noreferrer">"values is an array of string values."</a>. So we're able to do</p>
<pre><code> when:
- input: $(tasks.status)
operator: in
values: [ "Failed", "None" ]
</code></pre>
<p>and</p>
<pre><code> when:
- input: $(tasks.status)
operator: in
values: [ "Succeeded", "Completed" ]
</code></pre>
<p>Finally this results in our Tekton Pipeline's locking like this (and implementing 2 finally tasks <code>report-pipeline-failed-to-gitlab</code> and <code>report-pipeline-success-to-gitlab</code>):</p>
<pre><code>...
finally:
- name: report-pipeline-failed-to-gitlab
when:
- input: $(tasks.status)
operator: in
values: [ "Failed", "None" ] # see aggregated status https://tekton.dev/docs/pipelines/pipelines/#using-aggregate-execution-status-of-all-tasks
taskRef:
name: "gitlab-set-status"
params:
- name: "STATE"
value: "failed"
- name: "GITLAB_HOST_URL"
value: "$(params.GITLAB_HOST)"
- name: "REPO_FULL_NAME"
value: "$(params.REPO_PATH_ONLY)"
- name: "GITLAB_TOKEN_SECRET_NAME"
value: "gitlab-api-secret"
- name: "GITLAB_TOKEN_SECRET_KEY"
value: "token"
- name: "SHA"
value: "$(params.SOURCE_REVISION)"
- name: "TARGET_URL"
value: "$(params.TEKTON_DASHBOARD_HOST)/#/namespaces/default/pipelineruns/$(context.pipelineRun.name)"
- name: "CONTEXT"
value: "tekton-pipeline"
- name: "DESCRIPTION"
value: "An error occurred building your commit in Tekton"
- name: report-pipeline-success-to-gitlab
when:
- input: $(tasks.status)
operator: in
values: [ "Succeeded", "Completed" ] # see aggregated status https://tekton.dev/docs/pipelines/pipelines/#using-aggregate-execution-status-of-all-tasks
taskRef:
name: "gitlab-set-status"
params:
- name: "STATE"
value: "success"
- name: "GITLAB_HOST_URL"
value: "$(params.GITLAB_HOST)"
- name: "REPO_FULL_NAME"
value: "$(params.REPO_PATH_ONLY)"
- name: "GITLAB_TOKEN_SECRET_NAME"
value: "gitlab-api-secret"
- name: "GITLAB_TOKEN_SECRET_KEY"
value: "token"
- name: "SHA"
value: "$(params.SOURCE_REVISION)"
- name: "TARGET_URL"
value: "$(params.TEKTON_DASHBOARD_HOST)/#/namespaces/default/pipelineruns/$(context.pipelineRun.name)"
- name: "CONTEXT"
value: "tekton-pipeline"
- name: "DESCRIPTION"
value: "Finished building your commit in Tekton"
</code></pre>
<p>Executing our Tekton Pipeline should now be reported correctly to our GitLab. Failures look like this:</p>
<p><a href="https://i.stack.imgur.com/SSxKP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SSxKP.png" alt="enter image description here" /></a></p>
<p>Succeeded Pipelines look like this:</p>
<p><a href="https://i.stack.imgur.com/c03It.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c03It.png" alt="enter image description here" /></a></p>
|
<p>I'm trying to configure EFK stack in my local minikube setup. I have followed <a href="https://www.metricfire.com/blog/logging-for-kubernetes-fluentd-and-elasticsearch/" rel="nofollow noreferrer">this tutorial</a>.</p>
<p>Everything is working fine (I can see all my console logs in kibana and Elasticsearch). But I have another requirement. I have Node.js application which is logs as files to custom path <code>/var/log/services/dev</code> inside the pod.</p>
<p>File Tree:</p>
<pre><code>/var/log/services/dev/# ls -l
total 36
-rw-r--r-- 1 root root 28196 Nov 27 18:09 carts-service-dev.log.2021-11-27T18.1
-rw-r--r-- 1 root root 4483 Nov 27 18:09 carts-service-dev.log.2021-11-27T18
</code></pre>
<p>How to configure my Fluentd to read all my console logs and also read logs from the custom path configured?</p>
<p>My App Deployment File:</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: carts
spec:
replicas: 1
selector:
matchLabels:
app: carts
template:
metadata:
labels:
app: carts
spec:
containers:
- name: app
image: carts-service
resources:
limits:
memory: "1024Mi"
cpu: "500m"
ports:
- containerPort: 4000
</code></pre>
<p>My Fluentd DaemonSet File:</p>
<pre><code>apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluentd
namespace: kube-system
labels:
k8s-app: fluentd-logging
version: v1
spec:
selector:
matchLabels:
k8s-app: fluentd-logging
version: v1
template:
metadata:
labels:
k8s-app: fluentd-logging
version: v1
spec:
terminationGracePeriodSeconds: 30
volumes:
- name: varlog
hostPath:
path: /var/log
- name: varlibdockercontainers
hostPath:
path: /var/lib/docker/containers
tolerations:
- key: node-role.kubernetes.io/master
effect: NoSchedule
containers:
- name: fluentd
image: fluent/fluentd-kubernetes-daemonset:v1-debian-elasticsearch
volumeMounts:
- name: varlog
mountPath: /var/log
- name: varlibdockercontainers
mountPath: /var/lib/docker/containers
readOnly: true
resources:
limits:
memory: 200Mi
requests:
cpu: 100m
memory: 200Mi
env:
- name: FLUENT_ELASTICSEARCH_HOST
value: "elasticsearch.default"
- name: FLUENT_ELASTICSEARCH_PORT
value: "9200"
</code></pre>
<p>I do know that log files written into custom path <code>/var/log/services/dev</code> will be deleted if pod crashes. So I have to use persistent volume to mount this path.</p>
<p>But I lack the experience of how to create persistent volume for that path and also link Fluentd to read from it.</p>
<p>Thanks in advance.</p>
| <p>If a pod crashes, all logs still will be accessible in <code>efk</code>. No need to add a persistent volume to the pod with your application only for storing log file.</p>
<p>Main question is how to get logs from this file. There are <strong>two main approaches</strong> which are suggested and based on kubernetes documentation:</p>
<ol>
<li><p><strong>Use a sidecar container</strong>.</p>
<p>Containers in pod have the same file system and <code>sidecar</code> container will be streaming logs from file to <code>stdout</code> and/or <code>stderr</code> (depends on implementation) and after logs will be picked up by kubelet.</p>
<p>Please find <a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/#streaming-sidecar-container" rel="nofollow noreferrer">streaming sidecar container</a> and example how it works.</p>
</li>
<li><p><strong>Use a sidecar container with a logging agent</strong>.</p>
<p>Please find <a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/#sidecar-container-with-logging-agent" rel="nofollow noreferrer">Sidecar container with a logging agent</a> and configuration example using <code>fluentd</code>. In this case logs will be collected by <code>fluentd</code> and they won't be available by <code>kubectl logs</code> commands since <code>kubelet</code> is not responsible for these logs.</p>
</li>
</ol>
|
<p>Running on Kubernetes v1.20</p>
<p>I have a startup probe configured and a liveness probe. On the first start of the container, the startup probe is executed until the liveness probe takes over (as documented). However, it seems if the liveness probe fails and the container restarts, the startup probe is not executed again. Is this intended behavior? I cannot find this documented anywhere.</p>
<p>To reproduce this issue, I'm running the following container definition (relevant parts only):</p>
<pre><code>containers:
- args:
- /bin/sh
- -c
- touch /tmp/alive; sleep 10000
image: busybox
livenessProbe:
exec:
command:
- /bin/sh
- -c
- touch /tmp/liveness; test -f /tmp/alive
failureThreshold: 3
initialDelaySeconds: 10
periodSeconds: 2
successThreshold: 1
timeoutSeconds: 2
startupProbe:
exec:
command:
- touch
- /tmp/startup
failureThreshold: 3
periodSeconds: 2
successThreshold: 1
timeoutSeconds: 2
</code></pre>
<p>So if the liveness probe runs, it creates /tmp/liveness. If the startup probe runs, it creates /tmp/startup. You can simulate the liveness check failing by deleting /tmp/alive.</p>
<p>On first startup:</p>
<pre><code>$ ls /tmp/
alive liveness startup
</code></pre>
<p>After <code>rm /tmp/alive</code>, the liveness check fails and the container is restarted. Then, in the new container:</p>
<pre><code>$ ls /tmp/
alive liveness
</code></pre>
<p>So it seems the startup probe is not executed anymore.</p>
| <p>Might want to check if your K8 version is the one affected by this issue:</p>
<p><a href="https://github.com/kubernetes/kubernetes/issues/101064" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/issues/101064</a></p>
<p>or</p>
<p><a href="https://github.com/kubernetes/kubernetes/issues/102230" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/issues/102230</a></p>
|
<p>I'm using fluent-bit to collect logs and pass it to fluentd for processing in a Kubernetes environment. Fluent-bit instances are controlled by DaemonSet and read logs from docker containers.</p>
<pre><code> [INPUT]
Name tail
Path /var/log/containers/*.log
Parser docker
Tag kube.*
Mem_Buf_Limit 5MB
Skip_Long_Lines On
</code></pre>
<p>There is a fluent-bit service also running</p>
<pre><code>Name: monitoring-fluent-bit-dips
Namespace: dips
Labels: app.kubernetes.io/instance=monitoring
app.kubernetes.io/managed-by=Helm
app.kubernetes.io/name=fluent-bit-dips
app.kubernetes.io/version=1.8.10
helm.sh/chart=fluent-bit-0.19.6
Annotations: meta.helm.sh/release-name: monitoring
meta.helm.sh/release-namespace: dips
Selector: app.kubernetes.io/instance=monitoring,app.kubernetes.io/name=fluent-bit-dips
Type: ClusterIP
IP Families: <none>
IP: 10.43.72.32
IPs: <none>
Port: http 2020/TCP
TargetPort: http/TCP
Endpoints: 10.42.0.144:2020,10.42.1.155:2020,10.42.2.186:2020 + 1 more...
Session Affinity: None
Events: <none>
</code></pre>
<p>Fluentd service description is as below</p>
<pre><code>Name: monitoring-logservice
Namespace: dips
Labels: app.kubernetes.io/instance=monitoring
app.kubernetes.io/managed-by=Helm
app.kubernetes.io/name=logservice
app.kubernetes.io/version=1.9
helm.sh/chart=logservice-0.1.2
Annotations: meta.helm.sh/release-name: monitoring
meta.helm.sh/release-namespace: dips
Selector: app.kubernetes.io/instance=monitoring,app.kubernetes.io/name=logservice
Type: ClusterIP
IP Families: <none>
IP: 10.43.44.254
IPs: <none>
Port: http 24224/TCP
TargetPort: http/TCP
Endpoints: 10.42.0.143:24224
Session Affinity: None
Events: <none>
</code></pre>
<p>But fluent-bit logs doesn't reach fluentd and getting following error</p>
<pre><code>[error] [upstream] connection #81 to monitoring-fluent-bit-dips:24224 timed out after 10 seconds
</code></pre>
<p>I tried several things like;</p>
<ul>
<li>re-deploying fluent-bit pods</li>
<li>re-deploy fluentd pod</li>
<li>Upgrade fluent-bit version from 1.7.3 to 1.8.10</li>
</ul>
<p>This is an Kubernetes environment where fluent-bit able to communicate with fluentd in the very earlier stage of deployment. Apart from that, this same fluent versions is working when I deploy locally with docker-desktop environment.</p>
<p>My guesses are</p>
<ul>
<li>fluent-bit cannot manage the amount of log process</li>
<li>fluent services are unable to communicate once the services are restarted</li>
</ul>
<p>Anyone having any experience in this or has any idea how to debug this issue more deeper?</p>
<hr />
<p>Updated following with fluentd running pod description</p>
<pre><code>Name: monitoring-logservice-5b8864ffd8-gfpzc
Namespace: dips
Priority: 0
Node: sl-sy-k3s-01/10.16.1.99
Start Time: Mon, 29 Nov 2021 13:09:13 +0530
Labels: app.kubernetes.io/instance=monitoring
app.kubernetes.io/name=logservice
pod-template-hash=5b8864ffd8
Annotations: kubectl.kubernetes.io/restartedAt: 2021-11-29T12:37:23+05:30
Status: Running
IP: 10.42.0.143
IPs:
IP: 10.42.0.143
Controlled By: ReplicaSet/monitoring-logservice-5b8864ffd8
Containers:
logservice:
Container ID: containerd://102483a7647fd2f10bead187eddf69aa4fad72051d6602dd171e1a373d4209d7
Image: our.private.repo/dips/logservice/splunk:1.9
Image ID: our.private.repo/dips/logservice/splunk@sha256:531f15f523a251b93dc8a25056f05c0c7bb428241531485a22b94896974e17e8
Ports: 24231/TCP, 24224/TCP
Host Ports: 0/TCP, 0/TCP
State: Running
Started: Mon, 29 Nov 2021 13:09:14 +0530
Ready: True
Restart Count: 0
Liveness: exec [/bin/healthcheck.sh] delay=0s timeout=1s period=10s #success=1 #failure=3
Readiness: exec [/bin/healthcheck.sh] delay=0s timeout=1s period=10s #success=1 #failure=3
Environment:
SOME_ENV_VARS
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from monitoring-logservice-token-g9kwt (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
monitoring-logservice-token-g9kwt:
Type: Secret (a volume populated by a Secret)
SecretName: monitoring-logservice-token-g9kwt
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events: <none>
</code></pre>
| <p>Try change your fluent-bit config that points to fluentd service as <strong>monitoring-logservice.dips:24224</strong></p>
|
<p>I have 1 master and 2 nodes running and kube-proxy to debug.</p>
<pre><code>kube-m1:/$ kubectl get pod -n kube-system kube-proxy-tmt58
NAME READY STATUS RESTARTS AGE
kube-proxy-tmt58 1/1 Running 6 439d
</code></pre>
<p>How can I specify a namespace to get <code>kubectl logs</code> to debug a pod?</p>
<pre><code>kube-m1:/$ kubectl logs kube-proxy-tmt58
Error from server (NotFound): pods "kube-proxy-tmt58" not found
</code></pre>
<p>I am new in kubernetes so, also would be great and very helpful to get some good and working guides or materials about pods and nodes debugging :)</p>
<p>Thanks a lot.</p>
| <p>Just like you did it to get a pod, to specify a namespace you can pass <code>-n</code> | <code>--namespace</code> flag, so your command would look like</p>
<pre><code>kubectl logs kube-proxy-tmt58 -n kube-system
</code></pre>
|
<p>We have below chart structure in helm which can deploy 'a microservice' to our k8s cluster</p>
<pre><code>service-chart
|_templates
|_deployment.yaml
|_Ingress.yaml
|_service.yaml
|_Chart.yaml
|_valueBase.yaml
|_valueForService1.yaml
|_valueForService2.yaml
..
..
|_valueForService{n}.yaml
</code></pre>
<p><code>valueBase.yaml</code> contains default values for a service (for eg. limits, replicas etc)</p>
<pre><code>global:
namespace: teamname
environment: staging
limits:
memory: "500Mi"
cpu: "300m"
deployments:
replicas: 1
probes:
path: "/"
</code></pre>
<p>and <code>valueForService1.yaml</code> file contains values overridden for a specific service</p>
<pre><code>app:
name: "service1"
image:
name: "service1"
version: "2021.11.xxx"
port: 50001
deployments:
replicas: 3
</code></pre>
<p>All of above services follow exactly same structure and create similar resources i.e. a service, a pod and an ingress.
we deploy an individual service as</p>
<pre><code>helm upgrade --install -f valueBase.yaml -f valueForService1.yaml service1 .
</code></pre>
<p>But problem is we have 50 of these services.
and we would want to install all of them together instead of running 50 commands back to back.
Also would like to have some release co-ordination in between releasing multiple services.
for eg. release service1 before releasing service2.</p>
<p>I know we can do this in one command with 50 <code>-f</code> parameters in it but that's not the kind of solution I am here for.</p>
<p>How can we package them properly so we can</p>
<ul>
<li>release all services at once when we want to.</li>
<li>release an individual service</li>
<li>release them as group of service for eg. group1 consist of service1, service2 and service3</li>
<li>release orchestration for eg. release service1 then service2 then service3</li>
</ul>
<p>All suggestions welcomed. Feel free to ask for more details.</p>
<p>Note: We tried using sub-chart but it doesn't appear to be solved by using sub-charts.
We just have lots of services with similar structure.
but I might have used sub charts completely wrong.</p>
| <p>What you're looking for is <a href="https://github.com/roboll/helmfile" rel="nofollow noreferrer"><code>helmfile</code></a></p>
<ol>
<li><p>Store your base chart and services values in the same folder.</p>
</li>
<li><p>Create <code>helmfile.yml</code>.</p>
<pre><code>releases:
- name: service1
labels:
app: service1
group: group1
chart: charts/baseChart
values:
- valueBase.yaml
- valueForService1.yaml
- fullnameOverride: service1
- name: service2
labels:
app: service2
group: group1
chart: charts/baseChart
values:
- valueBase.yaml
- valueForService2.yaml
- fullnameOverride: service2
needs:
- service1
</code></pre>
<p>Each release in the <em><strong>releases</strong></em> list is a helm release definition. You can control installation order with the <a href="https://github.com/roboll/helmfile/tree/v0.142.0#dag-aware-installationdeletion-ordering-with-needs" rel="nofollow noreferrer"><code>needs</code></a> keyword.</p>
</li>
<li><p>Now your folder looks something like this</p>
<pre><code>.
├── charts/
│ └── baseChart/
├── helmfile.yml
├── valueBase.yml
├── valueForService1.yml
└── valueForService2.yml
</code></pre>
<p>and you're ready to run helmfile commands</p>
</li>
</ol>
<ul>
<li><p><code>helmfile -n <namespace> apply</code> will release all services at once</p>
</li>
<li><p><code>helmfile -n <namespace> -l app=service1 apply</code> will release an individual service with the <em><strong>app: service</strong></em> label</p>
</li>
<li><p><code>helmfile -n <namespace> -l group=group1 apply</code> will release all services with the <em><strong>group: group1</strong></em> label</p>
</li>
</ul>
|
<p>I'm trying to start minikube on a Mac M1 (macOs Monterey V12.0.1) after installing minikube with homebrew (<code>brew install minikube</code>) but I am getting an error after running <code>minikube start</code>.</p>
<p>The error in the logs is this one:</p>
<pre><code>💢 initialization failed, will try again: wait: /bin/bash -c "sudo env PATH="/var/lib/minikube/binaries/v1.22.3:$PATH" kubeadm init --config /var/tmp/minikube/kubeadm.yaml --ignore-preflight-errors=DirAvailable--etc-kubernetes-manifests,DirAvailable--var-lib-minikube,DirAvailable--var-lib-minikube-etcd,FileAvailable--etc-kubernetes-manifests-kube-scheduler.yaml,FileAvailable--etc-kubernetes-manifests-kube-apiserver.yaml,FileAvailable--etc-kubernetes-manifests-kube-controller-manager.yaml,FileAvailable--etc-kubernetes-manifests-etcd.yaml,Port-10250,Swap,Mem,SystemVerification,FileContent--proc-sys-net-bridge-bridge-nf-call-iptables": Process exited with status 1
stdout:
[init] Using Kubernetes version: v1.22.3
[preflight] Running pre-flight checks
stderr:
[WARNING Swap]: running with swap on is not supported. Please disable swap
[WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
error execution phase preflight: [preflight] Some fatal errors occurred:
[ERROR KubeletVersion]: couldn't get kubelet version: cannot execute 'kubelet --version': exit status 255
[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`
To see the stack trace of this error execute with --v=5 or higher
💣 Error starting cluster: wait: /bin/bash -c "sudo env PATH="/var/lib/minikube/binaries/v1.22.3:$PATH" kubeadm init --config /var/tmp/minikube/kubeadm.yaml --ignore-preflight-errors=DirAvailable--etc-kubernetes-manifests,DirAvailable--var-lib-minikube,DirAvailable--var-lib-minikube-etcd,FileAvailable--etc-kubernetes-manifests-kube-scheduler.yaml,FileAvailable--etc-kubernetes-manifests-kube-apiserver.yaml,FileAvailable--etc-kubernetes-manifests-kube-controller-manager.yaml,FileAvailable--etc-kubernetes-manifests-etcd.yaml,Port-10250,Swap,Mem,SystemVerification,FileContent--proc-sys-net-bridge-bridge-nf-call-iptables": Process exited with status 1
stdout:
[init] Using Kubernetes version: v1.22.3
[preflight] Running pre-flight checks
stderr:
[WARNING Swap]: running with swap on is not supported. Please disable swap
[WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
error execution phase preflight: [preflight] Some fatal errors occurred:
[ERROR KubeletVersion]: couldn't get kubelet version: cannot execute 'kubelet --version': exit status 255
[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`
To see the stack trace of this error execute with --v=5 or higher
╭───────────────────────────────────────────────────────────────────────────────────────────╮
│ │
│ 😿 If the above advice does not help, please let us know: │
│ 👉 https://github.com/kubernetes/minikube/issues/new/choose │
│ │
│ Please run `minikube logs --file=logs.txt` and attach logs.txt to the GitHub issue. │
│ │
╰───────────────────────────────────────────────────────────────────────────────────────────╯
❌ Exiting due to GUEST_START: wait: /bin/bash -c "sudo env PATH="/var/lib/minikube/binaries/v1.22.3:$PATH" kubeadm init --config /var/tmp/minikube/kubeadm.yaml --ignore-preflight-errors=DirAvailable--etc-kubernetes-manifests,DirAvailable--var-lib-minikube,DirAvailable--var-lib-minikube-etcd,FileAvailable--etc-kubernetes-manifests-kube-scheduler.yaml,FileAvailable--etc-kubernetes-manifests-kube-apiserver.yaml,FileAvailable--etc-kubernetes-manifests-kube-controller-manager.yaml,FileAvailable--etc-kubernetes-manifests-etcd.yaml,Port-10250,Swap,Mem,SystemVerification,FileContent--proc-sys-net-bridge-bridge-nf-call-iptables": Process exited with status 1
stdout:
[init] Using Kubernetes version: v1.22.3
[preflight] Running pre-flight checks
stderr:
[WARNING Swap]: running with swap on is not supported. Please disable swap
[WARNING Service-Kubelet]: kubelet service is not enabled, please run 'systemctl enable kubelet.service'
error execution phase preflight: [preflight] Some fatal errors occurred:
[ERROR KubeletVersion]: couldn't get kubelet version: cannot execute 'kubelet --version': exit status 255
[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`
To see the stack trace of this error execute with --v=5 or higher
╭───────────────────────────────────────────────────────────────────────────────────────────╮
│ │
│ 😿 If the above advice does not help, please let us know: │
│ 👉 https://github.com/kubernetes/minikube/issues/new/choose │
│ │
│ Please run `minikube logs --file=logs.txt` and attach logs.txt to the GitHub issue. │
│ │
╰───────────────────────────────────────────────────────────────────────────────────────────╯
</code></pre>
<p>I have tried enabling kubelet.service by running <code>sysctl enable kubelet.service</code> but didn't change anything. I have also kubeclt version <code>1.22</code> installed.</p>
| <p>I was able to find the solution to my problem, although, I'm not really sure what was the main issue, it seems that it was related to old configurations in the <code>.minikube</code> folder in the users' home directory.</p>
<p>To fix it, first I had to enabled Kubernetes in docker desktop, and then I had to stop and delete minikube cluster, and finally delete the directory. Then running the command again was successful.</p>
<p>To fix:</p>
<pre class="lang-sh prettyprint-override"><code>$ minikube stop
$ minikube delete
$ rm -rf ~/.minikube/
$ minikube start
😄 minikube v1.24.0 on Darwin 12.0.1 (arm64)
✨ Automatically selected the docker driver
👍 Starting control plane node minikube in cluster minikube
🚜 Pulling base image ...
🔥 Creating docker container (CPUs=2, Memory=1988MB) ...
> kubectl.sha256: 64 B / 64 B [--------------------------] 100.00% ? p/s 0s
> kubelet.sha256: 64 B / 64 B [--------------------------] 100.00% ? p/s 0s
> kubeadm.sha256: 64 B / 64 B [--------------------------] 100.00% ? p/s 0s
> kubeadm: 40.50 MiB / 40.50 MiB [-------------] 100.00% 29.75 MiB p/s 1.6s
> kubectl: 41.44 MiB / 41.44 MiB [-------------] 100.00% 21.39 MiB p/s 2.1s
> kubelet: 107.26 MiB / 107.26 MiB [-----------] 100.00% 27.70 MiB p/s 4.1s
▪ Generating certificates and keys ...
▪ Booting up control plane ...
▪ Configuring RBAC rules ...
🔎 Verifying Kubernetes components...
▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟 Enabled addons: storage-provisioner, default-storageclass
🏄 Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default
</code></pre>
|
<p>I just lost access to my k3s.</p>
<p>I had the certs check this week to if if they had been auto-updated... and it seen so:</p>
<pre><code>[root@vmpkube001 tls]# for crt in *.crt; do printf '%s: %s\n' "$(date --date="$(openssl x509 -enddate -noout -in "$crt"|cut -d= -f 2)" --iso-8601)" "$crt"; done | sort
2021-09-18: client-admin.crt
2021-09-18: client-auth-proxy.crt
2021-09-18: client-cloud-controller.crt
2021-09-18: client-controller.crt
2021-09-18: client-k3s-controller.crt
2021-09-18: client-kube-apiserver.crt
2021-09-18: client-kube-proxy.crt
2021-09-18: client-scheduler.crt
2021-09-18: serving-kube-apiserver.crt
2029-11-03: client-ca.crt
2029-11-03: request-header-ca.crt
2029-11-03: server-ca.crt
</code></pre>
<p>but the cli is broken:
<a href="https://i.stack.imgur.com/Y3fRC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y3fRC.png" alt="image" /></a></p>
<p>Same goes to the dashboard:</p>
<p><a href="https://i.stack.imgur.com/hUQuO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hUQuO.png" alt="image" /></a></p>
<p>The cluster "age" was about 380~something days.
I am running a "v1.18.12+k3s1" in a centos7 cluster.</p>
<p>I change the date on the server to be able to execute kubectl again...
<a href="https://i.stack.imgur.com/s3dJS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s3dJS.png" alt="enter image description here" /></a>
The secrets are wrong... how to update this?</p>
<p>Node logs:</p>
<pre><code>Nov 18 16:34:17 pmpnode001.agrotis.local k3s[6089]: time="2020-11-18T16:34:17.400604478-03:00" level=error msg="server https://127.0.0.1:33684/cacerts is not trusted: Get https://127.0.0.1:33684/cacerts: x509: certificate has expired or is not yet valid"
</code></pre>
<p>Not only that but every case of this problem in the internet says somethings about kubeadm alpha certs. There is no kubeadm, and the only "alpha" feature i have in kubeclt is debug.</p>
| <p>To ignore this error, follow these steps:</p>
<p><strong>Step 1. Stop k3s</strong></p>
<pre><code>systemctl stop k3s.service
</code></pre>
<p><strong>Step 2. Stop time sync</strong></p>
<pre><code>hwclock --debug
timedatectl set-ntp 0
systemctl stop ntp.service
systemctl status systemd-timesyncd.service
</code></pre>
<p><strong>Step 3. Update date to <90 days from expiration</strong></p>
<pre><code>date $(date "+%m%d%H%M%Y" --date="90 days ago")
</code></pre>
<p><strong>Step 4. Restart k3s</strong></p>
<pre><code>systemctl start k3s.service
</code></pre>
<p>Just run this to test cluster!</p>
<pre><code>kubectl get nodes
</code></pre>
|
<p>Here is my values.yaml file:</p>
<pre><code>options:
collection: "myCollection"
ttl: 100800
autoReconnect: true
reconnectTries: 3
reconnectInterval: 5
</code></pre>
<p>Now I'm trying to convert it into JSON in my configMap like this:</p>
<pre><code>options: {
{{- range $key, $val := .Values.options }}
{{ $key }}: {{ $val | quote }},
{{- end }}
}
</code></pre>
<p>But I need to eliminate last comma in JSON so I'm trying to add a counter:</p>
<pre><code>options: {
{{ $c := 0 | int }}
{{- range $key, $val := .Values.options }}
{{ if ne $c 0 }},{{ end }}
{{- $key }}: {{ $val | quote }}
{{ $c := $c add 1 }}
{{- end }}
}
</code></pre>
<p>But I'm getting following error for helm template ... command:</p>
<pre><code>at <$c>: can't give argument to non-function $c
</code></pre>
<p>So what am I doing wrong?</p>
| <p>The simplest way to increment the counter in your case would be to replace</p>
<pre><code>{{ $c := $c add 1 }}
</code></pre>
<p>with</p>
<pre><code>{{ $c = add1 $c }}
</code></pre>
|
<pre><code> kubectl cp namespace/podname:/path/target .
</code></pre>
<p>If I use the instructed command from kubernetes guide, it only copies the contents inside the <code>target</code> directory and omits <code>target</code> itself.<br />
I don't want to use <code>mkdir</code> every time I need to copy.<br />
What's the option?</p>
| <p>Try <code>kubectl cp namespace/podname:/path/target target</code>. Note specify "./target" will receive a warning: "tar: removing leading '/' from member names". Also, ensure your image have <code>tar</code> command or <code>kubectl cp</code> can fail.</p>
|
<p>I am trying to deploy an ASP.NET Core Web API service that receives messages in Service Bus using Docker / Azure Kubernetes, but am having trouble with the port blocked.</p>
<p>Here is my deployment files:</p>
<p><strong>Dockerfile</strong></p>
<pre><code>FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 8004
EXPOSE 5671
EXPOSE 5672
ENV ASPNETCORE_URLS=http://+:8004
ENTRYPOINT ["dotnet", "MyTest.dll"]
</code></pre>
<p><strong>Deployment.yml</strong></p>
<p><a href="https://i.stack.imgur.com/DRFnb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DRFnb.png" alt="enter image description here" /></a></p>
<p><strong>Service.yaml</strong></p>
<p><a href="https://i.stack.imgur.com/EPIUW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EPIUW.png" alt="enter image description here" /></a></p>
<p>Seems it is all that is needed? But it still cannot access Service Bus.</p>
| <p>Thank you <a href="https://stackoverflow.com/users/10008173/david-maze">David Maze</a>. Posting your suggestion as an answer to help other community members.</p>
<blockquote>
<p>You seem to have included two PNG files in place of your YAML files. Those aren't searchable or runnable; <code>kubectl apply -f</code> will just complain if I try to run it</p>
</blockquote>
<blockquote>
<p>(If you're running the RabbitMQ broker in a separate StatefulSet, you don't need to declare anywhere that you're making outbound connections to it; you do not need Dockerfile <code>EXPOSE</code> directives or to mention port 5672 in the Kubernetes YAML anywhere.)</p>
</blockquote>
<p>You can refer to <a href="https://stackoverflow.com/questions/35397430/rabbitmq-cluster-setup-in-kubernetes">Rabbitmq cluster setup in Kubernetes</a></p>
|
<p>Since I'm developing on an M1 mac, my Docker builds will build ARM. I want to build x86_64 images which I know I can build with the <code>--platform</code> flag but I want to do that with my Skaffold configuration.</p>
| <p>Thanks to @p10l putting me on the right track, I was able to figure it out. Skaffold can't set the platform using the Docker Engine API, so we need to pass <code>--platform=linux/x86_64</code> to the command line by setting <code>useDockerCLI</code> to <code>true</code> and adding <code>cliFlags</code> to our Docker configuration.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: skaffold/v2beta26
kind: Config
build:
# ... other unrelated config ...
artifacts:
- image: my-image
context: ./
docker:
cliFlags:
- --platform=linux/x86_64
local:
useDockerCLI: true # the only way to set platform is with cliFlags so we need to enable the Docker CLI
</code></pre>
|
<p>By using the reference of <a href="https://learn.microsoft.com/en-us/azure/aks/csi-secrets-store-nginx-tls" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/aks/csi-secrets-store-nginx-tls</a> this document, I'm trying to fetch the TLS secrets from AKV to AKS pods.
Initially I created and configured <strong>CSI driver configuration</strong> with using <strong>User Assigned Managed Identity</strong>.</p>
<p>I have performed the following steps:</p>
<ul>
<li>Create AKS Cluster with 1 nodepool.</li>
<li>Create AKV.</li>
<li>Created user assigned managed identity and assign it to the nodepool i.e. to the VMSS created for AKS.</li>
<li>Installed CSI Driver helm chart in AKS's <strong>"kube-system"</strong> namespace. and completed all the requirement to perform this operations.</li>
<li>Created the TLS certificate and key.</li>
<li>By using TLS certificate and key, created .pfx file.</li>
<li>Uploaded that .pfx file in the AKV certificates named as <strong>"ingresscert"</strong>.</li>
<li>Created new namespace in AKS named as "ingress-test".</li>
<li>Deployed secretProviderClass in that namespace are as follows.:</li>
</ul>
<pre><code>apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
name: azure-tls
spec:
provider: azure
secretObjects: # secretObjects defines the desired state of synced K8s secret objects
- secretName: ingress-tls-csi
type: kubernetes.io/tls
data:
- objectName: ingresscert
key: tls.key
- objectName: ingresscert
key: tls.crt
parameters:
usePodIdentity: "false"
useVMManagedIdentity: "true"
userAssignedIdentityID: "7*******-****-****-****-***********1"
keyvaultName: "*****-*****-kv" # the name of the AKV instance
objects: |
array:
- |
objectName: ingresscert
objectType: secret
tenantId: "e*******-****-****-****-***********f" # the tenant ID of the AKV instance
</code></pre>
<ul>
<li>Deployed the <strong>nginx-ingress-controller</strong> helm chart in the same namespace, where certificates are binded with application.</li>
<li>Deployed the Busy Box deployment are as follows:</li>
</ul>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: busybox-one
labels:
app: busybox-one
spec:
replicas: 1
selector:
matchLabels:
app: busybox-one
template:
metadata:
labels:
app: busybox-one
spec:
containers:
- name: busybox
image: k8s.gcr.io/e2e-test-images/busybox:1.29-1
command:
- "/bin/sleep"
- "10000"
volumeMounts:
- name: secrets-store-inline
mountPath: "/mnt/secrets-store"
readOnly: true
volumes:
- name: secrets-store-inline
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes:
secretProviderClass: "azure-tls"
---
apiVersion: v1
kind: Service
metadata:
name: busybox-one
spec:
type: ClusterIP
ports:
- port: 80
selector:
app: busybox-one
</code></pre>
<ul>
<li>Check secret is created or not by using command</li>
</ul>
<pre><code>kubectl get secret -n <namespaceName>
</code></pre>
<p><strong>One thing to notice here is, if I attach shell with the busy box pod and go to the mount path which I provided to mount secrets I have seen that secrets are successfully fetched there. But this secrets are not showing in the AKS's secret list.</strong></p>
<p>I have troubleshooted all the AKS,KV and manifest files but not found anything.
IF there is anything I have missed or anyone has solution for this please let me know.</p>
<p>Thanks in advance..!!!</p>
| <p>i added this as a new answer, bcs the formatting was bad in the comments:</p>
<p>As you are using the Helm chart, you have to activate the secret sync in the <code>values.yaml</code> of the Helm Chart:</p>
<pre><code>secrets-store-csi-driver:
syncSecret:
enabled: true
</code></pre>
<p>I would still recommend to use the <code>csi-secrets-store-provider-azure</code> as AKS Addon instead of the Helm-Chart</p>
|
<p>I have a pod that exposes a port (Server). Other pods (Clients) can communicate with it.</p>
<p>The server can find remote IP and port on a socket (when the client connects to it). I am looking for a way to get the client's pod name (from its IP and port).</p>
<p>I saw a bunch of questions/answers about getting pod names via kubectl. However, I am not sure whether I can do kubectl from within a cluster itself.</p>
<p>I am trying to figure out what is available for something running on the cluster. It's ok if it requires some special privileges. It's more complicated if it requires authentication.</p>
| <p>List all the Pods with the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#list-pod-v1-core" rel="nofollow noreferrer"><em>List Pods</em></a> API operation and parse the JSON response for the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#podstatus-v1-core" rel="nofollow noreferrer"><code>podIP</code></a> field (e.g. with <a href="https://stedolan.github.io/jq/" rel="nofollow noreferrer">jq</a> or some other JSON parsing tool) to find the JSON object of the Pod that has your desired IP address. Then, extract the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#pod-v1-core" rel="nofollow noreferrer"><code>metadata.name</code></a> field from this JSON object to get the name of the Pod.</p>
<p>You can do this by either directly using the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/" rel="nofollow noreferrer">Kubernetes API</a> (e.g. with curl) or with kubectl (e.g. <code>kubectl get pods -o json | jq ...</code>). In any case, you must include in this request the <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/" rel="nofollow noreferrer">ServiceAccount token</a> of the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#serviceaccount-v1-core" rel="nofollow noreferrer">ServiceAccount</a> used by the Pod from which you are issuing the request (if you use the Kubernetes API directly, as a Bearer token in the <code>Authorization</code> header, and if you use kubectl with the <code>--token</code> command-line flag).</p>
<p>Regarding <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/" rel="nofollow noreferrer">authorisation</a>, you need a <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#role-v1-rbac-authorization-k8s-io" rel="nofollow noreferrer">Role</a> allowing the <code>list</code> verb on the <code>pods</code> resource and a <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#rolebinding-v1-rbac-authorization-k8s-io" rel="nofollow noreferrer">RoleBinding</a> that binds this Role to the ServiceAccount that your Pod is using (by default, Pods use a ServiceAccount named <code>default</code> in their namespace, but you can specify a custom ServiceAccount with the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#podspec-v1-core" rel="nofollow noreferrer"><code>serviceAccountName</code></a> field of the Pod).</p>
|
<p>We are bringing up a Cassandra cluster, using k8ssandra helm chart, it exposes several services, our client applications are using the datastax Java-Driver and running at the same k8s cluster as the Cassandra cluster (this is testing phase)</p>
<pre><code>CqlSessionBuilder builder = CqlSession.builder();
</code></pre>
<p>What is the recommended way to connect the application (via the Driver) to Cassandra?</p>
<p>Adding all nodes?</p>
<pre><code>for (String node :nodes) {
builder.addContactPoint(new InetSocketAddress(node, 9042));
}
</code></pre>
<p>Adding just the service address?</p>
<pre><code> builder.addContactPoint(new InetSocketAddress(service-dns-name , 9042))
</code></pre>
<p>Adding the service address as unresolved? (would that even work?)</p>
<pre><code> builder.addContactPoint(InetSocketAddress.createUnresolved(service-dns-name , 9042))
</code></pre>
| <p>The k8ssandra Helm chart deploys a CassandraDatacenter object and cass-operator in addition to a number of other resources. cass-operator is responsible for managing the CassandraDatacenter. It creates the StatefulSet(s) and creates several headless services including:</p>
<ul>
<li>datacenter service</li>
<li>seeds service</li>
<li>all pods service</li>
</ul>
<p>The seeds service only resolves to pods that are seeds. Its name is of the form <code><cluster-name>-seed-service</code>. Because of the ephemeral nature of pods cass-operator may designate different C* nodes as seed nodes. Do not use the seed service for connecting client applications.</p>
<p>The all pods service resolves to all Cassandra pods, regardless of whether they are readiness. Its name is of the form <code><cluster-name>-<dc-name>-all-pods-service</code>. This service is intended to facilitate with monitoring. Do not use the all pods service for connecting client applications.</p>
<p>The datacenter service resolves to ready pods. Its name is of the form <code><cluster-name>-<dc-name>-service</code> This is the service that you should use for connecting client applications. Do not directly use pod IPs as they will change over time.</p>
|
<p>I have 3 masters, several workers and Calico as cni. Pods created on masters get <code>172.17.0.*</code> IPs and this is docker network. Pods on workers get IP from calico pool as it should be. <code>calicoctl</code> shows <code>status ok</code> for all nodes.</p>
<p>Also I have same kubelet parameters and config files and I don't have any pod cidr settings there. <code>Kube-system/calico</code> pods are up and running and logs do not show any reason. How can I set correct cidr for pods on masters?</p>
<pre><code>kubectl describe node master1 | egrep -i 'cidr|calico':
projectcalico.org/IPv4Address: 192.168.0.26/24
projectcalico.org/IPv4IPIPTunnelAddr: 10.129.40.64
PodCIDR: 10.128.0.0/24
PodCIDRs: 10.128.0.0/24
</code></pre>
<p>pod details:</p>
<pre><code>kubectl describe po mypod | egrep -i 'master|ip'
Node: master1/192.168.0.26
IP: 172.17.0.3
IPs:
IP: 172.17.0.3
</code></pre>
| <p>Posted community wiki based on comments for better visibility. Feel free to expand it.</p>
<hr />
<p>The solution for the issue is to add flag <code>--network-plugin=cni</code> to Kubelet startup options on the masters nodes (from the @mzv comment):</p>
<blockquote>
<p>I needed to add "--network-plugin=cni" to kubelet startup options</p>
</blockquote>
<p>Instructions on how to add this flag to the Kubelet <a href="https://stackoverflow.com/questions/49278317/adding-network-flag-network-plugin-cni-to-kubelet/49285339#49285339">can be found here</a>.</p>
|
<p>I have Celery workers running on Kubernetes 1.20 cluster on AWS EKS using AWS Elasticache Redis as the broker. Because of the nature of the project ~80% of the time celery workers are running idle so the logical thing was to have them scale automatically. Scaling based on CPU/memory works ok. At about 4 workers node scaling also needs to kick in and that works ok as well.
An obvious problem is that it takes some time for a new node to start and get fully operational before that node can start taking on new celery worker pods. So some waiting to scale up is expected.</p>
<p>Somewhere in all that waiting a fresh celery worker pod gets started and starts accepting new tasks and executing them, but for some unknown reason the <code>startupProbe</code> does not complete. Because <code>startupProbe</code> was not successful the whole pod is killed potentially in the middle of a running task.</p>
<p><strong>Question</strong>:
Can I prevent celery from taking on tasks before the <code>startupProbe</code> is considered successful?</p>
<p>Celery config</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: celery-worker
labels:
app: celery-worker
spec:
selector:
matchLabels:
app: celery-worker
progressDeadlineSeconds: 900
template:
metadata:
labels:
app: celery-worker
spec:
containers:
- name: celery-worker
image: -redacted-
imagePullPolicy: Always
command: ["./scripts/celery_worker_entrypoint_infra.sh"]
env:
- name: CELERY_BROKER_URL
valueFrom:
secretKeyRef:
name: celery-broker-url-secret
key: broker-url
startupProbe:
exec:
command: ["/bin/bash", "-c", "celery -q -A app inspect -d celery@$HOSTNAME --timeout 10 ping"]
initialDelaySeconds: 20
timeoutSeconds: 10
successThreshold: 1
failureThreshold: 30
periodSeconds: 10
readinessProbe:
exec:
command: ["/bin/bash", "-c", "celery -q -b $CELERY_BROKER_URL inspect -d celery@$HOSTNAME --timeout 10 ping"]
periodSeconds: 120
timeoutSeconds: 10
successThreshold: 1
failureThreshold: 3
livenessProbe:
exec:
command: ["/bin/bash", "-c", "celery -q -b $CELERY_BROKER_URL inspect -d celery@$HOSTNAME --timeout 10 ping"]
periodSeconds: 120
timeoutSeconds: 10
successThreshold: 1
failureThreshold: 5
resources:
requests:
memory: "384Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
terminationGracePeriodSeconds: 2400
</code></pre>
<p>Celery HPA config</p>
<pre><code>kind: HorizontalPodAutoscaler
apiVersion: autoscaling/v2beta2
metadata:
name: celery-worker
spec:
minReplicas: 2
maxReplicas: 40
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: celery-worker
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 90
</code></pre>
<p>Celery startup script</p>
<pre><code>python manage.py check
exec celery --quiet -A app worker \
--loglevel info \
--concurrency 1 \
--uid=nobody \
--gid=nogroup
</code></pre>
<p>I'm sharing complete configs including <code>readinessProbe</code> and <code>livenessProbe</code> whose values are a bit inflated, but are a consequence of various try-and-error scenarios.</p>
<p><strong>Edit:</strong>
This is a catch-22 situation.</p>
<p>I have defined <code>startupProbe</code> to check if celery is running in current host and that will only be true if celery worker is running. And if celery worker is running it will accept tasks. And if it will accept tasks <code>celery inspect</code> command might take too long causing the <code>startupProbe</code> to hang and failing. If <code>startupProbe</code> fails too many times it will kill the pod.</p>
<p>Furthermore, if I call <code>celery inspect</code> without destination (host) defined, <code>startupProbe</code> will fail on initial deployment.</p>
<p>Conclusion: <code>celery inspect</code> is not a good <code>startupProbe</code> candidate.</p>
| <blockquote>
<p>Conclusion: <code>celery inspect</code> is not a good <code>startupProbe</code> candidate.</p>
</blockquote>
<p>I agree.</p>
<p>You also mentioned that you have an active <code>healtcheck</code></p>
<blockquote>
<p>I have in another container a web service that uses Django framework and exposes health check at <code>/health</code></p>
</blockquote>
<p>I think it is worth using it to create <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-startup-probes" rel="nofollow noreferrer">startup probe</a>:</p>
<blockquote>
<p>Sometimes, you have to deal with legacy applications that might require an additional startup time on their first initialization. In such cases, it can be tricky to set up liveness probe parameters without compromising the fast response to deadlocks that motivated such a probe. The trick is to set up a startup probe with the same command, HTTP or TCP check, with a <code>failureThreshold * periodSeconds</code> long enough to cover the worse case startup time.</p>
</blockquote>
<p>You also mention an example attack:</p>
<blockquote>
<p>Hmm, I'm not sure that is a smart thing to do. If for instance my web service that serves <code>/health</code> gets DDoS-ed my celery workers would also fail.</p>
</blockquote>
<p>However, this shouldn't be a problem. Startup probe will only run when the container is started. The chance that someone will attack you while the environment is being launched is practically zero. You should use <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes" rel="nofollow noreferrer">readiness or liveness</a> probe to check if your container is alive while the application is running.</p>
<blockquote>
<p>The kubelet uses startup probes to know when a container application has started. If such a probe is configured, it disables liveness and readiness checks until it succeeds, making sure those probes don't interfere with the application startup. This can be used to adopt liveness checks on slow starting containers, avoiding them getting killed by the kubelet before they are up and running.</p>
</blockquote>
<p>Here you can find example yaml</p>
<pre class="lang-yaml prettyprint-override"><code>ports:
- name: liveness-port
containerPort: 8080
hostPort: 8080
livenessProbe:
httpGet:
path: /healthz
port: liveness-port
failureThreshold: 1
periodSeconds: 10
startupProbe:
httpGet:
path: /healthz
port: liveness-port
failureThreshold: 30
periodSeconds: 10
</code></pre>
<p>In this case <code>startupProbe</code> will execute on their first initialization, then will be used <code>livenessProbe</code>.</p>
|
<p>I am running this Cronjob at 2 AM in the morning:</p>
<pre><code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: postgres-backup
spec:
# Backup the database every day at 2AM
schedule: "0 2 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: postgres-backup
image: postgres:10.4
command:
- "/bin/sh"
- -c
- |
pg_dump -Fc -d postgresql://$DBUSER:$DBPASS@$DBHOST:$DBPORT/$DBNAME > /var/backups/backup_$(date +"%d-%m-%Y_%H-%M").bak;
env:
- name: DBHOST
valueFrom:
configMapKeyRef:
name: dev-db-config
key: db_host
- name: DBPORT
valueFrom:
configMapKeyRef:
name: dev-db-config
key: db_port
- name: DBNAME
valueFrom:
configMapKeyRef:
name: dev-db-config
key: db_name
- name: DBUSER
valueFrom:
secretKeyRef:
name: dev-db-secret
key: db_username
- name: DBPASS
valueFrom:
secretKeyRef:
name: dev-db-secret
key: db_password
volumeMounts:
- mountPath: /var/backups
name: postgres-backup-storage
- name: postgres-restore
image: postgres:10.4
volumeMounts:
- mountPath: /var/backups
name: postgres-backup-storage
restartPolicy: OnFailure
volumes:
- name: postgres-backup-storage
hostPath:
# Ensure the file directory is created.
path: /var/volumes/postgres-backups
type: DirectoryOrCreate
</code></pre>
<p>The jobs are getting executed successfully, but what I don't like is that for every Job execution a new Pod is created:</p>
<p><a href="https://i.stack.imgur.com/42w3e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/42w3e.png" alt="Multiple Pods of Cornjob Job execution" /></a></p>
<p>Is there a way to clean previous (old) created Pods?
Or maybe is there a way to rerun one an the same Pod/Job every time?</p>
| <p>If only last job and pod need to be preserved, you can use <code>.spec.successfulJobsHistoryLimit</code> field set to <code>1</code>.</p>
<p>This way only last job and corresponding pod will be preserved. By default it's set to <code>3</code>. Also it's possible to set this value to <code>0</code> and nothing will be saved after cronjob's execution.</p>
<p>Same logic has <code>.spec.failedJobsHistoryLimit</code> field, it has <code>1</code> by default.</p>
<p>See <a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/#jobs-history-limits" rel="nofollow noreferrer">jobs history limits</a>.</p>
<hr />
<p>This is how it looks when I get events from cronjob:</p>
<pre><code>$ kubectl describe cronjob test-cronjob
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal SuccessfulCreate 2m31s cronjob-controller Created job test-cronjob-27304493
Normal SawCompletedJob 2m30s cronjob-controller Saw completed job: test-cronjob-27304493, status: Complete
Normal SuccessfulCreate 91s cronjob-controller Created job test-cronjob-27304494
Normal SawCompletedJob 90s cronjob-controller Saw completed job: test-cronjob-27304494, status: Complete
Normal SuccessfulDelete 90s cronjob-controller Deleted job test-cronjob-27304493
Normal SuccessfulCreate 31s cronjob-controller Created job test-cronjob-27304495
Normal SawCompletedJob 30s cronjob-controller Saw completed job: test-cronjob-27304495, status: Complete
Normal SuccessfulDelete 30s cronjob-controller Deleted job test-cronjob-27304494
</code></pre>
<p>Only one last job is presented:</p>
<pre><code>$ kubectl get jobs
NAME COMPLETIONS DURATION AGE
test-cronjob-27304496 1/1 1s 3s
</code></pre>
<p>And one pod:</p>
<pre><code>$ kubectl get pods
NAME READY STATUS RESTARTS AGE
test-cronjob-27304496-r4qd8 0/1 Completed 0 38s
</code></pre>
|
<p>I'm running Docker Desktop 3.6.0 on Windows 10 with WSL2.
When I try to enable Kubernetes I only see "Failed to start" within the Docker Desktop UI.
Docker itself works fine. Not sure how I can get any further logs.</p>
<p>Here the output from kubectl version:</p>
<pre><code>kubectl version
Client Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.3", GitCommit:"ca643a4d1f7bfe34773c74f79527be4afd95bf39", GitTreeState:"clean", BuildDate:"2021-07-15T21:04:39Z", GoVersion:"go1.16.6", Compiler:"gc", Platform:"windows/amd64"}
Error from server (InternalError): an error on the server ("") has prevented the request from succeeding
</code></pre>
<p>From other posts it seems that and internet connections is required for initial setup:</p>
<ul>
<li><a href="https://stackoverflow.com/a/52765732/1100559">https://stackoverflow.com/a/52765732/1100559</a></li>
<li><a href="https://stackoverflow.com/a/63318739/1100559">https://stackoverflow.com/a/63318739/1100559</a></li>
</ul>
<p>Direct internet connection is not possible on my work environment, I can only manually copy required images on my pc.
I also do not have admin access.</p>
<p>Is there a way to manually setup Kubernetes on Docker Desktop or somehow indicate where the required images can be found?</p>
<p>I have a nexus Docker repository where I can push required images to.
I have changed the <code>~\.docker\daemon.json</code> and added my docker repository in insecure-registries. After first login docker is able to pull images from there and run them.</p>
<p>Already tried to reset or enable and disable Kubernetes. Also deleting ~/.kube/config did not work.</p>
| <p>High level answer...</p>
<ol>
<li>Get a docker registry
<ol>
<li>If you work for an old skool cool enterprise; use <a href="https://jfrog.com/artifactory" rel="nofollow noreferrer">JFrog Artifactory</a></li>
<li>If you just want to get it to work; use <a href="https://goharbor.io/" rel="nofollow noreferrer">Harbor</a></li>
<li>GitHub and GitLab (depending on license) have registries available too...</li>
</ol>
</li>
<li>Edit the docker daemon on the kubernetes nodes (your workstation) to only pull from these registries.
<ol>
<li>if redhat; <code>/etc/containers/registries.conf</code></li>
<li>if debain; <code>/etc/docker/daemon.json</code></li>
<li>you might be able to hack a <code>/etc/hosts</code> entry too...</li>
</ol>
</li>
<li>Populate the new registry</li>
<li>Run kubernetes and yoiu should be good to go. Depending on the configuration you choose you may need to add a <a href="https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/" rel="nofollow noreferrer">registry credential secret</a>.</li>
</ol>
|
<p>Today my kubernetes cluster(v1.15.2) node disk full and cause pods give this tips:</p>
<pre><code>Update plugin resources failed due to failed to write checkpoint file "kubelet_internal_checkpoint": write /var/lib/kubelet/device-plugins/.261578065: no space left on device, which is unexpected.
MountVolume.SetUp failed for volume "default-token-xnrwt" : mkdir /opt/k8s/k8s/kubelet/pods/67eaa71b-adf4-4365-a1c7-42045d5e9426: no space left on device
</code></pre>
<p>I login into server and find the disk usage is 100%, so I remove some log file and release 10GB + disk space, but now it seems pod is not recovery automaticlly and still have this error tips:</p>
<p><a href="https://i.stack.imgur.com/bTlcL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bTlcL.png" alt="enter image description here"></a></p>
<p>what should I do to fix this problem? I am try to restart all pods, and all pods works fine. But finally I found the error tips message still give me tips no space left and did not disappear automaticlly. I check the node status and find the node has no disk pressure. How to make the error tips disappear?</p>
| <p>Other possibility is incorrect unit values for resource requests/limits (ex, using <code>mi</code> instead of <code>Mi</code>).</p>
<p>For example:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Pod
spec:
containers:
- name: {container_name}
resources:
limits:
memory: "512mi" # incorrect; should be "512Mi"
cpu: "200m"
</code></pre>
|
<p>I am wondering if Kubernetes can automatically move the pods to another node if that node resources are on critical, or if that happens only for pods managed by Replica Sets?</p>
<p>In particular:</p>
<ol>
<li>What happens when a <strong>bare pod</strong> (not managed by Replica Sets or similar) is evicted? Is it moved to another node or it is just removed?</li>
<li>In case it is "moved" to a new node, is it really moved or it is recreated? For example, does its <em>age</em> change?</li>
<li>Is it true that only <strong>pods managed by Deployments and Replica Sets</strong> are moved/recreated on a new node while bare pods are simply removed in case of resource shortage?</li>
</ol>
| <blockquote>
<ol>
<li>What happens when a <strong>bare pod</strong> (not managed by Replica Sets or similar) is evicted? Is it moved to another node or it is just removed?</li>
</ol>
</blockquote>
<p>Pod is <a href="https://kubernetes.io/docs/concepts/workloads/pods/#working-with-pods" rel="nofollow noreferrer">designed as a relatively ephemeral, disposable entity</a>; when it is evicted, it's deleted by a Kubelet agent running on the node. There is no recreating / moving to the other node, it's just removed (for bare pods). The controllers (like Deployment, StatefulSet, DaemonSet) are responsible for <a href="https://kubernetes.io/docs/concepts/workloads/pods/#pods-and-controllers" rel="nofollow noreferrer">placing the replacement pods</a>.</p>
<blockquote>
<ol start="2">
<li>In case it is "moved" to a new node, is it really moved or it is recreated? For example, does its <em>age</em> change?</li>
</ol>
</blockquote>
<p>As I mentioned in the answer from the previous question, in the Kubernetes architecture pods are <a href="https://kubernetes.io/docs/concepts/workloads/pods/#working-with-pods" rel="nofollow noreferrer">designed as relatively ephemeral, disposable entities</a>, so there is no "moving". It's recreated as a "fresh" pod on the same or new node. The <em>age</em> parameter is changed, it's starting counting from the beginning as it is a new pod.</p>
<blockquote>
<ol start="3">
<li>Is it true that only <strong>pods managed by Deployments and Replica Sets</strong> are moved/recreated on a new node while bare pods are simply removed in case of resource shortage?</li>
</ol>
</blockquote>
<p>Not only pods managed by Deployment/ReplicaSets but it's also true for some <a href="https://kubernetes.io/docs/concepts/workloads/controllers/" rel="nofollow noreferrer">other controllers</a> (e.g StatefulSet). When a pod is missing (it's got evicted by resource shortage or there is a rolling update), the <a href="https://kubernetes.io/docs/concepts/workloads/controllers/" rel="nofollow noreferrer">controllers</a> are making requests to the <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kube-scheduler/" rel="nofollow noreferrer">Kubernetes Scheduler</a> to roll-out new pods. The bare pods, as answered in the first question, are not recreated.</p>
<p>If you want to read more about this process, check <a href="https://stackoverflow.com/questions/69976108/kubernetes-control-plane-communication/70007320#70007320">my other answer</a>.</p>
|
<p>I have an application deployed to kubernetes.
Here is techstack:
<em>Java 11, Spring Boot 2.3.x or 2.5.x, using hikari 3.x or 4.x</em></p>
<p>Using spring actuator to do healthcheck. Here is <code>liveness</code> and <code>readiness</code> configuration within application.yaml:</p>
<pre><code> endpoint:
health:
group:
liveness:
include: '*'
exclude:
- db
- readinessState
readiness:
include: '*'
</code></pre>
<p>what it does if DB is down -</p>
<ol>
<li>Makes sure <code>liveness</code> doesn't get impacted - meaning, application
container should keep on running even if there is DB outage.</li>
<li><code>readinesss</code> will be impacted making sure no traffic is allowed to hit the container.</li>
</ol>
<p><code>liveness</code> and <code>readiness</code> configuration in container spec:</p>
<pre><code>livenessProbe:
httpGet:
path: actuator/health/liveness
port: 8443
scheme: HTTPS
initialDelaySeconds: 30
periodSeconds: 30
timeoutSeconds: 5
readinessProbe:
httpGet:
path: actuator/health/readiness
port: 8443
scheme: HTTPS
initialDelaySeconds: 30
periodSeconds: 30
timeoutSeconds: 20
</code></pre>
<p>My application is started and running fine for few hours.</p>
<p><strong>What I did:</strong></p>
<p>I brought down DB.</p>
<p><strong>Issue Noticed:</strong></p>
<p>When DB is down, after 90+ seconds I see 3 more pods getting spinned up. When a pod is described I see Status and condition like below:</p>
<pre><code>Status: Running
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
</code></pre>
<p>when I list all running pods:</p>
<pre><code>NAME READY STATUS RESTARTS AGE
application-a-dev-deployment-success-5d86b4bcf4-7lsqx 0/1 Running 0 6h48m
application-a-dev-deployment-success-5d86b4bcf4-cmwd7 0/1 Running 0 49m
application-a-dev-deployment-success-5d86b4bcf4-flf7r 0/1 Running 0 48m
application-a-dev-deployment-success-5d86b4bcf4-m5nk7 0/1 Running 0 6h48m
application-a-dev-deployment-success-5d86b4bcf4-tx4rl 0/1 Running 0 49m
</code></pre>
<p><strong>My Analogy/Finding:</strong></p>
<p>Per <code>ReadinessProbe</code> configuration: <code>periodSeconds</code> is set to 30 seconds and <code>failurethreshold</code> is defaulted to 3 per k8s documentation.</p>
<p>Per application.yaml <code>readiness</code> includes db check, meaning after every 30 seconds <code>readiness</code> check failed. When it fails 3 times, <code>failurethreshold</code> is met and it spins up new pods.</p>
<p>Restart policy is default to Always.</p>
<p><strong>Questions:</strong></p>
<ol>
<li>Why it spinned new pods?</li>
<li>Why it spinned specifically only 3 pods and not 1 or 2 or 4 or any number?</li>
<li>Does this has to do anything with <code>restartpolicy</code>?</li>
</ol>
| <ol>
<li>As you answered to yourself, it spinned new pods after 3 times tries according to <code>failureThreshold</code>. You can change your <code>restartPolicy</code> to <code>OnFailure</code>, it will allow you to restart the job only if it fails or <code>Never</code> if you don't want have the cluster to be restarted. The difference between the statuses you can find <a href="https://stackoverflow.com/a/40534364/16860542">here</a>. Note this:</li>
</ol>
<blockquote>
<p>The restartPolicy <strong>applies to all containers</strong> in the Pod. restartPolicy only refers to r<strong>estarts of the containers</strong> by the kubelet <strong>on the same node</strong>. After containers in a Pod exit, the kubelet restarts them with an exponential back-off delay (10s, 20s, 40s, …), that is capped at five minutes. Once a container has executed for 10 minutes without any problems, the kubelet resets the restart backoff timer for that container.</p>
</blockquote>
<ol start="2">
<li><p>Share your full <code>Deployment</code> file, I suppose that you've set <code>replicas</code> number to <code>3</code>.</p>
</li>
<li><p>Answered in the answer for the 1st question.</p>
</li>
</ol>
<p>Also note this, if this works for you:</p>
<blockquote>
<p>Startup probes are useful for Pods that have containers that take a long time to come into service. Rather than set a long liveness interval, you can configure a separate configuration for probing the container as it starts up, allowing a time longer than the liveness interval would allow.</p>
<p>If your container usually starts in more than initialDelaySeconds + failureThreshold × periodSeconds, you should specify a startup probe that checks the same endpoint as the liveness probe. The default for periodSeconds is 10s. You should then set its failureThreshold high enough to allow the container to start, without changing the default values of the liveness probe. This helps to protect against deadlocks.</p>
</blockquote>
|
<p>I run Minio on a kubernetes cluster since May. Everything worked fine. Since the last action, updated ingress from Traefik to Nginx ingress, I cannot login to the Minio Console anymore.</p>
<p>I do not really know if this happen before or after the ingress update. But in all I think this is not the reason.</p>
<p>The secret is still there in the cluster and it looks well.</p>
<p>The common Minio login to browse the buckets works perfect. But not the Minio Console.</p>
<p>The pod is always writing in the pod log (Lens):</p>
<pre><code>2021-11-29 22:01:17.806356 I | 2021/11/29 22:01:17 operator.go:73: the server has asked for the client to provide credentials
2021-11-29 22:01:17.806384 I | 2021/11/29 22:01:17 error.go:44: original error: invalid Login
</code></pre>
<p>No word about an error, but always <code>Unauthorized</code> inside the login screen. Anybody here with a similar problem in the past?</p>
| <p><strong>Solution 1:</strong></p>
<p>The auth issue can be faced due to an expired <code>apiserver-kubelet-client.crt</code>. If it's expired, try to renew the cert and restart the apiserver.</p>
<p>In order to do this:</p>
<ul>
<li>check if the cert is expired</li>
<li>remove expired certificates(.crt)</li>
<li>execute <code>kubeadm alpha phase certs all</code></li>
</ul>
<p>Note this:</p>
<pre><code># for kube-apiserver
--kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
--kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
# for kubelet
--client-ca-file=/etc/kubernetes/pki/ca.crt
</code></pre>
<p><strong>Solution 2:</strong></p>
<p>While you've deployed cluster on Kubernetes before, you've should created Kubernetes manifest. You can try to delete them(service account, role, rolebinding) and create them once again:</p>
<ul>
<li>Remove Service Account:</li>
</ul>
<p><code>kubectl delete serviceaccount --namespace NAMESPACE_NAME SERVICEACCOUNT_NAME</code></p>
<ul>
<li>Remove Cluter Role Binding:</li>
</ul>
<p><code>kubectl delete clusterrolebinding CLUSTERROLEBINDING_NAME</code></p>
<ul>
<li>Remove Minio directory:</li>
</ul>
<p><code>rm -rf ./minio</code></p>
<ul>
<li>Create the Service Account, Role, RoleBinding:</li>
</ul>
<pre><code>---
apiVersion: v1
kind: ServiceAccount
metadata:
name: minio-serviceaccount
labels:
app: minio
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: minio-role
labels:
app: minio
rules:
- apiGroups:
- ""
resources:
- secrets
resourceNames:
- "minio-keys"
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: minio-role-binding
labels:
app: minio
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: minio-role
subjects:
- kind: ServiceAccount
name: minio-serviceaccount
</code></pre>
<blockquote>
<p>Make sure that the Minio pods can access the Minio keys stored in the previously created Secret or create new secrets.</p>
</blockquote>
<ul>
<li>Run helm init command:</li>
</ul>
<p><code>helm init --service-account=minio-serviceaccount</code></p>
<ul>
<li><p>Recreate your Minio pod</p>
</li>
<li><p>Reinstall the charts</p>
</li>
</ul>
|
<p>Let's say we have a frontend and a backend pods running in a kubernetes cluster.</p>
<p>Both pods have corresponding services exposing them on the host (type: <code>NodePort</code>). In the end, the frontend uses <code><Host IP>:<Port 1></code>, and the backend runs on <code><Host IP>:<Port 2></code>.</p>
<p>How to find out the host IP so that it could be used in the frontend pod (to be defined as a value of a variable)? Tried with setting <code>localhost</code>, but it didn't work, so probably the exact IP has to be defined.</p>
| <p>Use the <a href="https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/" rel="noreferrer">downward API</a>:</p>
<pre><code>spec:
image: ...
env:
- name: REACT_APP_BACKEND_URL
valueFrom:
fieldRef:
fieldPath: status.hostIP
</code></pre>
|
<p>I restarted my mac (Mac OS High Sierra) and now Visual Studio code can't find kubectl binary even it is installed via brew.</p>
<pre><code>$ which kubectl
/usr/local/bin/kubectl
</code></pre>
<p><a href="https://i.stack.imgur.com/fKTSg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fKTSg.png" alt="enter image description here"></a></p>
<p>The weird thing is that it could find kubectl before I restarted my laptop.</p>
| <p>adding the below config is vscode settings.json may resolve this</p>
<pre><code>"vs-kubernetes": {
"vscode-kubernetes.minikube-path.mac": "/path/to/minikube",
"vscode-kubernetes.kubectl-path.mac": "/path/to/kubectl",
"vscode-kubernetes.helm-path.mac" : "/path/to/helm"
}
</code></pre>
|
<p>I have a same <a href="https://github.com/k3s-io/k3s/discussions/4488" rel="nofollow noreferrer">discussion</a> in k3s github repository, but no one reply. Hope someone can give an answer here.</p>
<p>There are articles talking about the embedded etcd HA solution of k3s like <a href="https://blog.alexellis.io/bare-metal-kubernetes-with-k3s/" rel="nofollow noreferrer">this</a>. One of the key behavior is adding a load balancer solution (EIP like this article or LB from the clound provider) between the agents and masters:</p>
<pre><code>k3s agent --> load balancer --> master
</code></pre>
<p>And the <a href="https://rancher.com/docs/k3s/latest/en/architecture/#fixed-registration-address-for-agent-nodes" rel="nofollow noreferrer">architecture of k3s</a> also show that a <strong>Fixed Registration Address</strong> is necessary.</p>
<p>While, after some research I found that k3s (at least v1.21.5+k3s2) have a internal agent load balancer (config at <code>/var/lib/rancher/k3s/agent/etc/k3s-agent-load-balancer.yaml</code>) which will auto update the master k8s api server list in it. So the out side load balancer is unnecessary?</p>
| <p>I got a response from the k3s discussion:</p>
<p><a href="https://github.com/k3s-io/k3s/discussions/4488#discussioncomment-1719009" rel="nofollow noreferrer">https://github.com/k3s-io/k3s/discussions/4488#discussioncomment-1719009</a></p>
<blockquote>
<p>Our documentation lists a requirement for a "fixed registration endpoint" so that nodes do not rely on a single server being online in order to join the cluster. This endpoint could be a load-balancer or a DNS alias, it's up to you. This is only needed when nodes are registering to the cluster; once they have successfully joined, they use the client load-balancer to communicate directly with the servers without going through the registration endpoint.</p>
</blockquote>
<p>I think this is good enough to answer this question.</p>
|
<p>skaffold version
v1.35.1</p>
<p>Using <a href="https://kind.sigs.k8s.io/docs/user/local-registry/" rel="nofollow noreferrer">local registry:2</a> in KinD cluster.</p>
<p><code>kubectl config current-context</code> > kind-kind. And kubectl config view, shows the right url for <code>kind-kind</code> to the server: 127.0.0.1:57836</p>
<h3>Expected behavior</h3>
<p>In Goland: Cloud Code: Kubernetes - a running example</p>
<p>skaffold.yaml</p>
<pre><code># To learn more about the skaffold.yaml schema visit
# https://skaffold.dev/docs/references/yaml/
apiVersion: skaffold/v2beta19
kind: Config
build:
artifacts:
- context: .
image: go-hello-world
deploy:
kubectl:
manifests:
- kubernetes-manifests/**
</code></pre>
<h3>Actual behavior</h3>
<p>Error:</p>
<pre><code>unable to connect to Kubernetes: the server has asked for the client to provide credentials
</code></pre>
<p>Note in the following, that it actually runs - but only very short time. See: <code>Step 8/14</code> in the following</p>
<p>skaffold dev --default-repo localhost:5000</p>
<pre><code>Listing files to watch...
- go-hello-world
Generating tags...
- go-hello-world -> 127.0.0.1:5000/go-hello-world:6b3fc6f-dirty
Checking cache...
- go-hello-world: Not found. Building
Starting build...
Found [kind-kind] context, using local docker daemon.
Building [go-hello-world]...
Sending build context to Docker daemon 932.9kB
Step 1/14 : FROM golang:1.16 as build
---> 5b838b7289de
Step 2/14 : WORKDIR /hello-world
---> Using cache
---> a8c93bc46b78
Step 3/14 : COPY go.mod go.sum ./
---> Using cache
---> cba8d38c5d62
Step 4/14 : RUN go mod download
---> Using cache
---> bfb3c3842a45
Step 5/14 : COPY . ./
---> f7f0547858d2
Step 6/14 : ARG SKAFFOLD_GO_GCFLAGS
---> Running in 8df9562291c8
---> 20aec50f0a84
Step 7/14 : RUN echo "Go gcflags: ${SKAFFOLD_GO_GCFLAGS}"
---> Running in f35f8060867a
Go gcflags:
---> cc2532367c46
Step 8/14 : RUN go build -gcflags="${SKAFFOLD_GO_GCFLAGS}" -mod=readonly -v -o /app
---> Running in 03fe6cd6a195
hello-world
---> d8873c3d1844
Step 9/14 : FROM gcr.io/distroless/base
---> 64bbfbb81976
Step 10/14 : ENV GOTRACEBACK=single
---> Using cache
---> e7db9a53c2fe
Step 11/14 : WORKDIR /hello-world
---> Using cache
---> cba82d8b0927
Step 12/14 : COPY --from=build /app .
---> Using cache
---> fdd46a287814
Step 13/14 : COPY template ./template
---> Using cache
---> 01f1804abfcc
Step 14/14 : ENTRYPOINT ["./app"]
---> Using cache
---> c57d404bd28f
Successfully built c57d404bd28f
Successfully tagged 127.0.0.1:5000/go-hello-world:6b3fc6f-dirty
Tags used in deployment:
- go-hello-world -> 127.0.0.1:5000/go-hello-world:c57d404bd28fbee71266d45debb822dd57215b585c2e16f5b1b21b5632ee0904
Starting deploy...
Cleaning up...
unable to connect to Kubernetes: the server has asked for the client to provide credentials
</code></pre>
| <p>Running skaffold with the <code>--kubeconfig <path to kubeconfig file></code> should to the trick.</p>
|
<p>I am new to k8's and trying to update storageClassName in a StatefulSet.(from default to default-t1 only change in the yaml)</p>
<p>I tried running <code>kubectl apply -f test.yaml</code></p>
<p>The only difference between 1st and 2nd Yaml(one using to apply update) is storageClassName: default-t1 instead of default</p>
<pre><code>apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: "nginx"
podManagementPolicy: "Parallel"
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: k8s.gcr.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: default
resources:
requests:
storage: 1Gi
</code></pre>
<p>Every-time I try to update it I get <code>The StatefulSet "web" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden</code></p>
<p>What am I missing or what steps should I take to do this?</p>
| <p>There's no easy way as far as I know but it's possible.</p>
<ol>
<li>Save your current StatefulSet configuration to yaml file:</li>
</ol>
<pre><code>kubectl get statefulset some-statefulset -o yaml > statefulset.yaml
</code></pre>
<ol start="2">
<li>Change <code>storageClassName</code> in <code>volumeClaimTemplate</code> section of StatefulSet configuration saved in yaml file</li>
<li>Delete StatefulSet without removing pods using:</li>
</ol>
<pre><code>kubectl delete statefulset some-statefulset --cascade=orphan
</code></pre>
<ol start="4">
<li>Recreate StatefulSet with changed StorageClass:</li>
</ol>
<pre><code>kubectl apply -f statefulset.yaml
</code></pre>
<ol start="5">
<li>For each Pod in StatefulSet, first delete its PVC (it will get stuck in terminating state until you delete the pod) and then delete the Pod itself</li>
</ol>
<p>After deleting each Pod, StatefulSet will recreate a Pod (and since there is no PVC) also a new PVC for that Pod using changed StorageClass defined in StatefulSet.</p>
|
<p>If a Helm deployment's status is <code>failed</code>, what can I do to determine what made it fail?</p>
| <p><code>helm history <chartname></code></p>
<p>Shows the kubernetes errors for the attempted deployment of that chart.</p>
|
<p>What happens when Kubernetes <code>liveness-probe</code> returns false?
Does Kubernetes restart that pod immediately?</p>
| <p>First, please note that <code>livenessProbe</code> concerns <strong>containers</strong> in the pod, not the pod itself. So if you have multiple containers in one pod, only the affected container will be restarted.</p>
<p>It's worth noting, that there is <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#configure-probes" rel="noreferrer">parameter <code>failureThreshold</code></a>, which is set by default to 3. So, after 3 failed probes a container will be restarted:</p>
<blockquote>
<p><code>failureThreshold</code>: When a probe fails, Kubernetes will try <code>failureThreshold</code> times before giving up. Giving up in case of liveness probe means restarting the container. In case of readiness probe the Pod will be marked Unready. Defaults to 3. Minimum value is 1.</p>
</blockquote>
<p>Ok, we have information that a container is restarted after 3 failed probes - but what does it mean to <em>restart</em>?</p>
<p>I found a good article about <em>how</em> Kubernetes terminates a pods - <a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace" rel="noreferrer">Kubernetes best practices: terminating with grace</a>. Seems for container restart caused by liveness probe it's similar - I will share my experience below.</p>
<p>So basically when container is being terminated by liveness probe steps are:</p>
<ul>
<li>if there is a <a href="https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks" rel="noreferrer"><code>PreStop</code> hook</a>, it will be executed</li>
<li><a href="https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html" rel="noreferrer">SIGTERM signal</a> is sent to the container</li>
<li>Kubernetes waits for grace period</li>
<li>After grace period, <a href="https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html" rel="noreferrer">SIGKILL signal</a> is sent to a pod</li>
</ul>
<p>So... if an app in your container is catching the SIGTERM signal properly, then the container will shut-down and will be started again. Typically it's happening pretty fast (as I tested for the NGINX image) - almost immediately.</p>
<p>Situation is different when SIGTERM is not supported by your application. It means after <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination" rel="noreferrer"><code>terminationGracePeriodSeconds</code> period</a> the SIGKILL signal is sent, it means the container will be forcibly removed.</p>
<p>Example below (modified example from <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-command" rel="noreferrer">this doc</a>) + I set <code>failureThreshold: 1</code></p>
<p>I have following pod definition:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Pod
metadata:
labels:
test: liveness
name: liveness-exec
spec:
containers:
- name: liveness
image: nginx
livenessProbe:
exec:
command:
- cat
- /tmp/healthy
periodSeconds: 10
failureThreshold: 1
</code></pre>
<p>Of course there is no <code>/tmp/healthy</code> file, so livenessProbe will fail. The NGINX image is properly catching the SIGTERM signal, so the container will be restarted almost immediately (for every failed probe). Let's check it:</p>
<pre><code>user@shell:~/liveness-test-short $ kubectl get pods
NAME READY STATUS RESTARTS AGE
liveness-exec 0/1 CrashLoopBackOff 3 36s
</code></pre>
<p>So after ~30 sec the container is already restarted a few times and it's status is <a href="https://sysdig.com/blog/debug-kubernetes-crashloopbackoff/" rel="noreferrer">CrashLoopBackOff</a> as expected. I created the same pod without livenessProbe and I measured the time need to shutdown it:</p>
<pre><code>user@shell:~/liveness-test-short $ time kubectl delete pod liveness-exec
pod "liveness-exec" deleted
real 0m1.474s
</code></pre>
<p>So it's pretty fast.</p>
<p>The similar example but I added <code>sleep 3000</code> command:</p>
<pre class="lang-yaml prettyprint-override"><code>...
image: nginx
args:
- /bin/sh
- -c
- sleep 3000
...
</code></pre>
<p>Let's apply it and check...</p>
<pre><code>user@shell:~/liveness-test-short $ kubectl get pods
NAME READY STATUS RESTARTS AGE
liveness-exec 1/1 Running 5 3m37s
</code></pre>
<p>So after ~4 min there are only 5 restarts. Why? Because we need to wait for full <code>terminationGracePeriodSeconds</code> period (default is 30 seconds) for every restart. Let's measure time needed to shutdown:</p>
<pre><code>user@shell:~/liveness-test-short $ time kubectl delete pod liveness-exec
pod "liveness-exec" deleted
real 0m42.418s
</code></pre>
<p>It's much longer.</p>
<p><strong>To sum up:</strong></p>
<blockquote>
<p>What happens when Kubernetes liveness-probe return false? Does Kubernetes restart that pod immediately?</p>
</blockquote>
<p>The short answer is: by default no. Why?</p>
<ul>
<li>Kubernetes will restart a container in a pod after <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#configure-probes" rel="noreferrer"><code>failureThreshold</code></a> times. By default it is 3 times - so after 3 failed probes.</li>
<li>Depends on your configuration of the container, time needed for container termination could be very differential</li>
<li>You can adjust both <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#configure-probes" rel="noreferrer"><code>failureThreshold</code></a> and <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination" rel="noreferrer"><code>terminationGracePeriodSeconds</code> period</a> parameters, so the container will be restarted immediately after every failed probe.</li>
</ul>
|
<p>I have a service which is running in kubernetes, and has a path prefix <code>/api</code>. Now I want to use Ingress to access it through the host address <code>example.com/service1/</code> because I have multiple services. But the problem is that ingress redirects all the requests from path <code>service1/</code> with that prefix <code>service1/</code>, but I want it to redirect from <code>example.com/service1/</code> to my service with just <code>/</code> (so if I request <code>example.com/service1/api</code> it will redirect to service with just <code>/api</code>). Can I achieve something like this? I'm writing Ingress configuration in the helm chart of the service.
Ingress configuration in service chart file <code>values.yaml</code> looks like this:</p>
<pre><code>...
ingress:
enabled: true
className: ""
annotations: {}
# kubernetes.io/ingress.class: nginx // this comment was created when generating helm chart
hosts:
- host: example.com
paths:
- path: /service1(/|$)(.*)
pathType: ImplementationSpecific
backend:
serviceName: $name
servicePort: http
tls: []
...
</code></pre>
<p>And <code>ingress.yaml</code> inside <code>templates/</code> folder is a default file that was generated by <code>helm</code> when I was creating a chart for the service. It just uses values from <code>values.yaml</code> to configure ingress. I didn't find anything, only <a href="https://stackoverflow.com/questions/63532836/kubernetes-ingress-not-redirecting-to-correct-path">this question</a> which is basically saying that I need to add either prefix <code>service1/</code> to my service or just use <code>/api</code> in the Ingress configuration. But is there solution suitable for my needs?</p>
| <p><em>This is a community wiki answer posted for better visibility. Feel free to expand it.</em></p>
<p>Based on the solution provided in the comments (method 1 example 2 in the Medium <a href="https://medium.com/ww-engineering/kubernetes-nginx-ingress-traffic-redirect-using-annotations-demystified-b7de846fb43d" rel="nofollow noreferrer">post</a> ), a possible <code>values.yaml</code> file for Ingress might looks like below.</p>
<pre><code>...
ingress:
enabled: true
className: ""
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: http://example.com/$2
hosts:
- host: example.com
paths:
- path: /service1(/|$)(.*)
backend:
serviceName: $name
servicePort: http
tls: []
...
</code></pre>
|
<p>I have a question about Kubernetes enviroment. I have K8s cloud and after what I add assign one Persistent volume to one pod, this pod is still in "ContainerCreating" status. This PV has assign PVC correctly. PVC is on two external GlusterFS servers with replica 2. </p>
<p><strong>PV look like this:</strong></p>
<pre><code>apiVersion: v1
kind: PersistentVolume
metadata:
annotations:
definitionVersion: "20170919"
name: tarsier-pv
spec:
accessModes:
- ReadWriteMany
capacity:
storage: 50Gi
glusterfs:
endpoints: glusterfs-cluster
path: tarsier-prep
persistentVolumeReclaimPolicy: Recycle
</code></pre>
<p><strong>PVC look like this:</strong></p>
<pre><code> apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: tarsier-pvc
annotations:
definitionVersion: "20170919"
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 50Gi
volumeName: tarsier-pv
status:
accessModes:
- ReadWriteMany
capacity:
storage: 50Gi
phase: Bound
</code></pre>
<p><strong>Pods RC look like this:</strong></p>
<pre><code> apiVersion: v1
kind: ReplicationController
metadata:
name: xxx
spec:
replicas: 1
template:
metadata:
labels:
app: xxxxx
spec:
volumes:
- name: tarsier-pv
persistentVolumeClaim:
claimName: tarsier-pvc
...
containers:
- name: xxx
...
volumeMounts:
- name: tarsier-pv
mountPath: "/shared_data/storage"
</code></pre>
<p>Kubectl describe pod xxx return no errors.</p>
<p>kubectl logs xxx return this: </p>
<pre><code>Error from server (BadRequest): container "xxx" in pod "xxx" is waiting to start: ContainerCreating.
</code></pre>
<p>Do you have any ideas what could be wrong or where I can find any detailed logs?
THX in advance.</p>
<p>Edit:
Gluster mount is mounted on Master correctly and if I manually add there any file, it is correctly duplicated on both Gluster servers</p>
| <p>To see what is wrong, check the events:</p>
<pre><code>kubectl get events --sort-by=.metadata.creationTimestamp
</code></pre>
|
<p>I am trying to figure out <strong>how to get pod labels into the metric tags from kubelet metrics using prometheus-stack</strong>. In our environment, we need to hash pod names (due to length limitations) so our app name, env, and unit name are saved in pod labels.</p>
<p>We are using prometheus-stack (helm installation) to collect metrics from kubelet (<code>/metrics</code>, <code>/metrics/cadvisor</code>) and due to the lack of pod labels in metrics tags, it's difficult to know which metric belongs to which application.</p>
<p>Prometheus-stack is using <code>sd_kubernetes_config</code> with endpoint rule to collect kubelet metrics, where <code>__meta</code> tags for pod labels cannot be used. Is there another way how to get that labels in metric tags?</p>
<p>I also tried to collect pod_labels metric using <code>kubeStateMetrics</code>, where I can get metric that contains pod labels, but I cannot figure out how to display both metrics in a way that metric from cadvisor will show its value and metric from <code>kubeStateMetrics</code> will be used to display its labels (in Prometheus graph).</p>
<p>Thanks for any advice.</p>
| <p>As far as I know you can really use filtering metrics <a href="https://stackoverflow.com/questions/60067654/prometheus-filtering-based-on-labels">based on pod labels</a>. Look at the original answer:</p>
<blockquote>
<p>You can use <code>+</code> operator to join metrics. Here, <code>group_left()</code> will include the extra label: <code>label_source</code> from the right metric <code>kube_pod_labels</code>. The metric you're joining is forced to zero ( i.e. <code>0 * kube_pod_labels</code> ) so that it doesn't affect the result of first metric.</p>
</blockquote>
<pre><code>(
kube_pod_info{namespace="test"}
)
+ on(namespace) group_left(label_source)
(
0 * kube_pod_labels
)
</code></pre>
<p>In fact, metrics then can be long and nasty. However, it is an effective method in prometheus to create what you expect, which is kubelet metrics with pod labels.</p>
<p>Look also at <a href="https://ypereirareis.github.io/blog/2020/02/21/how-to-join-prometheus-metrics-by-label-with-promql/" rel="nofollow noreferrer">this guide</a> - it is described how to join Prometheus metrics by label with PromQL and <a href="https://grafana.com/blog/2021/08/04/how-to-use-promql-joins-for-more-effective-queries-of-prometheus-metrics-at-scale/" rel="nofollow noreferrer">this another guide</a> - How to use PromQL joins for more effective queries of Prometheus metrics at scale.</p>
|
<p>I have created an AKS cluster. Is Azure generating the following PKI certificate for us?</p>
<p><a href="https://kubernetes.io/docs/setup/best-practices/certificates/#how-certificates-are-used-by-your-cluster" rel="nofollow noreferrer">https://kubernetes.io/docs/setup/best-practices/certificates/#how-certificates-are-used-by-your-cluster</a>.</p>
| <p>Yes, AKS manages all these certificates for you, with the exception of:</p>
<blockquote>
<p>Client certificates for administrators of the cluster to authenticate to the API server</p>
</blockquote>
<p>Because AKS hands out access tokens in the form of JWTs.</p>
|
<p>If I have two pods running on different namespaces, and there is netpol already setup and cannot be modified, how would I approach the POD to POD communication making the ingress and egress possible again without modifying the existing object?</p>
| <p>User <a href="https://stackoverflow.com/users/1153938/vorsprung" title="30,068 reputation">Vorsprung</a> has good mentioned in the comment:</p>
<blockquote>
<p>The netpolicy that is already there probably does a general ingres / egress block. If you add another policy that specifically allows the POD to POD you need then it will, in this case override the general policy. See <a href="https://serverfault.com/questions/951958">https://serverfault.com/questions/951958</a></p>
</blockquote>
<p>Yes, you can add another network policy according to your needs and everything should work. It doesn't matter in which order you apply your rules.</p>
<p>Look also <a href="https://github.com/ahmetb/kubernetes-network-policy-recipes" rel="nofollow noreferrer">here</a>. You can find many <a href="https://github.com/ahmetb/kubernetes-network-policy-recipes" rel="nofollow noreferrer">kubernetes network policies recipes</a>.</p>
|
<p>I want to get the status code of my command executed in a container with Fabric8 Java Kubernetes client.</p>
<p>Here is the script located in my container:</p>
<pre><code>echo Bye Bye
exit 1
</code></pre>
<p>When I run the script with CLI or NodeJS Client I am able to get the output status code</p>
<p>Here is an example taken from fabric8 repository:</p>
<pre><code>package org.package;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.ExecListener;
import io.fabric8.kubernetes.client.dsl.ExecWatch;
import okhttp3.Response;
public class OtherMain {
public static void main(String[] args) throws InterruptedException {
String podName = "my-pod";
String namespace = "my-namespace";
try (
KubernetesClient client = new DefaultKubernetesClient();
ExecWatch watch = newExecWatch(client, namespace, podName)) {
Thread.sleep(10 * 1000L);
}
}
private static ExecWatch newExecWatch(KubernetesClient client, String namespace, String podName) {
return client.pods()
.inNamespace(namespace)
.withName(podName)
.readingInput(System.in)
.writingOutput(System.out)
.writingError(System.err)
.withTTY()
.usingListener(new SimpleListener())
.exec("sh", "test.sh");
}
private static class SimpleListener implements ExecListener {
@Override
public void onOpen(Response response) {
System.out.println("The shell will remain open for 10 seconds.");
}
@Override
public void onFailure(Throwable t, Response response) {
System.err.println("shell barfed");
}
@Override
public void onClose(int code, String reason) {
System.out.println("The shell will now close.");
}
}
}
</code></pre>
<p>However when looking at the output it seems that everything went ok. Is there a way to get the output status code ?</p>
| <p>It is possible by using the <code>wri</code> method:</p>
<p>Can use the <code>.writingErrorChannel</code> and parse the response:</p>
<pre><code>{
"metadata": {},
"status": "Failure",
"message": "command terminated with non-zero exit code: exit status 1",
"reason": "NonZeroExitCode",
"details": {
"causes": [
{
"reason": "ExitCode",
"message": "1"
}
]
}
}
</code></pre>
<p>Type is: <code>io.fabric8.kubernetes.api.model.Status</code></p>
|
<p>I have a ConfigMap with multiple files, and want to add these files to an already existing directory. But the tricky part here is, the filenames(keys) can change. So I can't try to mount them individually using subPath.</p>
<p>Is there any way this can be achieved from Deployment manifest?</p>
<p>Configmap:</p>
<pre><code>config-files-configmap
└── newFile1.yml
└── newFile2.yml
</code></pre>
<p>Existing directory after adding files from configmap:</p>
<pre><code>config/
└── existingFile1.yml
└── existingFile2.yml
└── newFile1.yml
└── newFile2.yml
</code></pre>
<p>PS: I have tried mounting the configmap as directory, which will override existing contents of the directory.</p>
<p>Thanks</p>
| <p>You can use the <strong>init container</strong> with <strong>configmap</strong> as a <strong>volume</strong> mount.</p>
<p>Not sure about the actual deployment architecture.</p>
<p>i would suggest injecting the configmap files to another directory and copying and pasting at starting of the main container.</p>
<p>Using life cycle hook of POD of init container.</p>
<p>As we can not go with <strong>subpath</strong>, this one option i am seeing as of now.</p>
<p>Example helm template from RabbitMQ</p>
<pre><code>apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-rabbitmq
labels: &RabbitMQDeploymentLabels
app.kubernetes.io/name: {{ .Release.Name }}
app.kubernetes.io/component: rabbitmq-server
spec:
selector:
matchLabels: *RabbitMQDeploymentLabels
serviceName: {{ .Release.Name }}-rabbitmq-discovery
replicas: {{ .Values.rabbitmq.replicas }}
updateStrategy:
# https://www.rabbitmq.com/upgrade.html
# https://cloud.google.com/kubernetes-engine/docs/how-to/updating-apps
type: RollingUpdate
template:
metadata:
labels: *RabbitMQDeploymentLabels
spec:
serviceAccountName: {{ .Values.rabbitmq.serviceAccount }}
terminationGracePeriodSeconds: 180
initContainers:
# This init container copies the config files from read-only ConfigMap to writable location.
- name: copy-rabbitmq-config
image: {{ .Values.rabbitmq.initImage }}
imagePullPolicy: Always
command:
- /bin/bash
- -euc
- |
# Remove cached erlang cookie since we are always providing it,
# that opens the way to recreate the application and access to existing data
# as a new erlang will be regenerated again.
echo ${RABBITMQ_ERLANG_COOKIE} > /var/lib/rabbitmq/.erlang.cookie
chmod 600 /var/lib/rabbitmq/.erlang.cookie
# Copy the mounted configuration to both places.
cp /rabbitmqconfig/rabbitmq.conf /etc/rabbitmq/rabbitmq.conf
# Change permission to allow to add more configurations via variables
chown :999 /etc/rabbitmq/rabbitmq.conf
chmod 660 /etc/rabbitmq/rabbitmq.conf
cp /rabbitmqconfig/enabled_plugins /etc/rabbitmq/enabled_plugins
volumeMounts:
- name: configmap
mountPath: /rabbitmqconfig
- name: config
mountPath: /etc/rabbitmq
- name: {{ .Release.Name }}-rabbitmq-pvc
mountPath: /var/lib/rabbitmq
env:
- name: RABBITMQ_ERLANG_COOKIE
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-rabbitmq-secret
key: rabbitmq-erlang-cookie
containers:
- name: rabbitmq
image: "{{ .Values.rabbitmq.image.repo }}:{{ .Values.rabbitmq.image.tag }}"
imagePullPolicy: Always
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: RABBITMQ_USE_LONGNAME
value: 'true'
- name: RABBITMQ_NODENAME
value: 'rabbit@$(MY_POD_NAME).{{ .Release.Name }}-rabbitmq-discovery.{{ .Release.Namespace }}.svc.cluster.local'
- name: K8S_SERVICE_NAME
value: '{{ .Release.Name }}-rabbitmq-discovery'
- name: K8S_HOSTNAME_SUFFIX
value: '.{{ .Release.Name }}-rabbitmq-discovery.{{ .Release.Namespace }}.svc.cluster.local'
# User name to create when RabbitMQ creates a new database from scratch.
- name: RABBITMQ_DEFAULT_USER
value: '{{ .Values.rabbitmq.user }}'
# Password for the default user.
- name: RABBITMQ_DEFAULT_PASS
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-rabbitmq-secret
key: rabbitmq-pass
ports:
- name: clustering
containerPort: 25672
- name: amqp
containerPort: 5672
- name: amqp-ssl
containerPort: 5671
- name: prometheus
containerPort: 15692
- name: http
containerPort: 15672
volumeMounts:
- name: config
mountPath: /etc/rabbitmq
- name: {{ .Release.Name }}-rabbitmq-pvc
mountPath: /var/lib/rabbitmq
livenessProbe:
exec:
command:
- rabbitmqctl
- status
initialDelaySeconds: 60
timeoutSeconds: 30
readinessProbe:
exec:
command:
- rabbitmqctl
- status
initialDelaySeconds: 20
timeoutSeconds: 30
lifecycle:
postStart:
exec:
command:
- /bin/bash
- -c
- |
# Wait for the RabbitMQ to be ready.
until rabbitmqctl node_health_check; do
sleep 5
done
# By default, RabbitMQ does not have Highly Available policies enabled,
# using the following command to enable it.
rabbitmqctl set_policy ha-all "." '{"ha-mode":"all", "ha-sync-mode":"automatic"}' --apply-to all --priority 0
{{ if .Values.metrics.exporter.enabled }}
- name: prometheus-to-sd
image: {{ .Values.metrics.image }}
ports:
- name: profiler
containerPort: 6060
command:
- /monitor
- --stackdriver-prefix=custom.googleapis.com
- --source=rabbitmq:http://localhost:15692/metrics
- --pod-id=$(POD_NAME)
- --namespace-id=$(POD_NAMESPACE)
- --monitored-resource-type-prefix=k8s_
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
{{ end }}
volumes:
- name: configmap
configMap:
name: {{ .Release.Name }}-rabbitmq-config
items:
- key: rabbitmq.conf
path: rabbitmq.conf
- key: enabled_plugins
path: enabled_plugins
- name: config
emptyDir: {}
volumeClaimTemplates:
- metadata:
name: {{ .Release.Name }}-rabbitmq-pvc
labels: *RabbitMQDeploymentLabels
spec:
accessModes:
- ReadWriteOnce
storageClassName: {{ .Values.rabbitmq.persistence.storageClass }}
resources:
requests:
storage: {{ .Values.rabbitmq.persistence.size }}
</code></pre>
<p>Example reference : <a href="https://github.com/GoogleCloudPlatform/click-to-deploy/blob/master/k8s/rabbitmq/chart/rabbitmq/templates/statefulset.yaml" rel="nofollow noreferrer">https://github.com/GoogleCloudPlatform/click-to-deploy/blob/master/k8s/rabbitmq/chart/rabbitmq/templates/statefulset.yaml</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.