<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dries De Smet on Medium]]></title>
        <description><![CDATA[Stories by Dries De Smet on Medium]]></description>
        <link>https://medium.com/@driesdesmet_69747?source=rss-48775017cf4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Arzo0b7DbzKO4v0o.</url>
            <title>Stories by Dries De Smet on Medium</title>
            <link>https://medium.com/@driesdesmet_69747?source=rss-48775017cf4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:58:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@driesdesmet_69747/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting up Google Cloud with Kubernetes, Nginx Ingress and Let’s Encrypt (Certmanager)]]></title>
            <link>https://medium.com/google-cloud/setting-up-google-cloud-with-kubernetes-nginx-ingress-and-lets-encrypt-certmanager-bf134b7e406e?source=rss-48775017cf4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf134b7e406e</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[lets-encrypt]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Dries De Smet]]></dc:creator>
            <pubDate>Tue, 10 Jul 2018 11:53:32 GMT</pubDate>
            <atom:updated>2018-07-10T12:06:33.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZKN6SsMTy_gpVY-MFSu_g.jpeg" /></figure><p>In this post I will try to share the steps that I took to setup a cluster in kubernetes. Note that my knowledge of Google Cloud &amp; Kubernetes is limited to a week of research, so I’m open to suggestions to improve it.</p><p>This is aimed at people that just begin exploring Google cloud / Kubernetes, and an attempt to consolidate the week of (sometimes confusing) research</p><p><strong>Assumed knowledge</strong> (Acquirable in a week! ;))</p><ul><li>Basic concepts of how kubernetes works (pods, deployments, services)</li><li>Basic concepts of google cloud</li></ul><p><strong>What will be deployed at the end:</strong></p><ul><li>A single node kubernetes cluster, with no scaling enabled.</li><li>A docker image containing the app (Nginx/Angular2)</li><li>A docker image containing the api (with connection details for a mongodb) (NodeJS)</li><li>A docker image with nginx to reverse proxy google storage</li><li>Nginx Ingress that routes to the docker backends</li><li>Certificate that gets validated by Let’s Encrypt &amp; used by ingress</li></ul><p><strong>Not included:</strong></p><ul><li>The actual docker images, this guide is more as a guideline on how to setup this ‘architecture’.</li></ul><h4>Setting up GCloud CLI (Skip if available)</h4><p>See the appendix for how to setup Google Cloud CLI. From this point it’s assumed that you have a working gcloud, logged in &amp; pointing at your project/compute zone</p><h3>Creating the cluster</h3><p>gcloud container clusters create &lt;cluster_name&gt; --num-nodes=1</p><p>This step will create a cluster for you with one node (one compute engine machine), on which all the pods/services will run.</p><p>gcloud container clusters get-credentials &lt;cluster_name&gt;</p><p>This command configures <strong>kubectl</strong>, which is the cli tool to interact with kubernetes, to work against the cluster that we’ve just created</p><h3>Creating a namespace (optional)</h3><p>For our purpose, namespaces was intended to separate environments from each other. So we would have a beta/QA environment running on the same cluster/node for example. This would isolate pods and services from each other.</p><p>kubectl create namespace &lt;name&gt;</p><p>A cluster normally has two namespaces when just creating, <strong>default </strong>and <strong>kube-system</strong>, if not specifying the namespace in commands, your resources will end up in the <strong>default</strong> namespace. <strong>kube-system</strong> is reserved for kubernetes services.</p><h3>Setting up Helm, installing Tiller</h3><p>Helm can best be described as a package manager for kubernetes, you will install nginx-ingress and certmanager with this tool. It runs as a client/server architecture, with helm being the cli tool you use, and tiller the server (which we will install later on the cluster).</p><pre><em>kubectl </em>create serviceaccount --namespace kube-system tiller<br><em>kubectl </em>create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller</pre><pre><em>helm </em>init --service-account tiller</pre><pre><em>kubectl </em>patch deploy --namespace kube-system tiller-deploy -p &#39;{&quot;spec&quot;:{&quot;template&quot;:{&quot;spec&quot;:{&quot;serviceAccount&quot;:&quot;tiller&quot;}}}}&#39;</pre><pre><em>helm </em>init --service-account tiller --upgrade</pre><p>Here we’re not sure if the patch is required. But it’ll create a service account in the kube-system namespace, create the necessary rolebindings, and init helm with this account.</p><p>Please refer to <a href="https://cloud.google.com/solutions/continuous-integration-helm-concourse">https://cloud.google.com/solutions/continuous-integration-helm-concourse</a> for more details about these steps.</p><h3>Deploying the app docker</h3><p>Prior to this step we have already the images available in the registry. For our app this is a nginx that exposes port 80 &amp; serves the angular 2 build.</p><p>We have a script that is run before starting nginx, that replaces the api &amp; static host variables present in the source code</p><pre><em>echo </em>&quot;Configuring environment variable&quot;<br><em>sed </em>-i -e &#39;s#SET_API_HOST_VARIABLE#&#39;&quot;$API_HOST&quot;&#39;#g&#39; /www/main.*.js<br><em>sed </em>-i -e &#39;s#SET_STATIC_HOST#&#39;&quot;$STATIC_HOST&quot;&#39;#g&#39;  /www/main.*.js</pre><p>This ensures that we have a generic docker image build, but we can still tweak the hosts with environment variables after deployment.</p><p>This is also the first step we do in kubernetes, creating a <strong>ConfigMap</strong> for our app.</p><pre><em>kubectl </em>create configmap AppNameConfig --from-literal API_HOST=http://api-host --from-literal STATIC_HOST=$STATIC_HOST</pre><p>This configmap is then used in our app kubernetes manifest file, to specify the environment variables to inject, and from where it needs to get the values, in this case, the map.</p><pre><strong>apiVersion: </strong>apps/v1beta2<br><strong>kind: </strong>Deployment<br><strong>metadata:<br>  name: </strong>AppName<br><strong>spec:<br>  replicas: </strong>1<br>  <strong>selector:<br>    matchLabels:<br>      app: </strong>AppName<br>  <strong>strategy:<br>    rollingUpdate:<br>      maxSurge: </strong>1<br>      <strong>maxUnavailable: </strong>1<br>    <strong>type: </strong>RollingUpdate<br>  <strong>template:<br>    metadata:<br>      labels:<br>        app: </strong>AppName<br>    <strong>spec:<br>      containers:<br>      </strong>- <strong>env:<br>        </strong>- <strong>name: </strong>API_HOST<br>          <strong>valueFrom:<br>            configMapKeyRef:<br>              key: </strong>API_HOST<br>              <strong>name: </strong>AppNameConfig<br>        - <strong>name: </strong>STATIC_HOST<br>          <strong>valueFrom:<br>            configMapKeyRef:<br>              key: </strong>STATIC_HOST<br>              <strong>name: </strong>AppNameConfig<br>        <strong>name: </strong>AppName<br>        <strong>image: </strong>AppDockerImageName<br>        <strong>ports:<br>        </strong>- <strong>containerPort: </strong>80</pre><p>This manifest is applied with:</p><pre><em>kubectl </em>apply -f AppManifest.yml</pre><p>This will create the deployment on kubernetes, which will spin up the pod holding the container running your image.</p><p>At this point, this deployment is not accessible from outside. For our load balancer to work, we need to expose this as a cluster ip service. Which just ensures that this deployment has a cluster ip.</p><pre><em>kubectl </em>expose deployment AppName</pre><h3>Deploying the API docker</h3><p>The process for this is exactly the same as the app docker. Except that we need a mongo connection. This is best stored in a kubernetes secret, so that they are not as visible as putting them in a configmap.</p><p>Create a secret with:</p><pre><em>kubectl </em>create secret generic ApiMongoSecret --from-literal MONGO_HOST=&quot;&lt;host&gt;&quot; --from-literal MONGO_REPLICA_SET=&quot;&lt;replica&gt;&quot; --from-literal MONGO_GET_VARIABLES=&quot;&lt;variables&gt;&quot;</pre><p>Create the configmap as before:</p><pre><em>kubectl </em>create configmap ApiConfigMap --from-literal API_HOST=http://apihost --from-literal STATIC_HOST=http://statichost --from-literal APP_HOST=http://apphost</pre><p>The manifest file is slightly different, as it now needs to also inject environment variables, but fill them with the contents of the secret. (I’ve only included one example of each).</p><pre><strong>apiVersion: </strong>apps/v1beta2<br><strong>kind: </strong>Deployment<br><strong>metadata:<br>  name: </strong>ApiName<br><strong>spec:<br>  replicas: </strong>1<br>  <strong>selector:<br>    matchLabels:<br>      app: </strong>ApiName<br>  <strong>strategy:<br>    rollingUpdate:<br>      maxSurge: </strong>1<br>      <strong>maxUnavailable: </strong>1<br>    <strong>type: </strong>RollingUpdate<br>  <strong>template:<br>    metadata:<br>      labels:<br>        app: </strong>ApiName<br>    <strong>spec:<br>      containers:<br>      </strong>- <strong>env:<br>        </strong>- <strong>name: </strong>API_HOST<br>          <strong>valueFrom:<br>            configMapKeyRef:<br>              key: </strong>API_HOST<br>              <strong>name: </strong>ApiConfigMap<br>        - <strong>name: </strong>MONGO_HOST<br>          <strong>valueFrom:<br>            secretKeyRef:<br>              key: </strong>MONGO_HOST<br>              <strong>name: </strong>ApiMongoSecret<br>        <strong>name: </strong>ApiName<br>        <strong>image: </strong>ApiDockerImageName<br>        <strong>livenessProbe:<br>          failureThreshold: </strong>3<br>          <strong>httpGet:<br>            path: </strong>/customendpoint<br>            <strong>port: </strong>6000<br>            <strong>scheme: </strong>HTTP<br>          <strong>initialDelaySeconds: </strong>60<br>          <strong>periodSeconds: </strong>60<br>          <strong>successThreshold: </strong>1<br>          <strong>timeoutSeconds: </strong>2<br>        <strong>readinessProbe:<br>          failureThreshold: </strong>3<br>          <strong>httpGet:<br>            path: </strong>/customendpoint<br>            <strong>port: </strong>6000<br>            <strong>scheme: </strong>HTTP<br>          <strong>initialDelaySeconds: </strong>60<br>          <strong>periodSeconds: </strong>60<br>          <strong>successThreshold: </strong>1<br>          <strong>timeoutSeconds: </strong>2<br>        <strong>ports:<br>        </strong>- <strong>containerPort: </strong>6000</pre><p>Note that this manifest also has a livenessProbe and readinessProbe configuration. By default, ingress will query ‘/’ of a backend and expect a 200 result to know whether the instance is “OK”. Since in our case we don’t have anything serving from / for the api, we override this check here.</p><p>As far as I understood, this will also be the endpoints that the deployments will use to know whether a pod is in an error state, so that it can stop &amp; restart them.</p><p>And as before, apply the manifest file &amp; expose it as a cluster ip service:</p><pre><em>kubectl </em>apply -f ApiManifest.yml<br><em>kubectl </em>expose deployment ApiName</pre><h3>Creating the Google Storage reverse proxy</h3><p>Again, the steps to deploy this proxy are the same. This probably could also be configured with an ingress, but we had no time to investigate this. Our docker is an nginx with the following config:</p><pre>user  nginx;<br>worker_processes  2;<br><br>error_log  /var/log/nginx/error.log warn;<br>pid        /var/run/nginx.pid;<br><br>load_module /usr/lib/nginx/modules/ngx_http_perl_module.so;<br><br>env GS_BUCKET;<br>env INDEX;<br><br>events {<br>    worker_connections  10240;<br>}<br><br><br>http {<br>    include       /etc/nginx/mime.types;<br>    default_type  application/octet-stream;<br><br>    log_format  main  &#39;$remote_addr - $remote_user [$time_local] &quot;$request&quot; &#39;<br>                      &#39;$status $body_bytes_sent &quot;$http_referer&quot; &#39;<br>                      &#39;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;&#39;;<br><br>    access_log  /var/log/nginx/access.log  main;<br><br>    sendfile        on;<br><br>    keepalive_timeout  65;<br><br>    resolver                   8.8.8.8 valid=300s ipv6=off;<br>    resolver_timeout           10s;<br><br>    upstream gs {<br>        server                   storage.googleapis.com:443;<br>        keepalive                128;<br>    }<br><br>    perl_set $bucket_name &#39;sub { return $ENV{&quot;GS_BUCKET&quot;}; }&#39;;<br>    perl_set $index_name  &#39;sub { return $ENV{&quot;INDEX&quot;} || &quot;index.html&quot;; }&#39;;<br><br>     gzip on;<br>      gzip_static on;<br>      gzip_disable &quot;msie6&quot;;<br>      gzip_vary on;<br>      gzip_proxied any;<br>      gzip_comp_level 6;<br>      gzip_buffers 16 8k;<br>      gzip_http_version 1.0;<br>      gzip_min_length 256;<br>      gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon application/octet-stream;<br><br>    server_tokens off;<br><br>    server {<br>        if ( $request_method !~ &quot;GET|HEAD&quot; ) {<br>            return 405;<br>        }<br><br><br>        location ~ /(.*) {<br>            set $query $1;<br>            proxy_set_header    Host storage.googleapis.com;<br>            proxy_pass          https://gs/$bucket_name/$query;<br>            proxy_http_version  1.1;<br>            proxy_set_header    Connection &quot;&quot;;<br><br>            proxy_intercept_errors on;<br>            proxy_hide_header       alt-svc;<br>            proxy_hide_header       X-GUploader-UploadID;<br>            proxy_hide_header       alternate-protocol;<br>            proxy_hide_header       x-goog-hash;<br>            proxy_hide_header       x-goog-generation;<br>            proxy_hide_header       x-goog-metageneration;<br>            proxy_hide_header       x-goog-stored-content-encoding;<br>            proxy_hide_header       x-goog-stored-content-length;<br>            proxy_hide_header       x-goog-storage-class;<br>            proxy_hide_header       x-xss-protection;<br>            proxy_hide_header       accept-ranges;<br>            proxy_hide_header       Set-Cookie;<br>            proxy_ignore_headers    Set-Cookie;<br>        }<br>    }<br>}</pre><p>The environment variables here are needed to specify to which bucket that we will proxy. Again, this keep the image generic.</p><p>We create the configmap:</p><pre><em>kubectl </em>create configmap StorageProxyConfigMap --from-literal GS_BUCKET=&lt;NameOfTheStorageBucket&gt;</pre><p>The manifest file that will kick off the deployment:</p><pre><strong>apiVersion: </strong>apps/v1beta2<br><strong>kind: </strong>Deployment<br><strong>metadata:<br>  name: </strong>StorageProxyName<br><strong>spec:<br>  replicas: </strong>1<br>  <strong>selector:<br>    matchLabels:<br>      app: </strong>StorageProxyName<br>  <strong>strategy:<br>    rollingUpdate:<br>      maxSurge: </strong>1<br>      <strong>maxUnavailable: </strong>1<br>    <strong>type: </strong>RollingUpdate<br>  <strong>template:<br>    metadata:<br>      labels:<br>        app: </strong>StorageProxyName<br>    <strong>spec:<br>      containers:<br>      </strong>- <strong>env:<br>        </strong>- <strong>name: </strong>GS_BUCKET<br>          <strong>valueFrom:<br>            configMapKeyRef:<br>              key: </strong>GS_BUCKET<br>              <strong>name: </strong>StorageProxyConfigMap<br>        <strong>name: </strong>StorageProxyName<br>        <strong>image: </strong>StorageProxyImageName<br>        <strong>ports:<br>        </strong>- <strong>containerPort: </strong>80</pre><p>And tell kubernetes what to do:</p><pre><em>kubectl </em>apply -f StorageProxyManifest.yml<br><em>kubectl </em>expose deployment StorageProxyName</pre><h3>Installing Nginx Ingress</h3><p>At this point we have the three images running in their container/pod/deployments, and they’re all exposed as a service, but they’re not yet accessible from the outside. For this we will install an ingress load balancer.</p><p>Ingress runs also in two parts, by installing it you setup the ‘nginx-ingress-controller’ deployment, which runs the actual nginx.</p><p>Afterwards, you can create Ingress resources, which are picked up by the controller and configure the nginx.</p><p><em>(By default, gcloud provides their own controller for this, but we opted for the nginx, since we could match our existing nginx config more closely.)</em></p><pre><em>helm </em>install --name nginx-ingress stable/nginx-ingress --set rbac.create=true<br><em>kubectl </em>apply -f /tmp/manifests-generated/ingress-resource.yml</pre><p><em>(RBAC option is for role based access control, something we have not explored further).</em></p><p>This will create two controllers, the nginx-ingress-controller, and the nginx-ingress-default-backend, to which all the non-matched urls will route.</p><p>To configure ingress, we create the following resource:</p><pre><strong>apiVersion: </strong>extensions/v1beta1<br><strong>kind: </strong>Ingress<br><strong>metadata:<br>  annotations:<br>    ingress.kubernetes.io/ssl-redirect: </strong>&quot;true&quot;<br>    <strong>kubernetes.io/ingress.class: </strong>nginx<br>    <strong>nginx.ingress.kubernetes.io/force-ssl-redirect: </strong>&quot;true&quot;<br>    <strong>nginx.ingress.kubernetes.io/rewrite-target: </strong>/<br>  <strong>name: </strong>IngressName<br><strong>spec:<br>  rules:<br>  </strong>- <strong>host: </strong>sub.host.com<br>    <strong>http:<br>      paths:<br>      </strong>- <strong>backend:<br>          serviceName: </strong>AppServiceName<br>          <strong>servicePort: </strong>80<br>        <strong>path: </strong>/<br>      - <strong>backend:<br>          serviceName: </strong>ApiServiceName<br>          <strong>servicePort: </strong>6000<br>        <strong>path: </strong>/api/<br>      - <strong>backend:<br>          serviceName: </strong>StorageProxyServiceName<br>          <strong>servicePort: </strong>80<br>        <strong>path: </strong>/static/<br>  <strong>tls:<br>  </strong>- <strong>hosts:<br>    </strong>- sub.host.com<br>    <strong>secretName: </strong>NameOfCertificateSecret</pre><p>This configuration will direct / to the app, requests to /api/ to the api, and /static/ to the storage proxy. The rewrite target annotation will ensure that /api/ &amp; /static/ are not sent to their backends, so for the call /api/todos/list, the api backend will receive it as /todos/list.</p><p>Note that we also configure SSL here by specifying from which secret it has to retrieve the certificate details. This is something we configure when setting up cert manager. Basically, the ingress expects a validated certificate from this secretname, otherwise you will have a fake self signed one.</p><p>Also note that while this ingress has now an external IP, this IP is not static, to do this, it has to be promoted to a static IP. This can be done through the google cloud console (VPC Networks -&gt; external IP -&gt; changing ephemeral to static, or via console:</p><pre>IP_ADDRESS=<strong>$</strong><em>(kubectl describe service nginx-ingress-controller --namespace=$NAMESPACE | grep &#39;LoadBalancer Ingress&#39; | rev | cut -d: -f1 | rev | xargs)<br></em><br><em>gcloud </em>compute addresses create NameOfStaticIp --addresses $IP_ADDRESS --region europe-west1</pre><p>This command will lookup the IP adress for the ingress load balancer (note, works for us since we only have one, mileage may vary :-))</p><p>Then we promote it to a static IP.</p><h3>Installing cert-manager and the certificates</h3><p>So far we have the loadbalancer who has an external IP &amp; routes the requests to the different backends, at this moment, you can point the DNS at your IP.</p><p>Install cert-manager with helm:</p><pre><em>helm </em>install stable/cert-manager</pre><p>Create an issuer (Instance that provides certificates, in our case, Let’s Encrypt):</p><pre><strong>apiVersion: </strong>certmanager.k8s.io/v1alpha1<br><strong>kind: </strong>Issuer<br><strong>metadata:<br>  name: </strong>NameForIssuer<br><strong>spec:<br>  acme:<br>    </strong><em># The ACME server URL<br>    </em><strong>server: </strong>https://acme-v02.api.letsencrypt.org/directory<br>    <em># Email address used for ACME registration<br>    </em><strong>email: </strong>&quot;yourmail@domain.com&quot;<br>    <em># Name of a secret used to store the ACME account private key<br>    </em><strong>privateKeySecretRef:<br>      name: </strong>IssuerPrivateKeyName<br>    <em># Enable the HTTP-01 challenge provider<br>    </em><strong>http01: </strong>{}</pre><p>Create a certificate:</p><pre><strong>apiVersion: </strong>certmanager.k8s.io/v1alpha1<br><strong>kind: </strong>Certificate<br><strong>metadata:<br>  name: </strong>CertificateName<br><strong>spec:<br>  secretName: </strong>NameOfCertificateSecret<br>  <strong>commonName: </strong>sub.host.com<br>  <strong>dnsNames:<br>  </strong>- sub.host.com<br>  <strong>issuerRef:<br>    name: </strong>NameForIssuer<br>    <strong>kind: </strong>Issuer<br>  <strong>acme:<br>    config:<br>    </strong>- <strong>http01:<br>        ingressClass: </strong>nginx<br>      <strong>domains:<br>      </strong>- sub.host.com</pre><p>Finally, apply them:</p><pre><em>kubectl </em>apply -f issuer.yml<br><em>kubectl </em>apply -f certificate.yml</pre><p>Once you apply these resources, cert-manager will pick up the fact that the certificate needs validation. It will create a new ingress that hosts the ACME challenge, it will also start a pod that executes the requests to Let’s Encrypt.</p><p>Once the validation is complete, it will store the details in the secret (which we also used earlier for the ingress).</p><p>There might be some delay in the validation, but normally, after a few minutes, your should be able to visit your host and see that it is secured!</p><p><strong>Note: </strong>Found some confusing information regarding setting up cert-manager. I think it can be setup in two ways. The one described above, where you manually create issuer/certificate and let cert-manager do its thing.</p><p>The other would be where you configure ingress with annotations, so that cert-manager picks that up. In our config, no specific annotations are needed for this.</p><h3>Appendix</h3><h4>Setting up GCloud CLI</h4><p>There are two options here, the Google Cloud shell, or from your favorite local terminal. Alternatively you can wrap the gcloud command with docker:</p><pre><strong>FROM </strong>google<strong>/</strong>cloud-sdk:latest<br><strong>RUN </strong>curl <strong>-</strong>o get_helm.sh https:<strong>//</strong>raw.githubusercontent.com<strong>/</strong>kubernetes<strong>/</strong>helm<strong>/</strong>master<strong>/</strong>scripts<strong>/</strong>get<br><strong>RUN </strong>chmod <strong>+</strong>x get_helm.sh<br><strong>RUN </strong>.<strong>/</strong>get_helm.sh</pre><p>Helm can best be described as a package manager for kubernetes, you will install nginx-ingress and certmanager with this tool. It runs as a client/server architecture, with helm being the cli tool you use, and tiller the server (which we will install later on the cluster).</p><p>If you create a container from this docker, and run that container, login sessions should be persisted. The volume in this case is a scripts folder that is shared between host/docker so we can add files/scripts to run on the cloud.</p><pre><em>docker </em>create -v <strong>$</strong><em>(pwd)</em>/scripts:/scripts -w=&quot;/scripts&quot; \<br> --name=&lt;container-name&gt; -it gcloud-platform:latest /bin/bash</pre><pre><em>docker </em>start -ia &lt;container-name&gt;</pre><p>After having installed gcloud in the flavour you prefer, you can login with:</p><p>gcloud auth login --brief</p><p>It should show you a link to a token that you have to copy in the terminal. After login, set your project ID &amp; compute zones with:<br>gcloud config set project &lt;PROJECT_ID&gt;</p><p>gcloud config set compute/zone &lt;ZONE&gt;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf134b7e406e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/setting-up-google-cloud-with-kubernetes-nginx-ingress-and-lets-encrypt-certmanager-bf134b7e406e">Setting up Google Cloud with Kubernetes, Nginx Ingress and Let’s Encrypt (Certmanager)</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A tale of three(.js) snapshots and Angular 2 or how memory leaks!]]></title>
            <link>https://medium.com/@driesdesmet_69747/a-tale-of-three-js-snapshots-and-angular-2-or-how-memory-leaks-bad4e9882669?source=rss-48775017cf4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad4e9882669</guid>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Dries De Smet]]></dc:creator>
            <pubDate>Wed, 29 Nov 2017 12:04:14 GMT</pubDate>
            <atom:updated>2017-11-29T12:04:14.361Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>(Three.js v0.88.0 , Angular 4.x)</strong></p><p>In my current project I’m working on an 3D viewer backed by three.js and Angular 2. We have a list of scenes that you can walk through and we use Angular 2 services to handle things like navigation, rendering, retrieving models etc. One of the issues we had was that navigating back and forth the viewer, the GPU memory usage would not go down. In this post I’ll share my experiences on how I’ve handled the issue.</p><p>Credits to: <a href="https://stackoverflow.com/a/19726918">https://stackoverflow.com/a/19726918</a> for putting me on the right track.</p><p>Our first solution to solving the issue was providing a close button that would reload the app at the given url e.g &lt;a href=&quot;/scans/123&quot;&gt;&lt;/a&gt;</p><p>This would reload the entire application &amp; the browser would do the cleanup for us. It would only benefit people using that button as using the back button would bypass this (there are probably tricks do force a hard refresh on using the back button, but then we’re heading down another rabbit hole), seeing we’re working on a SPA experience, we better do the cleaning up ourselves.</p><p>I’ve started by following the stack overflow advice of taking three snapshots so you have a good view on what objects are not collected.</p><p>The first snapshot was of the details page when it was first loaded. It would show me the scenes that you can load to navigate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0P4rbEfuuPXfnWWoXTWjw.png" /><figcaption>Starting at 80mb</figcaption></figure><p>The second snapshot is after loading the viewer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iIZ5UFRkM3py0j_NtiUCQ.png" /><figcaption>Increased to 133mb</figcaption></figure><p>And then the final snapshot is after navigating back to the details page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIugNDNdolVRMKcxb1AOog.png" /><figcaption>Increased even further to 144mb</figcaption></figure><p>In this last snapshot we notice that the heap size did not decrease despite navigating away from the viewer. If we look at the GPU memory in the same fashion (through chrome’s task manager), we can also spot that this memory is not cleared for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*Bg_WioMAsNv457b9zTMKIw.png" /><figcaption>First snapshot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*31eJKCY6Ub514IgC74bvBw.png" /><figcaption>Second snapshot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*afMXuKvXgAYPn3931sKNiw.png" /><figcaption>Third snapshot, GPU memory did not decrease</figcaption></figure><p>Using the snapshots that were made, we can make a comparison. We can check which objects are still present in the third snapshot but were made between the first &amp; second (e.g. loading the viewer):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOVIicQgq0dumohG1F39qQ.png" /></figure><p>When comparing by retained size, we can see that a lot of BufferGeometry, BufferAttribute and Mesh objects are kept and not collected. These are three.js objects that we no longer need outside the viewer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMXOfRQ0RjVSAgFkNKlehg.png" /></figure><p>We can also see that the state of the services used by the viewer is kept in memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsYzFchkTuctxrlPsiEcOQ.png" /></figure><p>This leads to two things that we can do. All our services are provided by a module, making them effectively singletons. This means that navigating around does not remove them. Considering that in our case, all the services in this module are only needed by the component that shows the viewer/threejs rendering, we can isolate the services to this component only by letting the component do the work of providing them.</p><pre>@NgModule({<br>    imports: [<br>        ...<br>    ],<br>    declarations: [<br>        ....<br>    ],<br>    entryComponents: [<br>    ],<br>    providers: [<br>        SnapshotService,<br>        AnimationService,<br>        RenderService,<br>        ...<br>    ]<br>})<br><strong>export class </strong>ViewerModule {<br>}</pre><pre><strong>public </strong>destroy() {<br>    <strong>this</strong>._scene = undefined;<br>}</pre><p>We remove the providers from the module &amp; add them to the viewer component.</p><pre>@Component({<br>    template: `...`,<br>    providers: [<br>        SnapshotService,<br>        AnimationService,<br>        RenderService,<br>        ...<br>    ]<br>})</pre><p>This gives us the advantage of Angular destroying the services when the viewer component is no longer in the DOM + provide a hook to do additional cleaning when these services are destroyed through the use of the ngOnDestroy() hook that it provides.</p><p>That’s the first part taken care of. The second part was to look at how three.js cleans up GPU memory. Some googling teaches you that it doesn’t do it for you, every mesh, geometry or material that you make and add to the scene have to be cleaned up manually. So our current code does not quite cut it:</p><pre><strong>public </strong>destroy() {<br>    <strong>this</strong>._scene = undefined;<br>}</pre><p>It will only dereference the scene, but do nothing on the GPU side. Seeing that we now have services that are only scoped to the viewer, we can take advantage of the destroy hook by letting your service implement OnDestroy. After the viewer is removed from the DOM (by navigating away), it no longer needs the services, so angular destroys them &amp; triggers the hook.</p><pre>@Injectable()<br><strong>export class </strong>WorldService <strong>implements </strong>OnDestroy {<br>    <strong>private </strong>_scene: Scene;<br><br>    <strong>public </strong>ngOnDestroy() {<br>        <strong>this</strong>._scene = undefined;<br>    }<br><br>}</pre><p>Next up is implementing the GPU cleanup of the scene <br>(Credits: <a href="https://stackoverflow.com/a/33199591">https://stackoverflow.com/a/33199591</a>)</p><pre>ngOnDestroy(): <strong>void </strong>{<br>    console.log(&quot;OnDestroy - WorldService&quot;);<br>    <strong>while </strong>(<strong>this</strong>._scene.children.length &gt; 0) {<br>        <strong>let </strong>obj = <strong>this</strong>._scene.children[0];<br>        <strong>this</strong>._scene.remove(obj);<br>        <strong>this</strong>.disposeHierarchy(obj, <strong>this</strong>.disposeNode);<br><br>    }<br>    <strong>this</strong>._scene = <strong>null</strong>;<br>}</pre><p>We iterate through the child objects of the scene, remove them, and then dispose of them on GPU side.</p><pre><strong>private </strong>disposeHierarchy(node, callback) {<br>    <strong>for </strong>(<strong>var </strong>i = node.children.length - 1; i &gt;= 0; i--) {<br>        <strong>var </strong>child = node.children[i];<br>        <strong>this</strong>.disposeHierarchy(child, callback);<br>        callback(child);<br>    }<br>}</pre><p>This will iterate through any sub children that the node has and then dispose of the child itself.</p><pre><strong>private </strong>disposeNode(node) {<br>    <strong>if </strong>(node <strong>instanceof </strong>Mesh) {<br>        node.parent = undefined;<br>        <strong>if </strong>(node.geometry) {<br>            node.geometry.dispose();<br>        }<br><br>        <strong>let </strong>material: <strong>any </strong>= node.material;<br>        <strong>if </strong>(material) {<br><br>            <strong>if </strong>(material.map) material.map.dispose();<br>            <strong>if </strong>(material.lightMap) material.lightMap.dispose();<br>            <strong>if </strong>(material.bumpMap) material.bumpMap.dispose();<br>            <strong>if </strong>(material.normalMap) material.normalMap.dispose();<br>            <strong>if </strong>(material.specularMap) material.specularMap.dispose();<br>            <strong>if </strong>(material.envMap) material.envMap.dispose();<br><br>            material.dispose();<br>        }<br>    } <strong>else if </strong>(node <strong>instanceof </strong>Object3D) {<br>        node.parent.remove(node);<br>        node.parent = undefined;<br>    }<br>}</pre><p>Basically, we check if the child has any geometry or material, and then remove it manually. After taking additional snapshots and comparing them, I’ve noticed that some of the Object3D objects were also kept because of parent references.</p><p>Taking new snapshots after these changes shows that the GPU memory drops back after navigating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*nzMhTLtXuQzW36JTIMA0aQ.png" /><figcaption>Before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*-4xtqWu_kpXquRl-ljJH-w.png" /><figcaption>During viewer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*fjqMRV17Ud8SUIYRt6uPMw.png" /><figcaption>After navigating back.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*aqW_8keb8DTL4oUoLfJJ6A.png" /><figcaption>The heap size lowers too!</figcaption></figure><p>We can notice that there’s still ~5mb more in data. We can use the memory tool to check what is still being retained, and by what.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*ekc3mh3DZ8fYhpW9VrqvIA.png" /></figure><p>For instance, we would not expect that something like FurnitureService is still retained after the component is destroyed. In the lower panel you can see that ViewportComponent is still referencing it, despite it being destroyed.</p><blockquote>After some navigating through the retainers and objects overviews I’ve found out that Angular 2 keeps some references to the previous view.</blockquote><p>After some navigating through the retainers and objects overviews I’ve found out that Angular 2 keeps some references to the previous view. This causes a chain of objects being retained, but if we navigate to yet another page, a new snapshot would show that there are no longer any references to the components or services that were created by the viewer.</p><p>Other things that are being retained are RX subscriptions and DOM event listeners, these can also linger if you do not unsubscribe() or removeEventListener(...).</p><p>The memory/snapshot functionally was new for me as I never really had to use it before, but it definitely helped me in this case to point me into the right direction. It also taught me a thing or two about the internals and how some references are kept, so it’s something fun to take a look at.</p><p>In our code there are still some tiny leaks that should be cleaned up, but seeing that these code changes already caused a massive drop in memory usage, we can now attend to other pressing issues.</p><p>Hope that sharing this experience helps you, and feel free to leave behind suggestions or tips!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad4e9882669" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>