<?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 Johnson Zhan on Medium]]></title>
        <description><![CDATA[Stories by Johnson Zhan on Medium]]></description>
        <link>https://medium.com/@johnsonzhan?source=rss-41350f042f5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9UasMVrlTDWyII-H4-FOsg.jpeg</url>
            <title>Stories by Johnson Zhan on Medium</title>
            <link>https://medium.com/@johnsonzhan?source=rss-41350f042f5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:36:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnsonzhan/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[GitLab Auto DevOps 深入淺出，自動部署，連設定檔不用？！]]></title>
            <link>https://medium.com/@johnsonzhan/gitlab-auto-devops-%E6%B7%B1%E5%85%A5%E6%B7%BA%E5%87%BA-%E8%87%AA%E5%8B%95%E9%83%A8%E7%BD%B2-%E9%80%A3%E8%A8%AD%E5%AE%9A%E6%AA%94%E4%B8%8D%E7%94%A8-89b4bc64d1bf?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89b4bc64d1bf</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 16:09:45 GMT</pubDate>
            <atom:updated>2020-03-04T16:09:45.897Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nMyswfep-1mgq3MCU4R4A.jpeg" /></figure><p>開發網站過程中，環境部署或是寫設定檔是一件不簡單的事。比起寫程式，寫設定檔不是開發過程中那麼「頻繁」需要做的事情，所以熟練度跟寫程式比起來多少有落差。</p><p>每次要部署或是做 CI / CD 相關的設定時，幾乎都是拿手邊的設定檔來修修改改，如果沒有什麼太特殊的功能，每個專案要做的設定也不會差太多。有沒有什麼服務可以幫我們把這些事做好，讓我們把程式推到 GitHub / GitLab 上的時候，就自動幫我們跑測試或是部署？</p><p>在以往只想得到 Heroku 的服務能自動部署，然而 GitLab Auto DevOps 也是能在沒什麼設定的情況下，幫忙我們跑完 CI / CD 的流程！</p><h4>目錄</h4><ul><li>深入淺出</li><li>什麼是 GitLab Auto DevOps</li><li>工具之間的關係</li><li>GitLab CI/CD 介紹</li><li>只要五十元！？沒有設定檔的 Auto Devops</li><li>快速建立 Rails 專案</li><li>用 GKE 設定 Cluster 好輕鬆</li><li>誒！又是設定檔！？</li><li>動手實作 Auto Devops</li><li>Build: 打包 Docker Image</li><li>Deploy: 部署/更新 Cluster</li><li>心得</li><li>參考資料</li></ul><blockquote>文章前半段會介紹使用到的工具，和他們之間的關係，後半段會介紹自己寫 .gitlab-ci.yml 來客製化 Auto Devops</blockquote><h4>什麼是 GitLab Auto DevOps</h4><p>GitLab 的 Auto DevOps 透過預先定義好的設定檔，來做到自動偵測、測試、部署等等工作，甚至讓我們可以用設定 GitLab 環境變數的方式，就一定程度調整 CI / CD 流程，是不是很方便呢？</p><p>但要使用 Auto DevOps 之前，他有四個前置任務</p><ul><li>Kubernetes (以下簡稱 K8S)</li><li>一個 K8S 的 Cluster，Auto DevOps 將會把網站部署到這個 Cluster，最簡單的方式是透過 Google 的 GKE 服務來設定</li><li>Base domain</li><li>需要有一個 wildcard 的 DNS 讓部署在這個環境的網站有 Domain name</li><li>GitLab Runner</li><li>一個可以跑 Docker 的 GitLab Runner，將會為由它來執行 CI / CD 的流程。如果用官方 GitLab 預設下可以直接使用官方的 shared Runners。</li><li>Prometheus (選用)</li><li>如果要使用 Auto Monitoring 功能的話才需要裝它，細節可以再看<a href="https://docs.gitlab.com/ee/topics/autodevops/">官方文件</a>說明XD</li></ul><p>完成以上任務並稍微設定 GitLab 後，再來就是把一份「沒有」gitlab-ci.yml 設定檔的專案推到 GitLab 上就能在 CI / CD Pipelines 看到 Auto DevOps 的成果囉！</p><blockquote>為什麼是「沒有」gitlab-ci.yml 設定檔的專案呢？其實 Auto DevOps 就是一份官方寫好的 gitlab-ci.yml，在啟動 Auto DevOps 的專案裡，如果找不到 gitlab-ci.yml 檔，那就會直接用官方 gitlab-ci.yml 去跑 CI / CD 流程。因此，如果想要客製化調整 Auto DevOps 也可以拿官方的 gitlab-ci.yml 來改！</blockquote><h4>工具之間的關係</h4><p>在摸索 Auto DevOps 過程中，最困難的地方就是搞不清楚每個工具、服務之間的關係，因為篇幅有限，我知道的也有限，所以就簡單說明它們之間的關係！更多內容說明請參考最下面列的參考資料。</p><blockquote>接下來會依序介紹 Docker、Kubernetes、Helm 和 GitLab Runners 這些工具<br> 如果已經有概念可以跳過</blockquote><h4>Docker 介紹</h4><p>Docker 是一個容器化技術，可以把 Process 隔離到獨立的空間，讓我們更好限制管理 Process 的資源、權限等。我們稱這個被隔離的 Process 和空間為 Docker Container (以下簡稱 Container)，要啟動 Container 需要有 Docker Image (以下簡稱 Image)，它們之間的關係有點像寫程式時，類別跟實體的關係，有了 Image 就能啟動 Container。我們可以透過 Dockerfile 客製化自己的 Image，而 Register 則是存放 Image 的倉庫。</p><h4>Kubernetes 介紹</h4><p>在一個複雜的系統裡，要如何管理那麼多 Container 呢？這時候就需要 Kubernetes 了！(以下簡稱 K8S)，K8S 可以自動化地部署及管理多台機器上的多個 Container，除了部署，它還有偵測並重新啟動系統中故障的容器等功能。在 K8S 中我們需要知道有以下幾個元件：</p><ul><li>Pod 是 K8S 中可以被部署的最小元件，一個 Pod 是由一到多個 Container 組成，同個 Pod 的不同 Container 之間彼此共享網路資源。 每個 Pod 都會有它的 yaml 檔，用以描述 Pod 會使用的 Image 還有連接的 Port 等資訊。</li><li>Node 就是一台機器、一台電腦或可以是 AWS 上的一個 EC2，在上面可以跑多個 Pod。其中 Node 又分成 Worker Node 和 Master Node 兩種，前者是實際運行 Pod 的機器，後者負責管理 Worker Node。</li><li>Cluster 是 K8S 中一個或多個 Node 的集合。本文會直接用 GCP 的 Google Kubernetes Engine (GKE) 服務來啟用 K8S Cluster。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waqcjxVw0PN4mRpY.png" /></figure><p>可以在上圖看到 Cluster 、 Node 還有 Pod 之間的關係，在 K8S 中可以用 kubectl 指令對 cluster 操作，使用 kubectl 後會透過 Master Node 上的 API server 收到來自使用者終端機的指令，再繼續透過 API server 來操作 Worker Node。</p><h4>Helm 介紹</h4><p>除了上述元件外，K8S 有大量的 resource object 像是可以做橫向擴展、控制 Pod 數量的 Deployment 或是控制 Pod 連線 port 的 Service 等等，要管理那麼多的 resource object 可能需要很多設定檔，並且使用很多次 kubectl 指令，如果系統複雜起來將難以管理！因此這時候就可以用 Helm 這個 K8S 的套件管理工具。</p><p>Helm 和 K8S 的關係圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XFih4UdWYPK7SH9a.png" /></figure><p>Helm 透過參數 (parameter) 跟模板 (template) 的方式，讓我們可以在只修改參數的方式重複利用模板。如上圖透過 values.yaml 設定參數再注入 deployment.yaml 這些模板中，最後透過 helm install 這類指令，把設定打包成一個 chart 並部署到 K8S cluster。使用 helm 的時候還需要在 Cluster 中建立 Tiller，他就像前面說到 kubectl 負責跟 API Server 溝通。</p><h4>GitLab Runners 介紹</h4><p>使用 GitLab 有兩種選擇，自己架 GitLab Server 或是註冊 <a href="https://gitlab.com/">gitlab.com</a> 直接用官方的服務，本文將使用官方 gitlab.com 並搭配它免費的 Shared Runners 來跑我們 CI/CD 的 Job。</p><p>誒！什麼是 Shared Runners 呢？為了要有 CI CD 的功能我們會把 .gitlab-ci.yml 放在專案的根目錄裡， GitLab 會依造 .gitlab-ci.yml 的設定產生 CI/CD Pipeline，每個 Pipeline 裡面可能有多個 Job，這時候就會需要有 GitLab Runner 來執行這些 Job 並把執行的結果回傳給 GitLab 讓它知道這個 Job 是否有正常執行。同樣的 Runner 也可以自行架設，或是在使用 gitlab.com 時，也能直接用官方的 Shared Runners。</p><h4>他們之間的關係</h4><p>介紹完 GitLab 還有 K8S 後，那麼 Auto Devops 到底是怎麼部署的呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EGeal5FPYaJK4yal.png" /></figure><p>再推了一個 commit 到 GitLab 後，依據 .gitlab-ci.yml 產生了對應的 CI/CD Pipeline，接著 Runner 就會去找 Pipeline 上的工作來執行，為了方便建立各種環境，很多 job 會用 Docker 的 Container 來跑，譬如把專案打包成 Docker Image 這工作又或是 helm 的操作都會在 Container 內執行。最後有了專案的 Image 以及設定好 helm chart 後，就會把它部署到 Cluster 上了！</p><blockquote>這樣介紹可能太簡略了，更多細節會在下方實作處再說明</blockquote><h4>GitLab CI/CD 介紹</h4><p>為接下來的 Auto Devops 做準備，我們需要對 .gitlab-ci.yml 的設定檔有一些了解，CI/CD Pipeline 是由 stage 還有 job 組成的，stage 是有順序性的，前面的 stage 完成後才會開始下一個 stage。如下圖，在有兩個 stage 的 Pipeline 時，如果上一個 stage 失敗，下一個 stage 就不會啟動。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*5wCt3I6pkpKVijHe.png" /></figure><p>每個 stage 裡面包含一到多個 Job，像是 stage_a 有 job1, job2 而 stage_b 有 job3 如下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*Rr2vQmOWJv061OVm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*ICOnCGCG5xoSQJXA.png" /></figure><p>要如何做出上圖的 Pipeline 呢？可以透過下面這個 gitlab-ci.yml</p><pre>stages:<br>  - stage_a<br>  - stage_b<br><br>job1:<br>  stage: stage_a<br>  script:<br>    - echo &#39;this is stage a job 1&#39;<br><br>job2:<br>  stage: stage_a<br>  script:<br>    - echo &#39;this is stage a job 2&#39;<br><br>job3:<br>  image: postgres:latest<br>  stage: stage_b<br>  script:<br>    - echo &#39;this is stage b job 3&#39;<br>    - psql --version</pre><p>在上圖可以看到有兩個 stage 依序為 stage_a 再 stage_b，每個 job 可以設定哪個 stage 會用這 job。另外可以注意 job3 設定哪個 Image 來啟動這個 job ，所以 job3 就是在 postgres Container 內運行的，也因此可以印出 postgres 的版本，Auto Devops 裡也會大量用到這種在指定 Container 內運行的工作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*QSObk9A3Fwduj7vH.png" /></figure><h3>只要五十元！？沒有設定檔的 Auto Devops</h3><p>介紹完工具之間關係後，終於可以來使用 GitLab 的 Auto Devops 了！我們會先練習一次沒有設定檔的版本，完成 GKE 跟 GitLab 基本設定然後部署成功後，才會進入到客製化 Auto Devops 的練習。</p><p>在最剛開始學習 Auto Devops 時，因為聽說是 K8S 整合 GitLab 的服務，所以知道都在本機跑十分麻煩，但要租用機器又需要白白燒錢，幸好這次練習中大部分服務都是免費或是有充足試用額度的，先是註冊 <a href="https://gitlab.com/">gitlab.com</a> 官方的服務，再搭配 GCP 的 Google Kubernetes Engine (GKE) 啟用 K8S Cluster，GCP 有 300 美元的試用額度，應該是蠻夠練習了。</p><p>最後是本文唯一需要花錢的地方，申請 wildcard 的 DNS ，我在 <a href="https://tw.godaddy.com/">godaddy</a> 找便宜的可能需要 50 元這樣。只要一份雞排的錢就能開始囉💪</p><blockquote>以下練習我用的 DNS 是 *.thejohnsonhi.site</blockquote><h4>快速建立 Rails 專案</h4><p>再來是要推上 GitLab 上面的專案，我用以下指令建出名為 auto_example 的 Rails 專案</p><pre># -T 省略測試<br># -d 指定使用的資料庫是 postgresql<br>rails new auto_example -T -d postgresql</pre><blockquote>版本資訊<br> Rails 6.0.2.1<br> Ruby 2.6.5</blockquote><p>然後用 scaffold 做出一些基本頁面</p><pre>rails generate scaffold user title start:time</pre><p>完成後還需要在 config/routes.rb 新增這路徑，確保首頁有內容可以通過 health checks</p><pre>root &#39;users#index&#39;</pre><h4>用 GKE 設定 Cluster 好輕鬆</h4><p>在 GitLab 開一個 Public 的專案</p><blockquote>開 private 的話還要注意使用 Container Registry 的權限問題</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKI8npqjA1PB1Tep.png" /></figure><p>到 Operations &gt; Kubernetes 選擇 GKE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MUFLE4ZHA2lGW9Fu.png" /></figure><p>我選擇 1 個 n1-standard-1 大小的機器</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*AFe7M2cqu_t3a_Pe.png" /></figure><p>填入申請好的 wildcard 的 DNS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n0Sveigj4gHuqSkB.png" /></figure><p>預設情況下，我們會啟用 GitLab-managed cluster 也就是 GitLab 可以幫我們在 Cluster 內安裝一些元件，這邊就一路把 Helm Tiller、Ingress、Cert-Manager、Prometheus 和 GitLab Runner 都裝起來吧</p><blockquote>可以注意到 Ingress 裝起來後會得到一組 IP ，也要記得設定 DNS 指到這組 IP</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q4jC8anb4CjoVF4p.png" /></figure><p>再來是到 Settings &gt; CI/CD 的 Auto DevOps 去勾選啟用</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3VwhM20pcve0prmW.png" /></figure><p>再來還需要設定幾個 CI/CD 需要的環境變數，如果是 Rails 搭配 postgres 最少需要設定這兩個</p><pre>DB_INITIALIZE = RAILS_ENV=production /bin/herokuish procfile exec bin/rails db:setup<br>DB_MIGRATE = RAILS_ENV=production /bin/herokuish procfile exec bin/rails db:migrate</pre><p>另外 Auto Devops 也提供只要設定環境變數就能一定程度客製化的選項，譬如我這邊設定就不會跑測試跟語法檢查</p><pre>CODE_QUALITY_DISABLED = true<br>TEST_DISABLED = true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NNSGqzk-W0rgmvMT.png" /></figure><p>完成以上步驟就把 Rails 專案推上來就能看到 Auto Devops 的 Pipeline 囉！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HcQYNxOtonC1vBm5.png" /></figure><p>然後變成</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j0XPkjZ4QwEky-ny.png" /></figure><p>所以說部署好的網站勒？可以到 Operations &gt; Environments 裡面看到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJhii2vnqemQKJyb.png" /></figure><p>點下去然後看到畫面，YA 都沒有用設定檔就部署成功了！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*xnZ_wwjfR_RMa5Dt.png" /></figure><p>希望大家最後有跑成功，假如有個萬一沒跑成功，可以先看 CI/CD 的 log 或是按 Retry 重新跑，如果還不行也能透過 GKE 的介面的 Cloud Shell 連到 K8S 內操作，以獲取更多資訊，可能會用到的指令有</p><pre># 查看 CLuster 內所有資源狀態<br>kubectl get all --all-namespaces</pre><pre># log 出特定 Pod 的內容<br># kubectl logs --namespace [namespace 名稱] [pod 名稱]<br>kubectl logs --namespace auto-example-16272281-production pod/production-b69b589b9-7x2vw</pre><blockquote>為了區別是誰的資源，這邊要特別注意 namespace 有沒有設定對，不然會找不到資料喔</blockquote><h4>誒！又是設定檔！？</h4><p>為了役物而不役於物，這篇號稱不用設定檔的文章，接下來設定檔講好講滿…</p><p>在沒有 .gitlab-ci.yml 的情況下完成了 Auto Devops，如果想要進一步的客製化，而且是改 GitLab 環境變數都無法實現的客製化，這時候還是得回到 .gitlab-ci.yml 設定檔，首先來測試一下在專案新增長這樣的 .gitlab-ci.yml</p><pre>image: alpine:latest<br><br>variables:<br>  POSTGRES_USER: user<br>  POSTGRES_PASSWORD: testing-password<br>  POSTGRES_ENABLED: &quot;true&quot;<br>  POSTGRES_DB: $CI_ENVIRONMENT_SLUG<br>  POSTGRES_VERSION: 9.6.2<br>  DOCKER_DRIVER: overlay2<br>  ROLLOUT_RESOURCE_TYPE: deployment<br>  DOCKER_TLS_CERTDIR: &quot;&quot;  # https://gitlab.com/gitlab-org/gitlab-runner/issues/4501<br><br>stages:<br>  - build<br>  - test<br>  - deploy  # dummy stage to follow the template guidelines<br>  - review<br>  - dast<br>  - staging<br>  - canary<br>  - production<br>  - incremental rollout 10%<br>  - incremental rollout 25%<br>  - incremental rollout 50%<br>  - incremental rollout 100%<br>  - performance<br>  - cleanup<br><br>include:<br>  - template: Jobs/Build.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml<br>  - template: Jobs/Test.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Jobs/Test.gitlab-ci.yml<br>  - template: Jobs/Code-Quality.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Jobs/Code-Quality.gitlab-ci.yml<br>  - template: Jobs/Deploy.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Jobs/Deploy.gitlab-ci.yml<br>  - template: Jobs/DAST-Default-Branch-Deploy.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Jobs/DAST-Default-Branch-Deploy.gitlab-ci.yml<br>  - template: Jobs/Browser-Performance-Testing.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Jobs/Browser-Performance-Testing.gitlab-ci.yml<br>  - template: Security/DAST.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Security/DAST.gitlab-ci.yml<br>  - template: Security/Container-Scanning.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Security/Container-Scanning.gitlab-ci.yml<br>  - template: Security/Dependency-Scanning.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Security/Dependency-Scanning.gitlab-ci.yml<br>  - template: Security/License-Management.gitlab-ci.yml  # https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Security/License-Management.gitlab-ci.yml<br>  - template: Security/SAST.gitlab-ci.yml  # <a href="https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml">https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml</a></pre><blockquote><a href="https://gitlab.com/gitlab-org/gitlab-foss">官方完整專案點我</a></blockquote><p>Auto Devops 就是去看專案中沒有 .gitlab-ci.yml 的話，就執行這個官方預設的 <a href="https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml">.gitlab-ci.yml</a> ，這是一份可以在很多環境下都跑的動的設定檔，他有許多 stage 和 template，如果要看更多設定要找註解起來的網址去看 template 裡面的設定。沒意外的話改成這份設定檔跑 CI/CD 也會通過喔！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QQLF6q7-Vlp5veZ5.png" /></figure><h3>動手實作 Auto Devops</h3><p>為了更了解裡面都做了什麼事，所以我參考了官方的 build 跟 production 這兩個 stage 的設定，自己客製化了一份 .gitlab-ci.yml，它有以下兩個 stage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*72JMs5-5XrR6rELn.png" /></figure><p>上圖是 build 階段</p><ol><li>在 Docker in Docker 的環境用 Dockerfile 打包 Image</li><li>把 Image 上傳 GitLab 的 Container Registry</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wo6aEry-CJ9SNIaa.png" /></figure><p>上圖是 production 階段</p><ol><li>取得 build 階段打包的 Image</li><li>取得 Chart Repository 上的 chart</li><li>用 helm upgrade 把 chart 部署到 K8S 上</li></ol><p>我的客製化 .gitlab-ci.yml 內容如下</p><pre>variables:<br>  POSTGRES_USER: user<br>  POSTGRES_PASSWORD: testing-password<br>  POSTGRES_ENABLED: &quot;true&quot;<br>  POSTGRES_DB: $CI_ENVIRONMENT_SLUG<br>  POSTGRES_VERSION: 9.6.2<br>  DB_MIGRATE: &#39;RAILS_ENV=production /bin/herokuish procfile exec bin/rails db:migrate&#39;<br>  TRACE: &#39;true&#39;<br><br>stages:<br>  - build<br>  - production<br><br>build:<br>  stage: build<br>  image: &quot;docker:stable&quot;<br>  services:<br>    - docker:stable-dind<br>  script:<br>    - export CI_APPLICATION_REPOSITORY=&quot;$CI_REGISTRY/johnsonzhan/auto_example/master&quot;<br>    - echo &quot;Logging to GitLab Container Registry with CI credentials...&quot;<br>    - docker login -u &quot;$CI_REGISTRY_USER&quot; -p &quot;$CI_REGISTRY_PASSWORD&quot; &quot;$CI_REGISTRY&quot;<br>    - docker image pull &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_BEFORE_SHA&quot; || \<br>    - docker build<br>      --cache-from &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_BEFORE_SHA&quot;<br>      --tag &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_SHA&quot; .<br>    - docker push &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_SHA&quot;<br><br>production:<br>  image: &quot;registry.gitlab.com/johnsonzhan/auto_example/deploy&quot;<br>  stage: production<br>  script:<br>    - auto-deploy preparation<br>    - auto-deploy deploy<br>  environment:<br>    name: production<br>    url: <a href="http://$ci_project_path_slug.$kube_ingress_base_domain/">http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN</a></pre><p>GitLab CI 的環境變數主要有三個來源，優先度高到低依序為</p><ul><li>Settings &gt; CI/CD 介面定義的變數</li><li>gitlab_ci.yml 定義環境變數</li><li>GitLab 預設環境變數</li></ul><blockquote>更多環境變數說明可以參考<a href="https://docs.gitlab.com/ee/ci/variables/">官方文件</a></blockquote><p>在這次練習中除了預設變數之外，其他變數都會放在 gitlab_ci.yml 方便說明</p><h4>Build: 打包 Docker Image</h4><p>把專案打包成 Docker Image 首先需要在專案下新增一份 Dockerfile</p><pre>FROM gliderlabs/herokuish as builder<br>COPY . /tmp/app<br>ENV USER=herokuishuser<br>RUN /bin/herokuish buildpack build<br><br>FROM gliderlabs/herokuish<br>COPY --chown=herokuishuser:herokuishuser --from=builder /app /app<br>ENV PORT=5000<br>ENV USER=herokuishuser<br>EXPOSE 5000<br>CMD [&quot;/bin/herokuish&quot;, &quot;procfile&quot;, &quot;start&quot;, &quot;web&quot;]</pre><blockquote>我直接參考 Auto Devops 裡面的做法，用 herokuish 提供的 Image 來打包專案</blockquote><p>再來是 gitlab_ci.yml 部分，在 build 階段要打包 Image，在 Runner 的環境中是沒有 docker 指令可以用的，所以這邊啟動一個 Docker Container 在裡面執行就可以用 docker 指令了。為了加速打包，我們都會先從 Container Registry 把上次的 Image 拉下來，放在下次要打包的 --cache-from 設定裡，其中 $CI_COMMIT_SHA $CI_COMMIT_BEFORE_SHA 這兩個都是 GitLab 預設環境變數，代表這次 commit 還有上次 commit 的 SHA 值。</p><pre>build:<br>  stage: build<br>  image: &quot;docker:stable&quot;<br>  services:<br>    - docker:stable-dind<br>  script:<br>    - export CI_APPLICATION_REPOSITORY=&quot;$CI_REGISTRY/johnsonzhan/auto_example/master&quot;<br>    - echo &quot;Logging to GitLab Container Registry with CI credentials...&quot;<br>    - docker login -u &quot;$CI_REGISTRY_USER&quot; -p &quot;$CI_REGISTRY_PASSWORD&quot; &quot;$CI_REGISTRY&quot;<br>    - docker image pull &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_BEFORE_SHA&quot; || \<br>    - docker build<br>      --cache-from &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_BEFORE_SHA&quot;<br>      --tag &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_SHA&quot; .<br>    - docker push &quot;$CI_APPLICATION_REPOSITORY:$CI_COMMIT_SHA&quot;</pre><p>在一開始最讓我疑惑就是使用 docker 這段</p><pre>image: &quot;docker:stable&quot;<br>services:<br>    - docker:stable-dind</pre><blockquote>為什麼需要兩個 Docker 的 Image ？他們有什麼不同？能只用一個嗎？</blockquote><p>可以先來測試本地跑兩種 docker 的差別，不指定 entrypoint 時</p><pre>docker run --privileged -it docker:stable</pre><p>stable 就會用 sh 來啟動</p><pre>/ #</pre><p>而 dind 則是直接啟動 docker daemon，此外 dind 還會自動產生 TLS certificates</p><pre>docker run --privileged -it docker:dind</pre><pre>Generating RSA private key, 4196 bit long modulus (2 primes)<br>....................................................................................................<br>...</pre><blockquote>為了在 Docker Container 內運行 Docker，會把 Host 上面的 Docker API 分享給 Container。通常這個 Docker API 是只有 Host 上面的 root 使用者才能用，所以如果 Container 有需要用 Docker API 就需要 TLS certificates 建立的安全連線。</blockquote><ul><li>docker:stable 有執行 docker 需要的執行檔，他裡面也包含要啟動 docker 的程式(docker daemon)，但啟動 Container 的 entrypoint 是 sh</li><li>docker:dind 繼承自 docker:stable，而且它 entrypoint 就是啟動 docker 的腳本，此外還會做完 TLS certificates</li></ul><p>說到這好像只要用 docker:stable-dind 就能完成 Docker in Docker 的操作了？對！差不多，可以試著把 gitlab_ci.yml 從用 dind 當作 services 改成用它當 Image</p><pre>build:<br>  stage: build<br>  image: &quot;docker:stable&quot;<br>  services:<br>      - docker:stable-dind</pre><p>改成</p><pre>build:<br>  stage: build<br>  image: &quot;docker:stable-dind&quot;</pre><p>改成這樣後運行 CI 時你可能會看到這問題</p><pre>error during connect: Get http://docker:2375/v1.40/containers/json: dial tcp: lookup docker on 169.254.169.254:53: no such host</pre><p>於是用 ps aux 指令發現 dind 沒有啟動 docker daemon，所以只好手動啟用囉，改成這樣</p><pre>build:<br>  image: &quot;docker:dind&quot;<br>  stage: build<br>  script:<br>    - docker-entrypoint.sh dockerd &amp;<br>    - sleep 15<br>    ...</pre><p>docker-entrypoint.sh dockerd &amp; 就是啟動 docker daemon 並在背景執行，然後 sleep 等他確定跑完就有 docker 能用了吧？</p><pre>error during connect: Get http://docker:2375/v1.40/containers/json: dial tcp: lookup docker on 169.254.169.254:53: no such host</pre><p>一樣的錯誤訊息</p><pre>$ ps aux<br> PID   USER     TIME  COMMAND<br>     1 root      0:00 /bin/sh<br>    14 root      0:00 /bin/sh<br>    16 root      0:00 dockerd<br>    33 root      0:00 containerd --config /var/run/docker/containerd/containerd.toml --log-level info<br>   144 root      0:00 ps aux</pre><p>而且這次確定有啟用 docker daemon，問題出在哪裡呢？剛剛說到 Container 要去連 Host 上的 Docker API 。但現在連線失敗卻是找 http://docker:2375，現在的 dind 已經不是被當做 services 來用了，而是要直接在裡面跑 Docker，所以他應該是要 unix:///var/run/docker.sock 用這種連線，於是把環境變數 DOCKER_HOST 從 tcp://docker:2375 改成空字串，讓 docker daemon 走預設連線就能成功囉！</p><h4>Deploy: 部署/更新 Cluster</h4><p>如果只是要在 Container 內執行一些 script 可以用 build stage 裡面的做法，直接把要做的事寫在gitlab_ci.yml 的 script 裡就好。但是要客製化 Image 內容的時候，可能就需要自己本地打包 Image 然後上傳到 GitLab Container Registry 了，接下來就要自己打包名為 registry.gitlab.com/johnsonzhan/auto_example/deploy 的 Image 了。</p><blockquote>接下來目標是讓客製化 Container 內可以用 auto-deploy 參數 指令的方式來操作。</blockquote><pre>production:<br>  image: &quot;registry.gitlab.com/johnsonzhan/auto_example/deploy&quot;<br>  stage: production<br>  script:<br>    - auto-deploy preparation<br>    - auto-deploy deploy<br>  environment:<br>    name: production<br>    url: <a href="http://$ci_project_path_slug.$kube_ingress_base_domain/">http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN</a></pre><p>Dockerfile 的部分會用 Gitlab 提供的 helm-install-image Image，在這環境下就可以直接使用 helm 指令。</p><p>Dockerfile</p><pre>FROM &quot;registry.gitlab.com/gitlab-org/cluster-integration/helm-install-image/releases/2.16.1-kube-1.13.12&quot;<br><br>COPY src/ build/<br><br># Install Dependencies<br>RUN apk add --no-cache openssl curl tar gzip bash<br><br>RUN ln -s /build/bin/* /usr/local/bin/</pre><p>在這邊我們會建立 src/bin/auto-deploy 腳本，然後在用 ln -s 的方式把它連結到執行檔目錄下，就是因為這樣才能使用 auto-deploy 參數 這些指令，以下是我們的 src/bin/auto-deploy</p><p>以下的 script 提供了兩種執行方式：</p><ul><li>auto-deploy preparation</li><li>helm init 建立 helm 專案</li><li>設定 tiller 在背景執行</li><li>設定 cluster 的 namespace</li><li>auto-deploy deploy</li><li>使用 helm upgrade 部署 chart 到 K8S 上</li><li>透過 — set 來設定要注入 template 的參數</li></ul><pre>#註解1<br>[[ &quot;$TRACE&quot; ]] &amp;&amp; set -x<br><br>export RELEASE_NAME=${HELM_RELEASE_NAME:-$CI_ENVIRONMENT_SLUG}<br>export auto_database_url=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${RELEASE_NAME}-postgres:5432/${POSTGRES_DB}<br>export DATABASE_URL=${DATABASE_URL-$auto_database_url}<br>export TILLER_NAMESPACE=$KUBE_NAMESPACE<br>export HELM_HOST=&quot;localhost:44134&quot;<br><br>function preparation() {<br>  local auto_chart=&quot;gitlab/auto-deploy-app&quot;<br><br>  helm init<br><br>  #註解2<br>  helm repo add gitlab https://charts.gitlab.io<br><br>  #註解3<br>  helm fetch ${auto_chart} --untar<br><br>  #註解4<br>  kubectl get namespace &quot;$KUBE_NAMESPACE&quot; || kubectl create namespace &quot;$KUBE_NAMESPACE&quot;<br><br>  #註解5<br>  nohup tiller -listen ${HELM_HOST} &gt;/dev/null 2&gt;&amp;1 &amp;<br>  echo &quot;Tiller is listening on ${HELM_HOST}&quot;<br>}<br><br>function deploy() {<br>  local track=&quot;stable&quot;<br>  local name=&quot;production&quot;<br><br>  #註解6<br>  local image_repository=${CI_APPLICATION_REPOSITORY:-$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG}<br>  local image_tag=${CI_APPLICATION_TAG:-$CI_COMMIT_SHA}<br>  local service_enabled=&quot;true&quot;<br>  local postgres_enabled=&quot;$POSTGRES_ENABLED&quot;<br>  local secret_name=&#39;&#39;<br><br>  echo &quot;Deploying new $track release...&quot;<br>  helm upgrade --install \<br>    --wait \<br>    --set service.enabled=&quot;$service_enabled&quot; \<br>    --set gitlab.app=&quot;$CI_PROJECT_PATH_SLUG&quot; \<br>    --set gitlab.env=&quot;$CI_ENVIRONMENT_SLUG&quot; \<br>    --set gitlab.envName=&quot;$CI_ENVIRONMENT_NAME&quot; \<br>    --set gitlab.envURL=&quot;$CI_ENVIRONMENT_URL&quot; \<br>    --set releaseOverride=&quot;$RELEASE_NAME&quot; \<br>    --set image.repository=&quot;$image_repository&quot; \<br>    --set image.tag=&quot;$image_tag&quot; \<br>    --set image.pullPolicy=IfNotPresent \<br>    --set image.secrets[0].name=&quot;$secret_name&quot; \<br>    --set application.track=&quot;$track&quot; \<br>    --set application.database_url=&quot;$DATABASE_URL&quot; \<br>    --set service.commonName=&quot;le-$CI_PROJECT_ID.$KUBE_INGRESS_BASE_DOMAIN&quot; \<br>    --set service.url=&quot;$CI_ENVIRONMENT_URL&quot; \<br>    --set replicaCount=1 \<br>    --set postgresql.enabled=&quot;$postgres_enabled&quot; \<br>    --set postgresql.nameOverride=&quot;postgres&quot; \<br>    --set postgresql.postgresDatabase=&quot;$POSTGRES_DB&quot; \<br>    --set postgresql.imageTag=&quot;$POSTGRES_VERSION&quot; \<br>    --set application.migrateCommand=&quot;$DB_MIGRATE&quot; \<br>    --namespace=&quot;$KUBE_NAMESPACE&quot; \<br>    &quot;$name&quot; \<br>    auto-deploy-app/<br>}<br><br>## End Helper functions<br><br>option=$1<br>case $option in<br>  preparation) preparation ;;<br>  deploy) deploy ;;<br>  *) exit 1 ;;<br>esac</pre><pre>[[ &quot;$TRACE&quot; ]] &amp;&amp; set -x</pre><blockquote>註解1：<br> 如果有環境變數 TRACE 就 set -x，這樣就能在執行前，顯示指令內容。</blockquote><pre>helm repo add gitlab <a href="https://charts.gitlab.io/">https://charts.gitlab.io</a></pre><blockquote>註解2：<br> 註冊一個 Chart Repository<br> 可以用 helm repo list 看看現在有註冊哪些 Chart Repository</blockquote><pre>helm fetch ${auto_chart} --untar</pre><blockquote>註解3：<br> 把 repo 裡的 helm 專案抓下來，好奇裡面長什麼樣子的話，也可以在本機用這行把他抓下來<br> helm fetch gitlab/auto-deploy-app --untar</blockquote><pre>kubectl get namespace &quot;$KUBE_NAMESPACE&quot; || kubectl create namespace &quot;$KUBE_NAMESPACE&quot;</pre><blockquote>註解4：<br> 新增一個 namespace 之後部署的 resource object 都整理進去</blockquote><pre>nohup tiller -listen ${HELM_HOST} &gt;/dev/null 2&gt;&amp;1 &amp;</pre><blockquote>註解5：<br> nohup 可以讓你在離線或登出系統後，還能夠讓工作繼續進行<br> &gt;/dev/null 2&gt;&amp;1 是把正確輸出還有錯誤輸出都忽略掉<br> 最後的 &amp; 是讓工作背景執行</blockquote><pre>local image_repository=${CI_APPLICATION_REPOSITORY:-$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG}</pre><blockquote>註解6<br> 在不特別設定 CI_APPLICATION_REPOSITORY 的情況下，image_repository 的值就是預設環境變數 CI_REGISTRY_IMAGE/CI_COMMIT_REF_SLUG，實際上 Auto Devops 的 template 也大量使用這寫法。</blockquote><blockquote>先解釋這 :- 符號</blockquote><blockquote>A:-B 的意思是如果有 A 就用它，沒有就用 B</blockquote><blockquote>CI_REGISTRY_IMAGE 跟 CI_COMMIT_REF_SLUG 都是 GitLab 預設環境變數，在我的範例中</blockquote><blockquote>CI_REGISTRY_IMAGE 就是 registry.gitlab.com/johnsonzhan/auto_example</blockquote><blockquote>CI_COMMIT_REF_SLUG 就是 master</blockquote><p>完成 Dockerfile 還有 src/bin/auto-deploy 後，就能打包 Image 然後上傳囉！</p><pre>docker build . -t registry.gitlab.com/johnsonzhan/auto_example/deploy<br>docker push registry.gitlab.com/johnsonzhan/auto_example/deploy</pre><h4>心得</h4><p>這次練習除了認識了 K8S 跟 GitLab 的一些設定外，也透過看 Auto Devops 的 gitlab_ci.yml 裡的 template 認識了很多 Shell Scripts 的寫法，算是收穫很多！對我來說研究 Auto Devops 難度最高的地方就是太多工具整合在一起，搞不清楚他們之間的關係，出錯也不知道從何查起，尤其最一開始還挑戰用 RKE + rancher 來建 K8S Cluster，真的是從頭到尾都卡關，幸好過程中同事<a href="https://blog.frost.tw/">蒼時弦也</a>在卡關的時候幫我解惑，不然應該會研究到放棄XD</p><h4>參考資料</h4><p><a href="https://docs.gitlab.com/ee/topics/autodevops/">GitLab Auto DevOps</a></p><p><a href="https://ithelp.ithome.com.tw/users/20120986/ironman/2733">和艦長一起 30 天玩轉 GitLab</a></p><p><a href="https://medium.com/@C.W.Hu/kubernetes-basic-concept-tutorial-e033e3504ec0">Kubernetes 基礎教學（一）原理介紹</a></p><p><a href="https://blog.tilt.dev/2019/09/16/tips-on-moving-your-dev-env-from-docker-compose-to-kubernetes.html">Tips on Moving your Dev Env from Docker Compose to Kubernetes</a></p><p><a href="https://godleon.github.io/blog/Kubernetes/k8s-Helm-Introduction/">[Kubernetes] Package Manager — Helm 簡介</a></p><p><a href="http://linux.vbird.org/linux_basic/0320bash.php">鳥哥：認識與學習BASH</a>、<a href="http://linux.vbird.org/linux_basic/0340bashshell-scripts.php">學習 Shell Scripts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89b4bc64d1bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[自動產生 Docker，一鍵佈署不是夢 ！？]]></title>
            <link>https://medium.com/@johnsonzhan/%E8%87%AA%E5%8B%95%E7%94%A2%E7%94%9F-docker-%E4%B8%80%E9%8D%B5%E4%BD%88%E7%BD%B2%E4%B8%8D%E6%98%AF%E5%A4%A2-777df3c50550?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/777df3c50550</guid>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 16:07:03 GMT</pubDate>
            <atom:updated>2020-03-04T16:07:03.895Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QjafPNd0U0OLhDCYsktRQ.jpeg" /></figure><p>想要一鍵部署！？首先要一鍵產生 Docker Image！要產生 Docker Image 需要有個 Dockerfile，通常在寫 Dockerfile 時從選擇 base 的 Image 到 Container 啟動後要執行的指令都需要一行一行設定。不僅如此，如果想要優化 Docker Image 的大小，還需要使用許多的技巧…突然覺得，要做這些事也太多！有沒有現成的 gem 可以幫我們做到這些事呢？</p><p>有的！就是五倍的同事<a href="https://blog.frost.tw/">蒼時弦也</a>開發的 <a href="https://github.com/5xRuby/bankai-docker">bankai-docker</a> 這工具啦！其實這接下來就是要來介紹一下 bankai-docker 這個專案，從怎麼使用它到它的部分功能怎麼做出來的，都將一一為您介紹。</p><blockquote>文章內容可能會需要一些 Docker 跟 Ruby DSL 相關的知識，對這些內容有興趣可以參考這兩篇文章</blockquote><blockquote><a href="https://5xruby.tw/posts/deploying-your-docker-rails-app/">用 Docker 部署 Rails，原來是這樣！？</a> 和 <a href="https://5xruby.tw/posts/discover-ruby-block/">Ruby 探索：Blocks 深入淺出</a></blockquote><h4>目錄</h4><ul><li>bankai-docker 介紹</li><li>使用說明書</li><li>如何偵測專案下有哪些 gem ？</li><li>把需要的 Package 印在 Dockerfile 上吧！</li><li>啟動 Docker Container</li><li>心得</li></ul><h4>bankai-docker 介紹</h4><p>bankai-docker 可以讓我們用一行指令 rake docker:build 自動產生 Rails 專案的 Docker Image，同時它也有 DSL 可以客製化產生的 Docker Image，預設情況下 bankai-docker 產生的 Docker Image 會包含 Ruby, Node.js, Yarn 還有 Rails 專案下需要的 gem，因為有優化 Image 的大小的關係，預設情況下 Docker Image 大小會落在 180 MB 上下。</p><p>就讓我們來研究一下 bankai-docker 是如何產生 Docker Image 的吧！這篇文章的講解，我使用的環境是：</p><pre>Rails：5.2.3<br>Ruby：2.6.0<br>資料庫：postgresql<br>然後額外安裝以下 gem<br>gem &#39;pg&#39;<br>gem &#39;bankai&#39;<br>gem &#39;bankai-docker&#39;</pre><blockquote>目前 bankai-docker 還需要額外裝 bankai 才能正常使用</blockquote><h4>使用說明書</h4><p>bankai-docker 透過 Ruby 的 DSL 讓我們可以客製化產生的 Docker Image，輸入rails generate bankai:docker:install 產生 config/docker.rb ，我們可以透過編輯 config/docker.rb 來產生不同的 Docker Image，以下是預設情況下 config/docker.rb 的內容</p><pre># frozen_string_literal: true<br><br># rubocop:disable Metrics/BlockLength<br>Bankai::Docker.setup do<br>  runtime_package &#39;tzdata&#39;, &#39;libstdc++&#39;, &#39;git&#39;<br><br>  stage :gem do<br>    package &#39;build-base&#39;, &#39;ca-certificates&#39;, &#39;zlib-dev&#39;, &#39;libressl-dev&#39;,<br>            runtime: false<br><br>    run &#39;mkdir -p /src/app&#39;<br><br>    add &#39;Gemfile&#39;, &#39;/src/app&#39;<br>    add &#39;Gemfile.lock&#39;, &#39;/src/app&#39;<br><br>    workdir &#39;/src/app&#39;<br>    run &#39;bundle install --deployment --without development test &#39; \<br>        &#39;--no-cache --clean &amp;&amp; rm -rf vendor/bundle/ruby/**/cache&#39;<br><br>    produce &#39;/src/app/vendor/bundle&#39;<br>    produce &#39;/usr/local/bundle/config&#39;<br>  end<br><br>  stage :node, from: &#39;node:10.15.2-alpine&#39; do<br>    run &#39;mv /opt/yarn-v${YARN_VERSION} /opt/yarn&#39;<br><br>    produce &#39;/usr/local/bin/node&#39;<br>    produce &#39;/opt/yarn&#39;<br>  end<br><br>  main do<br>    run &#39;mkdir -p /src/app&#39;<br><br>    env &#39;PATH=/opt/yarn/bin:/src/app/bin:$PATH&#39;<br>    env &#39;RAILS_ENV=production&#39;<br><br>    add &#39;.&#39;, &#39;/src/app&#39;<br>    workdir &#39;/src/app&#39;<br><br>    expose 80<br><br>    entrypoint &#39;docker-entrypoint&#39;<br>    cmd &#39;serve&#39;<br>  end<br>end<br># rubocop:enable Metrics/BlockLength</pre><p>可以透過 rake docker:preview 看看 config/docker.rb 產生的 Dockerfile 長什麼樣子</p><pre>FROM ruby:2.6.0-alpine AS gem<br>RUN apk add --no-cache postgresql-dev build-base ca-certificates zlib-dev libressl-dev<br><br>RUN  mkdir -p /src/app<br>ADD  Gemfile /src/app<br>ADD  Gemfile.lock /src/app<br>WORKDIR  /src/app<br>RUN  bundle install --deployment --without development test --no-cache --clean &amp;&amp; rm -rf vendor/bundle/ruby/**/cache<br><br>FROM node:10.15.2-alpine AS node<br><br><br>RUN  mv /opt/yarn-v${YARN_VERSION} /opt/yarn<br><br>FROM ruby:2.6.0-alpine<br>RUN apk add --no-cache tzdata libstdc++ git postgresql-libs<br>COPY --from=gem /src/app/vendor/bundle /src/app/vendor/bundle<br>COPY --from=gem /usr/local/bundle/config /usr/local/bundle/config<br>COPY --from=node /usr/local/bin/node /usr/local/bin/node<br>COPY --from=node /opt/yarn /opt/yarn<br>RUN  mkdir -p /src/app<br>ENV  PATH=/opt/yarn/bin:/src/app/bin:$PATH<br>ENV  RAILS_ENV=production<br>ADD  . /src/app<br>WORKDIR  /src/app<br>EXPOSE  80<br>ENTRYPOINT  [&quot;docker-entrypoint&quot;]<br>CMD  [&quot;serve&quot;]</pre><p>大概看一下這個 Dockerfile 可以知道，為了優化 Image 的大小，我們用了 3 個 stage 來產生我們要的 Image，一個是安裝 Rails 所需要的 gem，另一個是裝 Node.js 的，在處理完這兩個步驟後，只需要把必要的檔案放到主要的 stage 讓它產生 Image 即可。</p><p>稍微比對一下可以發現，幾乎 config/docker.rb 的每一行都可以對應到它產生的 Dockerfile，唯有以下兩行多裝了 postgresql？</p><pre>RUN apk add --no-cache tzdata libstdc++ git postgresql-libs<br><br>RUN apk add --no-cache postgresql-dev build-base ca-certificates zlib-dev libressl-dev</pre><p>config/docker.rb 中完全沒有做 postgresql 的相關設定，但產生的 Dockerfile 卻自動裝好了 postgresql？這就是 bankai-docker 貼心的地方啦，它會去偵測 Gemfile 中有使用的 gem 然後安裝對應的 Package，譬如我的 Gemfile 有使用 gem &#39;pg&#39; ，Dockerfile 上就會加上 postgresql 的 Package，這是哪裡設定的呢？bankai-docker 的 rake 執行的時候，第一步就是執行以下程式</p><pre>Bankai::Docker.setup do<br>  detect_package :database, :gem do |package|<br>    if gem?(&#39;pg&#39;)<br>      package.add_dependency &#39;postgresql-dev&#39;, runtime: false<br>      package.add_runtime_dependency &#39;postgresql-libs&#39;<br>    end<br><br>    if gem?(&#39;mysql2&#39;)<br>      package.add_dependency &#39;mariadb-dev&#39;, runtime: false<br>      package.add_runtime_dependency &#39;mariadb-client-libs&#39;<br>    end<br>  end<br><br>  detect_package :sassc, :gem do |package|<br>    package.add_runtime_dependency &#39;libstdc++&#39; if gem?(&#39;sassc&#39;)<br>  end<br><br>  detect_package :mini_magick, :gem do |package|<br>    package.add_runtime_dependency &#39;imagemagick&#39; if gem?(&#39;mini_magick&#39;)<br>  end<br>end</pre><blockquote>上面的 code 是原始碼的 templates/auto_packages.rb 檔案，這是目前 master 的程式，如果直接 gem install &#39;bankai-docker&#39; 載下來的套件可能跟這個不太一樣</blockquote><blockquote>再研究 gem 的過程很容易把原始碼玩壞，而且 gem 裡面也沒有 git 可以復原，這時候可以用 gem pristine bankai-docker 來讓 gem 復原唷！</blockquote><p>其實這邊的 DSL 就是一個一個去檢查 Gemfile 有裝哪些 gem ，用 gem? 方法檢查，如果有裝就用 package.add_dependency 或是 package.add_runtime_dependency 把對應的 Package 裝在 Dockerfile 裡面，看到這邊可能會好奇，誒！？就只有這麼幾行嗎？如果我還有其他需要裝 Package 的 gem 也在 Rails 專案中，這時 bankai-docker 產生的 Dockerfile 會有那個 Package 嗎？答案是不會ＸＤ，需要在 config/docker.rb 另外設定才能裝其它 Package。</p><h4>如何偵測專案下有哪些 gem ？</h4><p>剛剛前面說的用 gem? 方法檢查 Gemfile 有安裝哪些 gem ，這個是怎麼做到的呢？其實在 bankai-docker 的 lib/bankai/docker/dsl/gemfile.rb 檔案就是在做這件事</p><pre># frozen_string_literal: true<br><br>module Bankai<br>  module Docker<br>    module DSL<br>      # Gemfile detect<br>      module Gemfile<br>        def gem?(name)<br>          gemfile.match?(/^\s*gem .#{name}./)<br>        end<br><br>        private<br><br>        def gemfile<br>          @gemfile ||= ::File.read(Rails.root.join(&#39;Gemfile&#39;))<br>        end<br>      end<br>    end<br>  end<br>end</pre><p>使用 @gemfile ||= ::File.read(Rails.root.join(&#39;Gemfile&#39;)) 讀取專案中的 Gemfile 檔案，把它以 string 的狀態儲存在 @gemfile 變數中。接下來要找出 Gemfile 是否有安裝這個 gem，在這邊我們使用 match? 方法，裡面接的參數 (/^\s*gem .#{name}./) 是正規表達式，可以判斷 @gemfile 中是否有符合規則的字串，有的話就是符合 match? 的規則，正規表達式中的 ^\s*gem 代表</p><blockquote>從一行程式的開始可以有一個或多個空白，然後接上 gem 這個字</blockquote><p>為什麼要這樣設定呢？因為如果有些 gem 被註解掉像是# gem &#39;some_gem&#39;，這時候要判斷它不符合我們要找的規則，因為他不是 Gemfile 最後會裝的 gem。以上就是如何用 gem? 方法檢查 Gemfile 是否有安裝指定的 gem。</p><h4>把需要的 Package 印在 Dockerfile 上吧！</h4><p>可以透過 gem? 方法偵測專案使用哪些 gem 以後，要如何透過 add_dependency 方法將需要的 Package 印在 Dockerfile 上面呢？使用 add_dependency 的時候會呼叫 current_stage 或是 stage(:main) ，他們都是回傳實體變數 @stages 的方法，接著我們會在實體變數 @stages 上再使用 concat 把要註冊的 Package 存進去。</p><pre>def add_dependency(*packages, runtime: true)<br>  current_stage.concat(packages)<br>  stage(:main).concat(packages) if runtime<br>end</pre><p>完成以上工作後，就要用 template 來幫忙印出 Dockerfile， bankai-docker 中的 templates/stage.erb 是其中一個 template，在裡面用到 &lt;%= package_command %&gt;<br> 來處理 Dockerfile 裡面的 RUN apk add --no-cache ... 這行設定，就讓我們來看看 package_command 這方法怎麼做出來的吧！</p><pre>def package_command<br>  return unless Package.any?(@name)<br><br>  &quot;RUN #{Package.command_for @name}&quot;<br>end</pre><p>在 Package.any?(@name) 確認完 Package 的 @stages 不是空的後就用 Package.command_for @name 印出剛剛放在 @stages 裡面的 Package 套件名稱，以目前的例子</p><pre>&quot;RUN #{Package.command_for @name}&quot;</pre><p>將會變成</p><pre>&quot;RUN apk add --no-cache postgresql-dev build-base ca-certificates zlib-dev libressl-dev&quot;</pre><blockquote>更多更詳細 bankai-docker 中的 Package 的用法要看 lib/bankai/docker/package.rb 檔案</blockquote><p>以上就是簡略地說明 add_dependency 方法如何印 Package 的設定到 Dockerfile 上的，如果要完整知道過程還是需要把 bankai-docker 的 gem 拉到自己電腦跑跑看會比較清楚XD</p><h4>啟動 Docker Container</h4><p>講完 bankai-docker 大概是用什麼樣的方式做出來之後，另一個很重要的事情是，要怎麼讓這個 Docker Image 可以產生 Docker Container 跑起來？至少要跑起來才知道這 Image 是不是能用的，這邊我是用自己寫的 docker-compose.yml 來做的，以下是可以在本地端跑起來的設定</p><pre>version: &#39;3&#39;<br><br>services:<br>  db:<br>    image: postgres:9.6<br>    environment:<br>      - &quot;POSTGRES_USER=postgres&quot;<br>      - &quot;POSTGRES_PASSWORD=postgres&quot;<br>    networks:<br>      - johnson<br>  app:<br>    image: $(whoami)/[RAILS_APP_NAME]<br>    ports:<br>      - &quot;3000:80&quot;<br>    environment:<br>      - DATABASE_URL=postgres://postgres:postgres@db/postgres<br>      - SECRET_KEY_BASE=xxxxxx<br>      - RAILS_SERVE_STATIC_FILES=true<br>    networks:<br>      - johnson<br>    depends_on:<br>      - db<br>    command: &quot;rake db:migrate &amp;&amp; rake assets:precompile &amp;&amp; bundle exec puma -p 80&quot;<br><br>networks:<br>  johnson:</pre><p>如果你也想玩玩看用 Docker 跑 Rails 專案，可以設定一個 postgres 的 Container 來搭配。為了讓我 Rails 的 Container 跑起來之後，可以執行 rake db:migrate ，我在這邊用 docker-compose.yml 的 commond 設定 Container 跑起來後要執行的指令為 rake db:migrate &amp;&amp; rake assets:precompile &amp;&amp; bundle exec puma -p 80，這樣就能把 bankai-docker 產生的 Image 用 Container 在本地跑起來囉！</p><h4>心得</h4><p>研究 bankai-docker 過程，讓我更熟悉怎麼透過 multi-stage builds 的方式產生 Docker Image，要怎麼拆 stage？有哪些東西是要帶到主要的 stage 使用等等。同時，bankai-docker 中大量使用 DSL 的技巧，透過 block 的傳遞來讓使用者有更大的彈性來訂製 Dockerfile。目前 bankai-docker 還有許多功能仍在開發中，自動偵測哪些 gem 需要額外裝 Package 也是其中之一，上面的會偵測 mini_magick 的部分也是我寫這篇文章期間加上去的，看到自己加的功能讓有切圖功能的 Rails 專案用 Docker Container 跑起來後真的蠻有成就感的！希望未來有更多人可以對 bankai-docker 有興趣，一起來研究或是使用看看～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=777df3c50550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用 Docker 部署 Rails，原來是這樣！？]]></title>
            <link>https://medium.com/@johnsonzhan/%E7%94%A8-docker-%E9%83%A8%E7%BD%B2-rails-%E5%8E%9F%E4%BE%86%E6%98%AF%E9%80%99%E6%A8%A3-5fe9ff162fee?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe9ff162fee</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 16:01:15 GMT</pubDate>
            <atom:updated>2020-03-04T16:04:31.747Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mg6Ii8ibJPomegYj1tn8Ag.jpeg" /></figure><p>如果你曾經看過 Docker 相關的文章，對 Docker 有點認識但又不是太熟，需要找個主題來實作看看，那這篇文章就是為你準備的！我們將透過 Docker 部署一個 Rails 應用到 DigitalOcean 平台上，本文會一步一步介紹部署的過程。</p><h4>目錄</h4><ul><li>Docker 基本介紹</li><li>Docker 三大元素</li><li>設定檔</li><li>常用指令</li><li>實戰演練</li><li>步驟0: 簡單開一個 Rails 專案</li><li>步驟1: 開始加入 Docker</li><li>步驟2: Nginx 搭配 Puma</li><li>步驟3: 部署到雲端上吧！</li><li>步驟4: HTTPS 認證</li><li>步驟5: Docker image 瘦身</li><li>結論</li></ul><h4>Docker 基本介紹</h4><p>在程式開發的過程中，常常會發生環境不同或是系統設定有誤的情況，這樣的情況如果在本機重現不了 bug 真的很讓人頭痛，如果有一種技術可以讓我們本機的環境跟測試站、正式站一樣或是只要更接近一點，一定可以省下不少時間。於是 Docker 出現了，Docker 是現在當紅的虛擬化技術，它非常的輕量，啟動、停止是可以在幾秒內完成的那種，同時 Docker 對系統資源需求很少，甚至一台主機可以同時啟動數百甚至數千個 Docker 容器。為了要學習和體驗一下 Docker 的威力，所以我試著用 Docker 來部署我的 Rails 應用程式，這是個很好的機會讓我對不管是 Docker 技術還是環境部署都有更深一層的認識！</p><blockquote>礙於篇幅這邊只會簡要說明實作部分可能用到的名詞，更詳細的資料可能需要再 google 一下了</blockquote><h4>Docker 三大元素</h4><ul><li>Docker Image</li></ul><pre>Docker 映像檔，有點像虛擬機的映像檔，是一個能產生 Docker Container 的模板<br>之後文章中都簡寫成 Image</pre><ul><li>Docker Container</li></ul><pre>Docker 容器，就是用它來運行和隔離環境，它有點像簡易版的 Linux 環境<br>我們可以用 Docker Image 來建立 Docker Container，也能將它停止刪除等等<br>之後文章中都簡寫成 Container</pre><ul><li>Docker Registry</li></ul><pre>Docker 倉庫註冊伺服器，可以把我們的 Image 放上去<br>也能在其他機器把這些 Docker Image 下載下來<br>Docker Hub 就是 Docker 倉庫註冊伺服器的代表</pre><h4>設定檔</h4><ul><li>Dockerfile</li></ul><pre>可以設定自己客製化的 Docker Image</pre><ul><li>docker-compose.yml</li></ul><pre>docker-compose.yml 是個可以同時管理，啟動多個 Container 的工具</pre><h4>常用指令</h4><ul><li>docker images</li></ul><pre>列出目前機器上有的 Image</pre><ul><li>docker ps</li></ul><pre>列出目前機器上有運作中的 Container</pre><ul><li>docker exec -it &lt;Container ID&gt; bash</li></ul><pre>進入指定的 Container<br>-i 參數是本機電腦的鍵盤接到 Container 的 stdin<br>-t 參數是 Container 的 stdout 接到本機電腦的螢幕</pre><ul><li>docker run -it &lt;Image ID&gt; bash</li></ul><pre>用 Image 創建一個 Container 然後運行</pre><ul><li>docker rmi &lt;Image ID&gt;</li></ul><pre>刪除指定的 Image</pre><ul><li>docker rm &lt;Container ID&gt;</li></ul><pre>刪除指定的 Container</pre><ul><li>docker build .</li></ul><pre>依據 Dockerfile 的設定建立 Image</pre><ul><li>docker push NAME[:TAG]</li></ul><pre>上傳 Image 到 Docker Registry</pre><ul><li>docker pull NAME[:TAG]</li></ul><pre>從 Docker Registry 下載 Image 到本機</pre><ul><li>docker-compose up</li></ul><pre>啟動 docker-compose.yml 的設定，有 Container 就會啟動<br>沒 Container 也會從指定的 Image 生成</pre><h4>實戰演練</h4><p>看完 Docker 基本介紹可能有種似懂非懂的感覺，所以我們就來操作一下吧！這單元除了會用到上述 Docker 相關的知識外，也會需要一些部署的觀念，可能可以參考<a href="https://5xruby.tw/posts/rails-deploy/">這篇文章</a></p><h4>步驟 0: 簡單開一個 Rails 專案</h4><p>從終端機輸入指令建立專案吧！</p><pre>rails new docker_study</pre><p>接著新增 gem &#39;pg&#39; 以及更新對應的 config/database.yml</p><p>完成後再用 scaffold 產生基本框架</p><pre>rails generate scaffold post title:string body:text</pre><p>如果想要畫面好看一點點可以加上 bootstrap<br> 請參考： <a href="https://github.com/twbs/bootstrap-sass">https://github.com/twbs/bootstrap-sass</a></p><p>就先這樣，完成一個最簡單只有 CRUD 網站</p><h4>步驟 1: 開始加入 Docker</h4><blockquote>目標：<br> 在本機使用 docker-compose up 啟動多個 Container<br> 瀏覽器輸入 <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000</a> 可以開啟專案</blockquote><p>我們先試著在本機的環境使用 Dokcer，新增 Dockerfile 如下</p><pre>FROM ruby:2.5.1<br>MAINTAINER johnson &lt;johnson@5xruby.tw&gt;<br>RUN apt-get update &amp;&amp; apt-get install -y build-essential libpq-dev nodejs vim postgis imagemagick<br>RUN mkdir /app<br>WORKDIR /app<br>COPY Gemfile /app/Gemfile<br>COPY Gemfile.lock /app/Gemfile.lock<br>ENV RAILS_ENV production<br>RUN bundle install<br>COPY . /app<br>CMD rake db:migrate assets:precompile &amp;&amp; puma -C config/puma.rb</pre><p>這一個 Dockerfile 產生的 Image 就是我們 Rails App 的 Image，它是從一個有 Ruby 的 Linux 環境做出來的 FROM ruby:2.5.1，同時它安裝了許多環境中需要的套件 RUN apt-get ...，最後用 puma 啟動它。</p><p>看到這邊可能會有個疑問，為什麼在第 6、7、10 行都要 COPY，而不是直接在第六行寫一個 COPY . /app 就好了？因為這樣子的話我們的 Rails 專案每次有修改，都會重新跑一次 bundle install 。這是什麼意思！？ Dockerfile 在建立 Image 的時候是一層一層的包上去的，也就是 Dockerfile 中每一行設定都是會記錄下來的，如果這次專案沒有修改任何東西，當我們執行 docker build . 後，就不會重新產生 Image ，如果有做修改，就是從有修改的那個步驟再往下走，譬如第十行才修改，那就只會重新跑第十行後的設定。</p><p>目前操作的時候用 ruby 2.4.1 版會遇到問題，這篇文章先用 Ruby 2.5.1 版來操作，所以在Gemfile 要記得設定</p><pre>ruby &#39;2.5.1&#39;</pre><blockquote>如果用 ruby 2.4.1 會遇到什麼問題呢？在用 Docker 跑 ruby 2.4.1 的時候用 apt-get update 指令會遇到下面這問題</blockquote><pre>W: Failed to fetch http://deb.debian.org/debian/dists/jessie-updates/InRelease  Unable to find expected entry &#39;main/binary-amd64/Packages&#39; in Release file (Wrong sources.list entry or malformed file)</pre><blockquote>會有這問題是因為 /etc/apt/sources.list 檔案，也就是 APT 的套件來源清單沒更新，所以更新一下就能繼續用 ruby 2.4.1 囉，但在這範例我就直接用 ruby 2.5.1 給它操作下去！</blockquote><p>docker-compose.yml</p><pre>version: &#39;3&#39;<br><br>services:<br>  db:<br>    image: postgres:9.6<br>    environment:<br>      - &quot;POSTGRES_USER=postgres&quot;<br>      - &quot;POSTGRES_PASSWORD=postgres&quot;<br>    networks:<br>      - johnson<br>  app:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - DATABASE_URL=postgres://postgres:postgres@db/postgres<br>      - SECRET_KEY_BASE=8527f4cd4df56c3f41d8dc27251c09a55ed872eb299d230da758a05ee399b20ed655c33cf3039eccd59cf787cfb05ebe2b3e5a0b1811ad9d14163d0ee48f5f39<br>      - RAILS_SERVE_STATIC_FILES=true<br>    networks:<br>      - johnson<br>    depends_on:<br>      - db<br><br>networks:<br>  johnson:</pre><p>現在我們同時啟動兩個 Container ，一個是我們的 Rails App，另一個則是 Postgres 資料庫，其中資料庫的部分我們是直接使用現成的 Image 來建立，也就是image: postgres:9.6，而 Rails App 則是從當前目錄 (備註1) 的 Dockerfile 產生的 Image 來產生也就是build: .。</p><blockquote>備註1<br> 放 docker-compose.yml 的目錄</blockquote><p>在 Rails App 的 Container 啟動的最後階段會執行 rake db:migrate (Dockerfile CMD 設定的）也就是說必須先讓資料庫的 Container 啟動後，才能啟動 Rails App 的 Container ，因此可以在 docker-compose.yml 中看到以下的設定。</p><pre>app:<br>  depends_on:<br>     - db</pre><p>在專案中新增完這兩個檔案後，就執行吧</p><pre>docker-compose up</pre><p>沒意外的話到瀏覽器輸入 <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000</a> 應該能看到專案跑起來了！希望你可以看到類似這樣的畫面XD</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*1qO76OuJL-lNHRvp.png" /></figure><p>同時也可以用 docker ps 來看看這些跑起來的 Container</p><pre>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES<br>09f91d4b32aa        docker_app_app      &quot;/bin/sh -c &#39;rake db…&quot;   41 seconds ago      Up 11 seconds       0.0.0.0:3000-&gt;3000/tcp   docker_app_app_1<br>6297180618b4        postgres:9.6        &quot;docker-entrypoint.s…&quot;   42 seconds ago      Up 12 seconds       5432/tcp                 docker_app_db_1</pre><h4>步驟 2: Nginx 搭配 Puma</h4><blockquote>目標:<br> 在 docker-compose.yml 中加入 Nginx<br> 客製化 Nginx 的相關設定，讓 Nginx 能搭配 Puma 處理流量</blockquote><p>誒！？什麼是 Nginx 跟 Puma？為什麼需要這些東西？剛剛不是已經把專案跑起來了嗎？</p><p>其實一個完整的網站服務，除了有我們的 Rails App 之外，還會有專門處理 http request 的 reverse proxy server 像是 Nginx 或是 Apache ，還有在 reverse proxy server 跟 Rails App 中間的 App Server，例如 Puma 或 Passenger。</p><blockquote>如果想了解更多 Nginx 或是部署相關的說明，可以參考<a href="https://5xruby.tw/posts/rails-deploy/">這篇文章</a></blockquote><p>由於 Puma 是 Rails 內建的 App Server，所以他會和我們的 Rails App 一起啟動，Puma 的設定也在 config/puma.rb 調整即可，而 Nginx 的部分則是我們自己透過 Dockerfile 來客製化的。</p><p>為了要讓 Puma 可以搭配 Nginx，我們需要讓 Puma bind 在 Unix domain socket 上，而非一般常見的 TCP/IP network socket，修改 config/puma.rb 如下</p><pre># port        ENV.fetch(&quot;PORT&quot;) { 3000 }<br>bind &quot;unix:///app/tmp/sockets/puma.sock&quot;</pre><p>再來我們要用 Docker 的 Nginx 來作為我們的 reverse proxy server，在專案目錄中再開一個 Dockerfile，路徑可以是 docker/nginx/Dockerfile，這個 Dockerfile 就是官方的 Nginx 加上我們修改過的 default.conf 檔案，這檔案就是 Nginx 設定檔，我們要在裡面設定 Nginx 處理 request 的規則。新增 docker/nginx/Dockerfile 如下</p><pre>FROM nginx<br>COPY default.conf /etc/nginx/conf.d/default.conf</pre><p>我們要用下面這個設定方式，來執行我們的 Nginx，修改 docker/nginx/default.conf 如下</p><pre>server {<br>    listen       80;<br>    server_name  localhost;<br><br>     location / {<br>        proxy_pass http://unix:/app/tmp/sockets/puma.sock;<br>        proxy_set_header X-Forwarded-Host localhost;<br>    }<br>}</pre><p>上面的設定中，比較需要注意的是第六行的部分，要讓 Nginx 把接收到的 request 傳給 Puma</p><p>修改 docker-compose.yml 如下</p><pre>app:<br>  volumes:<br>      - /tmp/sockets:/app/tmp/sockets<br>nginx:<br>  build: docker/nginx/.<br>  ports:<br>    - &quot;80:80&quot;<br>  networks:<br>    - johnson<br>  volumes:<br>    - /tmp/sockets:/app/tmp/sockets<br>  depends_on:<br>    - app</pre><p>在 docker-compose.yml 也加上 Nginx，由於我們要讓 Nginx 跟 Web 這兩個 Container 可以共用 /app/tmp/sockets/puma.sock 這個檔案，所以我們用 volumes 來設定，讓 App 跟 Nginx 的 Container 的 /app/tmp/sockets 都會對應到本機的 /tmp/sockets。由於這次我們更新到 config/puma.rb 所以我們需要執行一次 docker-compose build 來讓 Dockerfile 重新檢查並產生新版本的 Image，更新完後再跑一次 docker-compose up</p><p>這一次 Nginx 可以搭配 Puma 一起運作！可以直接在瀏覽器輸入 127.0.0.1 來看我們的網站，由於 Nginx 是設定 port 80 ，因此這次不用在網址後面加上 :3000，然後再試著用 docker ps 看看我們啟動的 Container 吧！</p><pre>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES<br>c54bb26356b1        docker_app_nginx    &quot;nginx -g &#39;daemon of…&quot;   12 minutes ago      Up 13 seconds       0.0.0.0:80-&gt;80/tcp   docker_app_nginx_1<br>a65a5c532bb2        docker_app_app      &quot;/bin/sh -c &#39;rake db…&quot;   12 minutes ago      Up 13 seconds                            docker_app_app_1<br>6297180618b4        postgres:9.6        &quot;docker-entrypoint.s…&quot;   About an hour ago   Up 14 seconds       5432/tcp             docker_app_db_1</pre><h4>步驟 3: 部署到雲端上吧！</h4><blockquote>目標:<br> 將我們的 Docker 應用部署到 DigitalOcean 平台上<br> 並用申請好的 Domain Name 連線成功</blockquote><p>首先到 DigitalOcean 上申請一台機器吧！DigitalOcean 有提供已經裝好 Docker 的機器選擇，其實這就是一台裝好 Docker 的 Ubuntu 機器，我自己是選每月 10 美元的方案!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ue0vp5HYDN2fjs2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HqeyPfJjBm2enE1x.png" /></figure><p>DigitalOcean 的機器申請完後，可以在 Droplets 列表找到一組代表這台機器的 IP，有 IP 後就要來申請個 Domain Name，這樣才有部署網站的樣子嘛！可以網路上找個免費的服務來申請，像是 <a href="https://my.freenom.com/">freenom</a> 就是個不錯的選擇。這練習中我註冊的 Domain Name 是 dockerapp.ga</p><p>所以要記得把 docker/nginx/default.conf 修改如下</p><pre>server {<br>    listen       80;<br>    server_name  dockerapp.ga;<br><br>    location / {<br>        proxy_pass http://unix:/app/tmp/sockets/puma.sock;<br>        proxy_set_header X-Forwarded-Host localhost;<br>    }<br>}</pre><p>從這步驟起，我們要把所有的 Image 都放到 <a href="https://hub.docker.com/">Docker Hub</a> 上面，這樣就可以直接從 Docker Hub 把 Image pull 到機器上跑，這樣讓我們的環境更乾淨了一些。</p><p>首先把 docker-compose.yml 這兩個地方修改一下，這樣我們的 docker-compose up 用的 Image 就會是來自 Docker Hub ，而非當下目錄 build 出來的</p><pre>app:<br>    image: johnsonzhan121/docker_app:latest<br><br>  nginx:<br>    image: johnsonzhan121/docker_nginx:latest</pre><blockquote>johnsonzhan121 是我在 Docker Hub 上的帳號，我的 Image 都會放在這個帳號之下</blockquote><p>修改完後，可以執行 docker-compose up 看看會發生什麼事？</p><pre>Pulling app (johnsonzhan121/docker_app:latest)...<br>ERROR: manifest for johnsonzhan121/docker_app:latest not found</pre><p>在 Docker Hub 並沒有我的 Image，我現在需要把 Image 一個一個在本地 build 完，然後 psuh 到 Docker Hub 上面，也就是執行以下指令</p><pre>docker build . -t johnsonzhan121/docker_app<br>docker build docker/nginx/. -t johnsonzhan121/docker_nginx<br>docker push johnsonzhan121/docker_app<br>docker push johnsonzhan121/docker_nginx</pre><p>事情還沒完成，我們要在 DigitalOcean 平台上執行 docker-compose up，還需要把 Docker Hub 上的 Image pull 到 DigitalOcean 上等等，要做的事太多，直接寫成腳本自動執行吧！以後只要執行 ruby auto_deploy.rb 就能把部署的事情做完啦！自己新增一個 auto_deploy.rb 檔案吧</p><pre>#!/usr/bin/env ruby<br><br>p &#39;build docker_app and docker_nginx&#39;<br>`docker build . -t johnsonzhan121/docker_app`<br>`docker build docker/nginx/. -t johnsonzhan121/docker_nginx`<br><br>p &#39;push docker_app and docker_nginx&#39;<br>`docker push johnsonzhan121/docker_app`<br>`docker push johnsonzhan121/docker_nginx`<br><br>p &#39;update docker-compose.yml&#39;<br>`scp docker-compose.yml root@178.128.214.6:/home/docker`<br><br>p &#39;pull Image from Docker Hub&#39;<br>`ssh root@178.128.214.6  &#39;docker pull johnsonzhan121/docker_app&#39;`<br>`ssh root@178.128.214.6  &#39;docker pull johnsonzhan121/docker_nginx&#39;`<br><br>p &#39;remote docker-compose up&#39;<br>`ssh root@178.128.214.6  &#39;cd /home/docker &amp;&amp; docker-compose up&#39;`</pre><blockquote>178.128.214.6 是我 DigitalOcean 的 IP，你們的腳本要換上自己的 IP 喔，當然也可以用你申請到的 Domain Name</blockquote><p>在執行 ruby auto_deploy.rb 之前記得要到伺服器上新增對應的目錄喔，像是這個 /home/docker 正常執行後終端機會長這樣</p><pre>&quot;build docker_app and docker_nginx&quot;<br>&quot;push docker_app and docker_nginx&quot;<br>&quot;update docker-compose.yml&quot;<br>&quot;pull Image from Docker Hub&quot;<br>&quot;remote docker-compose up&quot;<br>Starting docker_db_1 ... done<br>Recreating docker_app_1 ... done<br>Recreating docker_nginx_1 ... done</pre><p>然後就能用剛剛申請的 Domain Name 來試試囉！也可以用 ssh 登入 DigitalOcean 然後輸入指令 docker images 或 docker ps 查看，我的網站已經可以用 http://dockerapp.ga/ 連線上囉！雖然目前只能做 get 的操作還不能用 post 的操作。</p><h4>步驟 4: HTTPS 認證</h4><blockquote>目標:<br> 透過 certbot 來申請 SSL 憑證<br> 可以用在瀏覽器輸入 <a href="https://dockerapp.ga/">https://dockerapp.ga</a> 然後連線成功</blockquote><p>一般正式的網站都會採用 HTTPS，來讓網站更安全更專業，我們要透過 Cerbot 自動化工具來申請免費的 Let’s Encrypt 的 SSL 憑證</p><p>在 docker-compose.yml 加入 certbot 以及調整 Nginx 如下</p><pre>nginx:<br>    image: johnsonzhan121/docker_nginx:latest<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - /tmp/sockets:/app/tmp/sockets<br>      - ./data/certbot/conf:/etc/letsencrypt<br>      - ./data/certbot/www:/var/www/certbot<br><br>  certbot:<br>    image: certbot/certbot<br>    volumes:<br>      - ./data/certbot/conf:/etc/letsencrypt<br>      - ./data/certbot/www:/var/www/certbot</pre><p>我們要讓 Nginx 跟 certbot 可以共用 /etc/letsencrypt 、/var/www/certbot 這兩個目錄，前者是放我們 SSL 認證的資料，後者是拿來申請 SSL 憑證用的。再來就是修改 Nginx 設定檔的部分，我們要用兩個 Sever 的 block 來控制不同 port 進來的 request，第一個 server block 是接收 80 port 的 request，接收到後把 request 轉到第二個 server block 也就是 443 port 的。這邊可以注意到我們新增了 proxy_set_header X-Forwarded-Ssl on;，有了它後我們就能對網站做 post request 囉，不然原本會遇到 Rails 的 ActionController::InvalidAuthenticityToken 問題</p><pre>server {<br>    listen       80;<br>    server_name  dockerapp.ga;<br>    return 301 https://dockerapp.ga$request_uri;<br>}<br><br>server {<br>    listen       443 ssl;<br>    server_name dockerapp.ga;<br><br>    ssl on;<br>    # 剛剛說的 SSL 認證資料<br>    ssl_certificate      /etc/letsencrypt/live/dockerapp.ga/fullchain.pem;<br>    ssl_certificate_key  /etc/letsencrypt/live/dockerapp.ga/privkey.pem;<br><br>    # 跟 Puma 搭配用<br>    location / {<br>        proxy_pass http://unix:/app/tmp/sockets/puma.sock;<br>        proxy_set_header X-Forwarded-Ssl on;<br>        proxy_set_header X-Forwarded-Host dockerapp.ga;<br>    }<br><br>    # 申請 SSL 憑證用的<br>    location ~ /.well-known {<br>        root /var/www/certbot;<br>    }<br>}</pre><p>完成囉！執行看看 ruby auto_deploy.rb 執行完後好像開始不能連上網站了XD，我們需要登入到機器裡面看看，登入機器後用 docker ps</p><pre>CONTAINER ID        IMAGE                              COMMAND                  CREATED              STATUS              PORTS               NAMES<br>8dac143fc834        johnsonzhan121/docker_app:latest   &quot;/bin/sh -c &#39;rake db…&quot;   About a minute ago   Up About a minute                       docker_app_1<br>2887c373e865        postgres:9.6                       &quot;docker-entrypoint.s…&quot;   18 minutes ago       Up 13 minutes       5432/tcp            docker_db_1</pre><p>看來 Nginx 沒有跑起來，所以到 /home/docker 跑跑看 docker-compose up ，跑完後大概看到這樣的東西</p><pre>docker_nginx_1 exited with code 1<br>certbot_1  | Saving debug log to /var/log/letsencrypt/letsencrypt.log<br>certbot_1  | Certbot doesn&#39;t know how to automatically configure the web server on this system. However, it can still get a certificate for you. Please run &quot;certbot certonly&quot; to do so. You&#39;ll need to manually configure your web server to use the resulting certificate.<br>docker_certbot_1 exited with code 1</pre><p>我們遇到一個問題，我們要用 Nginx 來申請 SSL 憑證，但是 Nginx 沒有申請 SSL 憑證的情況下無法啟動 Container，要處理這問題很麻煩，我們需要先做出一個假的憑證讓 Nginx 可以正常啟動，然後刪除掉這假憑證，接著正式申請 Let’s Encrypt 的 SSL 憑證。看到這真是麻煩到讓人想放棄，好險有人已經針對這塊寫好了腳本讓大家一鍵完成以上工作，請參考<a href="https://medium.com/@pentacent/nginx-and-lets-encrypt-with-docker-in-less-than-5-minutes-b4b8a60d3a71">這篇文章的教學</a> 看完教學後，我們需要做的事情就是下載腳本，修改權限</p><pre>curl -L https://raw.githubusercontent.com/wmnnd/nginx-certbot/master/init-letsencrypt.sh &gt; init-letsencrypt.sh<br><br>chmod +x init-letsencrypt.sh</pre><p>然後修改檔案裡面的 domains 等參數，然後再執行 sudo ./init-letsencrypt.sh 即可完成，試試看用 HTTPS 來拜訪網站吧！</p><h4>步驟 5: Docker image 瘦身</h4><blockquote>目標:<br> 用 alpine 的 Ruby Image 來幫我們的 web image 瘦身<br> 從原本的 1.72GB 簡化到 503MB</blockquote><p>Docker Image 的大小是衡量我們容器技術的重要指標，小的 Docker Image 可以讓部署更有效率而且也更安全！用 docker iamges 來看看我們的 web Image 到底多大吧，居然有 1.72GB，我們有很大的空間來幫它瘦身。</p><pre>REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE<br>johnsonzhan121/docker_app     latest              fab76a5630cb        45 minutes ago      1.72GB<br>ruby                          2.5.1               3c8181e703d2        5 months ago        869MB</pre><p>要幫 Image 瘦身有很多方法，包含使用小的 Base Image 、用 Multi-Stage 的方式寫 Dockerfile、移除不用進入 Image 的檔案等等，在這次實作我們將要用縮小 Base Image 來瘦身，因為在 1.72 GB 的 Image 中 Base Image 就佔了 896MB 呀！</p><p>其實 Ruby 有更小 Image 可以使用，那就是 Alpine 版本的 Ruby Image 啦！什麼是 Alpine？ Alpine 是一個輕型的 Linux 發行版本，目前大部分 Docker 官方映像檔都已經有支援 Alpine 作為基礎的映像檔，當然 Ruby 也不例外，下面是 Alpine 版本的 Ruby 比原版小的多，只有 45.4MB</p><pre>REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE<br>ruby                          2.5.1-alpine        d29267791323        6 months ago        45.3MB</pre><p>來改寫我們的 Dockerfile 吧！</p><p>把原本的</p><pre>FROM ruby:2.5.1<br>RUN apt-get update &amp;&amp; apt-get install -y build-essential libpq-dev nodejs vim postgis imagemagick</pre><p>改成</p><pre>FROM ruby:2.5.1-alpine<br>RUN apk update &amp;&amp; apk upgrade &amp;&amp; apk add --update --no-cache build-base nodejs imagemagick postgresql-dev</pre><p>第一行好理解，就是改用 Alpine 版本的 Ruby。第二行不是用 Ubuntu 常見的 apt-get，而是 apk add， apk 就是 Alpine 的套件管理工具，那我要怎麼知道每個原本用 apt-get 套件在 apk 有沒有支援呢？只能試試看了？或是到 apk 提供的<a href="https://pkgs.alpinelinux.org/packages">文件</a>去看囉。完成後再部署一次吧，執行 ruby auto_deploy.rb</p><p>執行後會看到類似這樣的錯誤訊息</p><pre>web_1      | rake aborted!<br>web_1      | TZInfo::DataSourceNotFound: tzinfo-data is not present. Please add gem &#39;tzinfo-data&#39; to your Gemfile and run bundle install</pre><p>看起來是少裝了 tzinfo-data，這個 gem 到底是什麼呢？稍微看一下我們這個預設的 Gemfile 裡面其實有寫到</p><pre># Windows does not include zoneinfo files, so bundle the tzinfo-data gem<br>gem &#39;tzinfo-data&#39;, platforms: [:mingw, :mswin, :x64_mingw, :jruby]</pre><p>看上面的意思就是說，如果在某些環境執行 Rails 就會需要裝這個 gem，剛好我們從原來的 ruby:2.5.1 Debian 系統，換成現在 ruby:2.5.1-alpine 就遇到了這問題，沒意外的話，只要加上這個 gem 就真的能順利運作了吧！？於是我們加上這個 gem 重跑一次試試看！沒錯成功啦 &gt;&lt;</p><p>再一次用 docker iamges 指令來確認，我們成功瘦身了多少？<br> 我們從原本的 1.72GB 瘦身成 503MB 啦！還有一些進步空間，那就之後再說吧～</p><pre>REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE<br>johnsonzhan121/docker_app     latest              6a7f0235885f        About a minute ago   503MB</pre><h4>結論</h4><p>終於成功用 Docker 部署一個 Rails 應用到 DigitalOcean 平台上了，雖然很陽春但還是很開心可以完成。<a href="https://github.com/shes50103/docker_app">範例程式碼</a>都放到 GitHub 上了，需要就拿去吧，每個步驟都有用 git commit 分出來。目前手邊的專案還沒有使用到 Docker 來部署，但在未來還是會想再撥一些時間研究 Docker，目前為止感覺它是相對有趣的技術，希望未來可以對 Docker 越來越熟悉，甚至在工作中使用到。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe9ff162fee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby 探索：Blocks 深入淺出]]></title>
            <link>https://medium.com/@johnsonzhan/ruby-%E6%8E%A2%E7%B4%A2-blocks-%E6%B7%B1%E5%85%A5%E6%B7%BA%E5%87%BA-86defcfe4225?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/86defcfe4225</guid>
            <category><![CDATA[block]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 15:54:36 GMT</pubDate>
            <atom:updated>2020-03-04T15:54:36.456Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpwORDIg_WGmzvOn_hY7ng.jpeg" /></figure><p>在學習 Ruby 的過程中，Block 是其中很重要的一環，如果對 Block 有多一點的認識就能更了解一些深奧的 code 到底是什麼意思啦！這篇文章主要是在看完 Metaprogramming Ruby 2 中的 Block 章節後的讀書心得，以及一個我自己找的一個小題目來練習學到的觀念。</p><h4>目錄</h4><ul><li>Scope 介紹</li><li>什麼是 Scope ?</li><li>Scope Gate</li><li>Block 介紹</li><li>Block 從頭開始</li><li>Proc 基本介紹</li><li>procs 和 lambdas 怎麼分？！</li><li>&amp; 符號解析</li><li>Block 實作</li><li>自己做一個 before action</li><li>第一步：試試看在 before 中執行 block</li><li>第二步：在執行 before 的時候只有紀錄…</li><li>第三步：重新定義要執行 before 的 method</li><li>第四部：只有第一次執行 execute_before</li><li>結論</li></ul><h4>Scope 介紹</h4><h4>什麼是 Scope ?</h4><p>在介紹 Block 之前，我們需要先認識 ruby 中的 scope。<br> 誒！什麼是 scope 呢？大概就是哪個變數可以在哪邊被看到的規則，舉例來說</p><pre>x = 10<br>def method<br>  puts x<br>end<br><br>method</pre><p>執行上面這段程式後會發生…</p><pre>test.rb:3:in &#39;method&#39;: undefined local variable or method &#39;x&#39; for main:Object (NameError)<br>    from test.rb:6:in &#39;&lt;main&gt;&#39;</pre><p>在 method 方法內和外是不同的兩個 scope，所以 method 方法不能看到它外面的變數 x。如果想知道在自己的 scope 中可以使用哪些變數可以用 local_variables 來看！以下面這段 code 為例：</p><pre>v1 = 1<br>class MyClass<br>  v2 = 2<br>  local_variables #[:v2]<br>  def my_method<br>    v3 = 3<br>    local_variables #[:v3]<br>  end<br>  local_variables # [:v2]<br>end<br>local_variables # [:v1, :obj]<br>obj = MyClass.new<br>obj.my_method</pre><blockquote>local_variables 會回傳現在的 scope 中可以看到的區域變數</blockquote><p>在上面的例子我們可以發現，定義 class MyClass 到 end 中間這段區域看不到變數 v1 ，同時 def my_method 到它的 end 這段也看不到變數 v2，這是因為他們在不同的 scope。</p><h4>Scope Gates</h4><p>在 Ruby 中有三個 Scope Gates：Class definitions, Module definitions 還有 Methods 他們就像一道牆，牆外牆內彼此看不見那裡有哪些變數。</p><p>當然也是有一些方法可以突破這樣子的限制，可以換個方式定義 Class 還有 Methods 讓他們不再是 Scope Gates，這方法叫做 Flattening the Scope (其實方法的名字好像也不是很重要)，反正就是突破那個 scope 的限制啦！</p><pre>my_var = &quot;Success&quot;<br>MyClass = Class.new do<br>  puts &quot;#{my_var} in the class definition&quot;<br>  define_method :my_method do<br>    puts &quot;#{my_var} in the method&quot;<br>  end<br>end<br><br>MyClass.new.my_method</pre><p>可以成功印出</p><pre>Success in the class definition<br>Success in the method</pre><h4>Block 介紹</h4><h4>Block 從頭開始</h4><p>除了上述方法可以突破 scope 的限制外，其實 block 也是可以做到類似的效果的，它讓我們可以先寫一段程式，然後再方法裡面呼叫，就像這樣</p><pre>def my_method<br>  x = &quot;Goodbye&quot;<br>  yield(&quot;cruel&quot;)<br>end<br><br>x = &quot;Hello&quot;<br><br>my_method do |y|<br>  puts &quot;#{x}, #{y} world&quot;<br>end</pre><p>會印出</p><pre>Hello, cruel world</pre><p>上面的例子，在呼叫 my_method 的時候我們傳了一個 block (do 到 end 的那段)，大概可以想像他是 my_method 這方法的一個參數，接著 my_method 可以用 yield 這方法來執行這個 block。這個 block 厲害的地方在於它可以帶著當下的 bindings(註解1) 到 method 裡面去執行，所以在 my_method 可以看到 x 變數內的值是 Hello。</p><blockquote>註解1</blockquote><blockquote>bindings 指的是當下 scope 可以使用的 variable, methos 還有 self</blockquote><p>在 Ruby 的世界裡 block 是個特殊的成員，他不是物件也不能單獨存在，但其實還是有方法可以把 block 轉成物件讓我們處理的，那就是 Proc。</p><h4>Proc 基本介紹</h4><pre>inc = Proc.new {|x| x + 1 }<br>inc.call(2) # 回傳 3</pre><p>在 Proc.new 後面接一個 block 就可以產生一個 Proc 的物件，接著可以使用 call 方法來呼叫。有很多種方式可以產生 Proc 的物件，而且用不同方式產生的 Proc 也會不太一樣，首先來介紹 proc 還有 lambda ～</p><h4>procs 和 lambdas 怎麼分？！</h4><pre>l1 = lambda {|x| x + 1 }<br>l2 = -&gt;(x){ x + 1 }<br>p1 = Proc.new {|x| x + 1 }<br>p2 = proc {|x| x + 1 }<br><br>puts &quot;l1: #{l1.lambda?}, #{l1.class}&quot; # l1: true, Proc<br>puts &quot;l2: #{l2.lambda?}, #{l2.class}&quot; # l2: true, Proc<br>puts &quot;p1: #{p1.lambda?}, #{p1.class}&quot; # p1: false, Proc<br>puts &quot;p2: #{p2.lambda?}, #{p2.class}&quot; # p2: false, Proc</pre><p>上面的 l1, l2, p1, p2 都可以使用 call 方法來執行，其中我們可以用 lambda? 來知道它是不是 lambda 如果不是那它就是 proc 啦！除了用 lambda 跟 -&gt;() 產生的 Proc 物件是 lambda 其他都是 proc 唷！</p><p>說了那麼久怎麼產生跟判斷 proc 和 lambda，當然就要來說他們有什麼不同啦！主要有兩個不同的地方，第一個是 return 的值，第二個是參數的判斷方式</p><p>procs 和 lambdas 有不同的 return</p><pre>def double(callable_object)<br>  callable_object.call * 2<br>end<br><br># return from lambdas<br>la = lambda { return 10 }<br><br># return from the scope which defined the procs(main)<br>pr = proc { return 10 }<br><br>puts double(la) # 20<br>puts double(pr) # LocalJumpError...</pre><p>執行程式後會</p><pre>20<br> test.rb:12:in `block in &lt;main&gt;&#39;: unexpected return (LocalJumpError)<br>    from p92.rb:22:in `double&#39;<br>    from p92.rb:29:in `&lt;main&gt;&#39;</pre><p>lambda 的 return 是從 lambda return，而 proc 則是從定義 proc 的 scope return 意思就是如果把 proc 用一個方法包起來的話…</p><pre>def lambda_double<br>  la = lambda { return 10 }<br>  result = la.call<br>  return result * 2<br>end<br><br>def proc_double<br>  pr = Proc.new { return 10 }<br>  result = pr.call<br>  return result * 2  # unreachable code!<br>end<br><br>puts lambda_double # =&gt; 20<br>puts proc_double   # =&gt; 10</pre><p>lambda_double 可以執行完方法中的每行程式，而 proc_double 則會在 pr.call 那行就 return 了，因為 proc 的 return 是從定義 proc 的地方也就是 proc_double 出發的。</p><p>procs 和 lambdas 處理參數的方式</p><p>procs 處理參數的方式比較有彈性，而 lambdas 則是比較嚴格，說起來不清楚!? 看 code 最快</p><pre>puts &quot;以下是 proc&quot;<br>pr = proc {|a,b| [a,b]}<br>p pr.call(&#39;a&#39;, &#39;b&#39;)<br>p pr.call(&#39;a&#39;)<br>p pr.call(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;)<br><br>puts &quot;以下是 lambda&quot;<br>la = lambda {|a,b| [a,b]}<br>p la.call(&#39;a&#39;, &#39;b&#39;)<br>p la.call(&#39;a&#39;)<br>p la.call(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;)</pre><p>執行程式後會</p><pre>以下是 proc<br>[&quot;a&quot;, &quot;b&quot;]<br>[&quot;a&quot;, nil]<br>[&quot;a&quot;, &quot;b&quot;]<br>以下是 lambda<br>[&quot;a&quot;, &quot;b&quot;]<br>test.rb:8:in `block in &lt;main&gt;&#39;: wrong number of arguments (given 1, expected 2) (ArgumentError)<br>    from test.rb:10:in `&lt;main&gt;&#39;</pre><p>procs 遇到多的參數會自動丟掉，而不夠就補 nil，lambdas 則要求參數的數量正確才能執行。</p><h4>&amp; 符號解析</h4><blockquote>促使我想要多瞭解 ruby 中的 block 就是這個 &amp; 符號了，第一次在 rails 專案裡面看到了這種符號真是既挫折又期待，覺得有很多東西可以學啦！在 C 語言中 &amp; 是來拿記憶體位址的符號，在 ruby 裡面 &amp; 符號到底是拿來做什麼的呢？</blockquote><p>&amp; 符號可以把 block 轉成 Proc 或是轉回來，多說無益看 code 就知道</p><pre>def second_method<br>  puts &#39;In second_method&#39;<br>  yield<br>end<br><br>def first_method(&amp;operator) # 這裡的 &amp; 是把 block 轉成 Proc<br>  puts &#39;In first_method&#39;<br>  operator.call<br>  second_method(&amp;operator) # 這裡的 &amp; 是把 Proc 轉成 block<br>end<br><br>first_method do<br>  puts &quot;this is block&quot;<br>end</pre><p>執行後會印出</p><pre>In first_method<br>this is block<br>In second_method<br>this is block</pre><p>在呼叫 first_method 得時候我們傳了一個 block 給他，我們可以把 block 想像成是最後一個參數，只是要在定義 first_method 的時候跟他說我們會有一個參數而且他是一個 block，因此就寫 &amp;operator，之後就能在 first_method 中使用 operator 這個 Proc 啦～</p><p>如果想要不是馬上要用這個 Proc 還能把他先轉成 block 再傳給下一個 method，這時候就是在 operator 前加個 &amp; 它就又從 Proc 轉成 block 囉！所以 second_method 使用 yield 才能成功呀！</p><p>以上就是關於 Block 的基本介紹啦，接下來做個小小的練習來應用一下學到的知識啦！</p><h4>Block 實作:</h4><h4>自己做一個 before action</h4><p>目標是讓下面的程式碼</p><pre>class Example<br>  extend BeforeAction<br>  before :method_a, :method_b do<br>    puts &#39;the code before method&#39;<br>  end<br><br>  def method_a<br>    puts &#39;this is method a&#39;<br>  end<br><br>  def method_b<br>    puts &#39;this is method b&#39;<br>  end<br>end<br><br>instance_1 = Example.new<br>instance_1.method_a<br>instance_2 = Example.new<br>instance_2.method_b</pre><p>可以有這樣的執行結果</p><pre>the code before method<br>this is method a<br>the code before method<br>this is method b</pre><blockquote>要做一個 BeforeAction 的 Module ，在裡面有個 before 方法可以讓指定的 method 在執行之前，先執行 before 後面的 block</blockquote><h4>第一步：試試看在 before 中執行 block</h4><pre>module BeforeAction<br>  def before(*methods, &amp;block)<br>    methods.each do |method|<br>      block.call<br>    end<br>  end<br>end</pre><blockquote>現在我們可以依據定義了幾個 method 給 before 來執行幾次 block</blockquote><h4>第二步：在執行 before 的時候只有紀錄…</h4><p>要做到 before action 就必須覆寫裡面的 method_a, method_b 之類的，但是在執行 before 的時候根本還沒有定義 method_a 是什麼，所以在這邊只能先把要執行的 block 還有要覆寫的 method 名字存起來！</p><pre>module BeforeAction<br>  def new<br>    execute_before<br>    super<br>  end<br><br>  def before(*methods, &amp;block)<br>    # 先存起來之後用<br>    @methods = methods<br>    @block = block<br>  end<br><br>  def execute_before<br>    # to do ...<br>  end<br>end</pre><blockquote>存起來之後我們可以在 Example 用了 new 方法時，再來處理我們的 block，讓那些需要執行 before action 的 method 可以被覆寫</blockquote><h4>第三步：重新定義要執行 before 的 method</h4><pre>module BeforeAction<br>  ...<br>  def execute_before<br>    @methods.each do |method|<br>      # 幫原本的 method 取一個新名字<br>      newname = &quot;new_#{method}&quot;<br>      alias_method newname, method<br>      block = @block<br>      # 重新定義每個 method 要做什麼<br>      define_method method do<br>        # 執行 block<br>        block.call<br>        # 原本的 method<br>        send(newname)<br>      end<br>    end<br>  end<br>end</pre><blockquote>這個步驟比較麻煩一點，重新定義方法後就會把原本的方法全部蓋過去。所以我們幫原本的方法取了個新名字(newname)，在重新定義方法後就可以在呼叫(send)來執行原本方法的程式了！</blockquote><p>到目前為止，我們的程式已經可以讓 Example 這個 class 做這樣的事囉！如果只有 new 一次都能正常執行～</p><pre>instance_1 = Example.new<br>instance_1.method_a<br>instance_1.method_b</pre><p>執行結果為</p><pre>the code before method<br>this is method a<br>the code before method<br>this is method b</pre><h4>第四部：只有第一次執行 execute_before</h4><p>因為只有在第一次 new 的時候需要執行 execute_before，所以我們可以做一點小小的修改…</p><pre>module BeforeAction<br>  def new<br>    execute_before if first_time?<br>    super<br>  end<br><br>  def first_time?<br>    return false if @not_first_time<br>    @not_first_time = true<br>  end<br><br>  ...<br>end</pre><h4>最後：大功告成</h4><p>完整程式碼如下</p><pre>module BeforeAction<br>  def new<br>    # 只有第一次執行 new 時要 execute_before<br>    execute_before if first_time?<br>    super<br>  end<br><br>  def first_time?<br>    return false if @not_first_time<br>    @not_first_time = true<br>  end<br><br>  def before(*methods, &amp;block)<br>    # 先存起來之後用<br>    @methods = methods<br>    @block = block<br>  end<br><br>  def execute_before<br>    @methods.each do |method|<br>      # 幫原本的 method 取一個新名字<br>      newname = &quot;new_#{method}&quot;<br>      alias_method newname, method<br>      block = @block<br>      # 重新定義每個 method 要做什麼<br>      define_method method do<br>        # 執行 block<br>        block.call<br>        # 原本的 method<br>        send(newname)<br>      end<br>    end<br>  end<br>end<br><br>class Example<br>  extend BeforeAction<br>  before :method_a, :method_b do<br>    puts &#39;the code before method&#39;<br>  end<br><br>  def method_a<br>    puts &#39;this is method a&#39;<br>  end<br><br>  def method_b<br>    puts &#39;this is method b&#39;<br>  end<br>end<br><br>instance_1 = Example.new<br>instance_1.method_a<br>instance_2 = Example.new<br>instance_2.method_b</pre><p>執行後結果</p><pre>the code before method<br>this is method a<br>the code before method<br>this is method b</pre><p>在這範例練習到把 block 轉成 Proc ，然後存起來之後使用，在每次呼叫方法的時候都先執行這個 Proc</p><h4>結論</h4><p>透過寫這篇文章好好的整理了 block 相關的觀念，不然以前總是略懂略懂，但要回想的時候又要翻書查看半天…雖然這些東西可能不是馬上需要用到，但以後如果有需要用到這些技巧的時候，再回來看這篇自己寫的文章應該可以很快回憶起來吧！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86defcfe4225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 部署工具，原來是這樣]]></title>
            <link>https://medium.com/@johnsonzhan/rails-%E9%83%A8%E7%BD%B2%E5%B7%A5%E5%85%B7-%E5%8E%9F%E4%BE%86%E6%98%AF%E9%80%99%E6%A8%A3-f0f3f5d69077?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f3f5d69077</guid>
            <category><![CDATA[passengers]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 15:50:20 GMT</pubDate>
            <atom:updated>2020-03-04T15:50:20.671Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6ddPWRflkRyQrrvjVQEuw.jpeg" /></figure><h4>部署 Rails 你可能會需要用到…</h4><p>在學習 Rails 部署的路上，你一定聽過 Nginx、 Passenger、 Capistrano 這幾個東西吧？這篇文章會依序介紹這幾個工具特色，以及常見功能！</p><blockquote>學習 Rails 部署建議可以參考蒼時的 <a href="https://blog.frost.tw/tags/DevOps/">系列教學文章</a><br> 它會詳細帶著讀者一步一步在 DigitalOcean 的機器上部署 Rails 專案</blockquote><p>部署大概像什麼樣子？大概像下面這張圖吧</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f4-jvt5gek-_KZpI.png" /></figure><p>遠端伺服器可能是 GCP、AWS、DigitalOcean 這些機器，程式碼倉庫則是 GitHub、 Gitlab、Bitbucket 這些服務，部署過程就是讓遠端伺服器可以取得程式碼倉庫的程式碼，然後順利的把專案執行起來。其中我們會需要在遠端伺服器安裝 Passenger、Nginx 這兩個軟體，同時得用 Capistrano 讓部署自動化、更有效率！</p><h4>目錄</h4><ul><li>Nginx &amp; Passenger</li><li>為什麼是 Nginx 搭配 Passenger ?</li><li>Passenger 擅長什麼呢？</li><li>Passenger 常用指令：</li><li>Nginx 設定檔說明</li><li>自己設定 Nginx</li><li>Capistrano</li><li>Capistrano 功能介紹</li><li>部署架構</li><li>設定檔</li><li>常用指令</li><li>結論</li></ul><h4>Nginx &amp; Passenger</h4><p>Nginx 是一個 Web Server，它的功能是接受 http request 並回覆 http response ， Nginx 本身和 Ruby 沒有關係，通常使用 Nginx 時我們還會搭配 Passenger 這一個 App Server，它可以管理 Rails 的 process 數量，同時 App Server 符合 Rack 的規範所以可以跟符合 Rack 規範的 Web Application (例如 Rails 溝通)</p><blockquote>在接下來的文章中，會使用三個名詞</blockquote><blockquote>Web Server 就是 Nginx</blockquote><blockquote>App Server 就是 Passenger</blockquote><blockquote>Web Application 就是 Rails App</blockquote><blockquote>關於 Passenger 和 Nginx 的安裝可以參考 <a href="https://blog.frost.tw/posts/2018/04/10/Getting-started-deploy-your-Ruby-on-Rails-Part-4/#more">這篇文章</a></blockquote><h4>為什麼是 Nginx 搭配 Passenger ?</h4><p>這是我一開始學習部署時一直弄不懂的地方，我原本的想像是伺服器上面除了有我的 Web Application 外，再來就是某個軟體來處理其他的事情。到底為什麼需要 Nginx 和 Passenger 兩樣工具的搭配才能完成這些工作呢？</p><p>Nginx 和 Apache 都是 Web Server，它們專攻處理靜態檔案還有 http request。一般來說 Web Server 會放在 App Server 還有 Web Application 之前，它可以直接接觸 Client 端送來的請求，但在它後面的 App Server 和 Web Application 卻不行，因為這樣的架構讓這些軟體可以更有效率的分工，也讓我們的伺服器更安全。</p><p>此外，Web Server 還能處理效能上的議題，譬如 slow client 問題，如果 Client 端處理 http request 的速度超慢，Server 這邊就可能得花許多時間在等待這個 Client ，這樣的等待是很浪費資源的，為了解決這類型效能問題，又不讓其他開發者浪費時間重複造輪子，最好的方式就是讓 Web Server 處理這些問題，讓 App Server 和 Web Application 處理他們擅長的，這就是為什麼我們會用到 Nginx 和 Passenger 這兩樣工具了！</p><h4>Passenger 擅長什麼呢？</h4><p>Passenger 會根據流量來判斷現在應該開啟多少個 Web Application，同時它也像是 Web Application 還有 Web Server之間的橋樑，它可以用 Rack 跟 Web Application 溝通，也能處理 Web Server 傳來的 http request，另外 Passenger 在架構上相當彈性也穩定，下圖是 Passenger 的架構圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*qKNkpkdIHmYvJWSj.png" /></figure><p>圖片來源：www.phusionpassenger.com</p><p>Passenger 是由多個模組所組成的，包含在編譯 Nginx 時一起編譯的 Phusion Passenger module，以及負責管理、重啟其它模組的 Watchdog 等等，因為這樣的結構可以讓 Passenger 更加有彈性，只要 Watchdog 沒有壞掉它就能幫忙重啟其他模組。</p><p>由於這些模組都是由許多的 process 在運行，因此彼此之間的溝通，需要透過一個 instance directory 的目錄，來存放這些 process 之間彼此溝通需要的檔案，所以在 nginx.conf 裡面我們會設定 passenger_instance_registry_dir 告訴 Passenger 它的 instance directory 在哪裡，我們在使用 passenger-status 指令的時候也是透過這資料夾內的資料取得資訊的。</p><blockquote>之前在用 Passenger 的時候常常會跑不起來卻不知道為什麼？<br> 原來就是少了 instance directory 這個目錄！</blockquote><p>關於這架構圖更詳細介紹可看<a href="https://www.phusionpassenger.com/documentation/Design%20and%20Architecture.html#_web_server_module">官方文件</a></p><h4>Passenger 常用指令：</h4><p>要使用 passenger 的指令必須先將 passenger 的 bin 目錄放到路徑之下，我們可以看到 passenger 的 bin 目錄下有這些執行檔</p><pre>passenger  passenger-config  passenger-install-apache2-module  passenger-install-nginx-module  passenger-memory-stats  passenger-status</pre><blockquote>這些執行檔也就是我們可以使用的指令唷！</blockquote><p>其中我們常用的可能有這兩個</p><pre># 查詢 passenger 的狀態<br>passenger-status<br><br># 透過 passenger 重新啟動 Rails<br>passenger-config restart-app</pre><p>咦！那要在哪邊做 Passenger 的相關設定呢？還記得前面說到的跟 Nginx 一起編譯的 Phusion Passenger module 模組嗎？因為這樣的關係，我們在寫 Nginx 設定檔時也可以一起設定一些 Passenger 需要的東西，接下來可以來看看 Nginx 的設定檔</p><h4>Nginx 設定檔說明</h4><p>Nginx 安裝好後會有 nginx.conf 這設定檔，我們可以直接在裡面做修改，或是用 include site-enabled/*.conf; 之類的方法把設定檔寫在其他地方，在這個範例我們會將設定檔寫在其他地方，所以在 nginx.conf 加上一行 include site-enabled/*.conf; 即可，同時也得在有 nginx.conf 檔案的目錄下新增 site-enabled 資料夾來放我們要的設定檔。</p><p>如果把 nginx.conf 的註解都拿掉的話，你的設定檔可能長這樣</p><pre># 註解0<br>worker_processes  1;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>    passenger_root /usr/local/passenger/passenger-5.3.3;<br>    passenger_ruby /usr/local/ruby-2.4.3/bin/ruby;<br>    include       mime.types;<br>    default_type  application/octet-stream;<br>    sendfile        on;<br>    keepalive_timeout  65;<br><br>    server {<br>        listen       80;<br>        server_name  localhost;<br>        location / {<br>            root   html;<br>            index  index.html index.htm;<br>        }<br>        error_page   500 502 503 504  /50x.html;<br>        location = /50x.html {<br>            root   html;<br>        }<br>    }<br><br>    # 這行是後來加上去的<br>    include site-enabled/*.conf;<br>}</pre><p>在 nginx.conf 中可以看到 http { ... } 包起來的設定，在這裡面還會看到 server {...} 的結構，而我們的include site-enabled/*.conf; 會寫在 http 這個 block 內然後 server 這個 block 外，因為其實我們要寫的設定檔就是好幾個 server {...} ，這些層級之間的規定可以在 <a href="http://nginx.org/en/docs/beginners_guide.html">Nginx 的文件</a>中找到~</p><blockquote>註解0</blockquote><blockquote>設定 Nginx 的 worker_processes 數量，Nginx 啟動方式是一個 master process 和多個 worker processes，master process 負責根據設定檔的設定來操作 worker processes，所以 worker processes 是真正在處理 http request 的 process！</blockquote><h4>自己設定 Nginx</h4><p>在看完 nginx.config 後我們使用以下指令來建立我們自己的設定檔</p><pre>$ mkdir site-enabled<br>$ cd site-enabled<br>$ vim xxx.conf (xxx可換為你的設定檔名稱，通常會用網域名稱好區分)</pre><p>完成後可以在 xxx.conf 中這樣寫，其中 # 為註解符號</p><pre>#設定 Passenger 的 instance directory<br>passenger_instance_registry_dir /var/run/passenger-instreg;<br><br>#第一個 server 區塊<br>server {<br><br>    #監聽 port 80 （ http request ）<br>    listen 80;<br><br>    #註解1，設定 server name<br>    server_name dodeploy.tk;<br><br>    #註解2，將 http request 都轉給第二個 server 區塊<br>    return 301 https://dodeploy.tk$request_uri;<br>}<br><br>#第二個 server 區塊<br>server {<br><br>    #監聽 port 443 （ https request ）<br>    listen       443 ssl;<br><br>    server_name dodeploy.tk;<br><br>    #SSL 憑證相關設定<br>    ssl on;<br>    ssl_certificate      /etc/letsencrypt/live/dodeploy.tk/fullchain.pem;<br>    ssl_certificate_key  /etc/letsencrypt/live/dodeploy.tk/privkey.pem;<br><br>    #註解3<br>    location ~ /.well-known {<br>        allow all;<br>        root /opt/nginx/html;<br>    }<br><br>    #提供靜態檔案的放置目錄<br>    root /home/deploy/do_deploy.com/current/public;<br><br>    #啟動 Passenger<br>    passenger_enabled on;<br>}</pre><blockquote>註解1</blockquote><blockquote>如果有需要，我們也可以讓多個 domain 都對應到這台機器，首先申請多個 domain name 都對應到我們機器的 IP，然後我們就可以用多個 server 的區塊分別接收到帶有不同網域名稱的 http 請求。</blockquote><blockquote>註解2</blockquote><blockquote>我們的範例會將 HTTP 轉換成 HTTPS ，要完成這功能要設定多個 server 的區塊，第一個區塊監聽 port 80，也就是只接受 HTTP 請求，在接收到 HTTP 請求後再來就是 return 將請求交由監聽 https 的第二個區塊來處理。</blockquote><blockquote>註解3</blockquote><blockquote>在第二個區塊我們做了 SSL 的憑證的設定，另外 location 那一塊是為了讓遇到 ~/.well-known 開頭的頁面，都使用 /opt/nginx/html 這個目錄，如此一來就能夠讓 Certbot 把驗證用的檔案放在這裡面，讓 Let’s Encrypt 可以驗證到。</blockquote><p>完成以上設定後，可以用以下指令檢查設定檔有沒有問題</p><pre>sudo /opt/nginx/sbin/nginx -t</pre><p>如果沒問題可以用以下指令重新啟動 Nginx ( 使用這指令需要設定 systemd 功能 )</p><pre>sudo systemctl restart nginx</pre><h4>Capistrano</h4><h4>Capistrano 功能介紹</h4><p>Capistrano 是自動化部屬的工具，如果少了 Capistrano 我們要部署遠端伺服器就得每個動作都自己來，如果有多台機器多個環境，就更會需要 Capistrano 來幫忙處理各種繁瑣的任務了！</p><p>Capistrano 支援 Multiple stages，stage 指的是環境( staging, production 之類的)，我們只需要定義一次部署的方式，就能將這樣的部署方式套用在多個環境，也就是將 Web Application 部署到不同環境卻不用重複寫相同的設定檔，只需要設定這些環境所不同的地方譬如 IP 位置就可以了！</p><p>Capistrano 也支援 Server roles，在一個環境下我們可能會定義多個 role，因為 Web Application 可能是由多個服務一起完成的，有跑 Web Application 、database 和 CronJob server 等等，每個 role 在部署時會有不同的流程，這些也可以透過定義什麼 role 需要執行甚麼來完成。</p><h4>部署架構</h4><p>Capistrano 部署到機器後結構大概會如下</p><pre>├── current -&gt; /home/deploy/do_deploy.com/releases/20150120114500/<br>├── releases<br>│   ├── 20150080072500<br>│   ├── 20150090083000<br>│   ├── 20150100093500<br>│   ├── 20150110104000<br>│   └── 20150120114500<br>├── repo<br>│   └── &lt;VCS related data&gt;<br>├── revisions.log<br>└── shared<br>    └── &lt;linked_files and linked_dirs&gt;</pre><p>Capistrano 在每次部署時都會產生一個新的資料夾在 releases 目錄下，新的資料夾裡面就是新版本的 code 而資料夾名稱也是用當時時間命名。所以 releases 目錄下就會有每次部署時程式碼。current 資料夾是目前最新版本的程式碼資料夾，他的來源其實就是用 symlink 指到 releases 資料夾中最新版本的程式資料夾！</p><p>在我們的專案中有一些資料我們可能希望他能在不同的 release 中都能使用同樣的資料，就譬如 20150080072500、20150090083000 等資料夾中的 log 目錄想用同一個，這時候我們會把 log 目錄放在 shared 資料夾中，同時一些敏感資料如 database.yml 或是 settings.yml 這些不會放在版本控制的檔案，也會放在 shared 資料夾中，要怎麼放進去呢？那就要在設定檔中設定啦！</p><h4>設定檔</h4><p>Capistrano 的相關檔案在專案中的位置如下：</p><pre>├── Capfile<br>├── config<br>│   ├── deploy<br>│   │   ├── production.rb<br>│   │   └── staging.rb<br>│   └── deploy.rb<br>└── lib<br>    └── capistrano<br>            └── tasks</pre><blockquote>設定檔部分會依序介紹 Capfile、deploy.rb、prdouction.rb 這三份檔案</blockquote><p>Capfile 的設定會決定你的 Capistrano 可以使用哪些功能，這些功能也就是你能使用的 Capistrano 指令有哪些，以及在跑這些指令的時候會做什麼事。</p><p>將部分註解都拿掉，一份全新的 Capfile 設定檔可能長這樣</p><pre># Load DSL and set up stages<br>require &quot;capistrano/setup&quot;<br><br># Include default deployment tasks<br>require &quot;capistrano/deploy&quot;<br><br>require &quot;capistrano/scm/git&quot;<br>install_plugin Capistrano::SCM::Git<br><br># require &quot;capistrano/bundler&quot;<br># require &quot;capistrano/rails/assets&quot;<br># require &quot;capistrano/rails/migrations&quot;<br># require &quot;capistrano/passenger&quot;<br><br># Load custom tasks from `lib/capistrano/tasks` if you have any defined<br>Dir.glob(&quot;lib/capistrano/tasks/*.rake&quot;).each { |r| import r }</pre><p>為了部署 Rails App 同時讓我們管理設定檔方便，我會在 Capfile 加上</p><pre>require &quot;capistrano/bundler&quot;<br>require &quot;capistrano/rails/assets&quot;<br>require &quot;capistrano/rails/migrations&quot;<br>require &quot;capistrano/passenger&quot;<br>require &#39;capistrano/upload-config&#39;</pre><p>這樣我們就有了專門針對 Rails 部署設計的功能，至於到底會有什麼差別呢？我們可以在使用 cap production deploy 的時候知道，詳細情況會在常用指令介紹</p><p>接下來 deploy.rb 還有 production.rb 分別代表 global 的設定還有 stage specific 的設定，這是什麼意思呢？我們部署時可能有很多種環境，staging、production 等等之類的，如果有些設定是所有環境都套用的就是 global 的設定，如果是專門放在某個環境的就是 stage specific 的設定。其中 deploy.rb 裡面就是 global 的設定，而 config/deploy/ 這目錄下的 xxx.rb 就是 stage specific 的設定唷！</p><p>config/deploy.rb</p><blockquote>global 設定</blockquote><pre>lock &quot;~&gt; 3.10.1&quot;<br><br># 設定專案名稱<br>set :application, &quot;do_deploy&quot;<br><br># 讓機器知道要到哪裡找我們的程式碼<br>set :repo_url, &quot;git@github.com:shes50103/do_deploy.git&quot;<br><br># 放在 shared 中，那些不在版本控制中的檔案<br>append :linked_files, &quot;config/database.yml&quot;, &quot;config/secrets.yml&quot;, &quot;config/settings.yml&quot;<br><br># 放在 shared 中，不同 release 之間共享的目錄<br>append :linked_dirs, &quot;log&quot;, &quot;tmp/pids&quot;, &quot;tmp/cache&quot;, &quot;tmp/sockets&quot;, &quot;public/system&quot;</pre><p>config/deploy/production.rb</p><blockquote>stage specific 設定</blockquote><pre># 設定部署 Rails 的模式<br>set :rails_env, :production<br><br># 決定要部署版本控制庫的哪一個 branch<br>set :branch, &#39;master&#39;<br><br># 決定部署到遠端伺服器哪個地方，從絕對路徑寫起<br>set :deploy_to, &#39;/home/deploy/do_deploy.com&#39;<br><br># 見下方說明<br>role :web, %w{deploy@178.128.xxx.xxx}<br>role :db, %w{deploy@178.128.xxx.xxx}</pre><blockquote>其實如果你喜歡的話，把所有 deploy.rb 裡面的東西都丟到 production.rb 裡面也是跑得動的，問題就會是假如到時候想要部署 staging 的時候， staging.rb 也得寫一大堆東西</blockquote><p>整個部署流程，我們需要在本地電腦用 ssh 連線到遠端伺服器，要連線上去需要有遠端伺服器的 IP 以及我們要連線上去的身份，在這裡我們使用一個叫做 deploy 的使用者連線上去，意思就是在遠端伺服器裡面有這麼一個使用者，同時他的~/.ssh/authorized_keys 裡面有我本地電腦 ssh 公鑰，這樣我才能連線上去！</p><p>此外，當我以 deploy 使用者連線上遠端伺服器後，我還需要在遠端伺服器中再連線到程式碼倉庫，所以我也必須把 deploy 使用者的公鑰放到程式碼倉庫才能完成部署。記得前面提到的 Capistrano 的特性 Server roles 嗎？這邊看到的 role :web 還有 role :db 就是我們在部署時指定的 role 唷！</p><p>誒！？<br> 怎麼感覺只設定了一點點東西，其實設定檔還有很多其他參數可以調整，但都有預設值了，譬如</p><pre># Releases 目錄下最多保留五份程式碼<br>set :keep_releases, 5<br><br># 預設版本控制是使用 Git<br>set :scm, :git</pre><p>因為已經有預設值了，所以可以少設定很多東西，我們就特別對我們要設定參數調整即可！<br> 更多詳細資料可以看<a href="https://capistranorb.com/documentation/getting-started/configuration/">官方文件</a></p><h4>常用指令</h4><p>完成設定檔後，我們總需要在終端機下指令來部署或是操作些什麼，要怎麼知道我們現在的設定能使用哪些指令呢？那就是下面這個</p><pre>bundle exec cap -T</pre><p>可以查詢目前 Capistrano 中能使用的指令，能使用的指令有哪些就取決於 Capfile 中 require 了多少東西，可以試試看把一些 require 的設定註解掉後再輸入一次 bundle exec cap -T 能使用的指令會變少</p><pre>bundle exec cap production config:pull<br>bundle exec cap production config:push</pre><p>要使用這兩個指令必須安裝 gem &#39;capistrano-upload-config&#39; 以及在 Capfile 中加入 require &#39;capistrano/upload-config&#39; ，這兩個指令就是把遠端伺服器中的 linked_files 檔案抓下來以及上傳上去</p><pre>bundle exec cap production deploy:check</pre><p>這個指令會幫忙檢查要部署的專案目錄( deploy_to設定的那個 )、 linked_dirs 、 linked_files 這些是否存在，如果不存在它會幫我們把目錄的部分做出來，所以在部署專案的一開始都會使用這指令來幫我們把 shared 目錄建立好，這樣才能用 cap production config:push 將設定檔上傳上去！</p><p>接下來這個就是部署的指令啦！</p><pre>bundle exec cap production deploy</pre><p>到底會做什麼呢？取決於設定檔的寫法，如果 Capfile 有了這兩行</p><pre>require &quot;capistrano/setup&quot;<br>require &quot;capistrano/deploy&quot;</pre><p>在 deploy 的時候就會跑過以下步驟</p><pre>git:wrapper<br>git:check<br>deploy:check:directories<br>deploy:check:linked_dirs<br>deploy:check:make_linked_dirs<br>git:clone<br>git:update<br>git:create_release<br>deploy:set_current_revision<br>deploy:symlink:linked_files<br>deploy:symlink:linked_dirs<br>deploy:symlink:release<br>deploy:cleanup<br>deploy:log_revision</pre><p>如果要部署 Rails 這可能還不夠，我們會需要在 Capfile 內加上</p><pre>require &quot;capistrano/bundler&quot;<br>require &quot;capistrano/rails/assets&quot;<br>require &quot;capistrano/rails/migrations&quot;</pre><p>這樣在跑 deploy 的時候就能增加這幾個步驟</p><pre>bundler:install<br>deploy:assets:precompile<br>deploy:assets:backup_manifest<br>deploy:migrate<br>deploy:migrating</pre><blockquote>這五個步驟會在 deploy:symlink:linked_dirs 和 deploy:symlink:release 之間</blockquote><p>在使用 Capistrano 比較常卡關的問題可能就是有些步驟是只有特定的 role 才能執行，這時候就要另外設定，又或者是有些東西的安裝我們可能需要額外指定明確路徑，不然就會安裝在錯的地方。更詳細的部署流程可以參考<a href="https://capistranorb.com/documentation/getting-started/flow/">這裡</a></p><h4>結論</h4><p>在學習部署的過程中，儘管已經完整走完了部署的流程讓服務可以正常執行，但是對這些部署工具的掌握還是十分有限，有很多東西只知道出問題了要這樣做、要那樣試可能可以解決問題，但往往不是很清楚自己到底在幹嘛XD，所以趁這個機會整理了一下這些工具的使用方法。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f3f5d69077" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[動手做 Active Record！]]></title>
            <link>https://medium.com/@johnsonzhan/%E5%8B%95%E6%89%8B%E5%81%9A-active-record-e3f06a6667e?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f06a6667e</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 15:47:32 GMT</pubDate>
            <atom:updated>2020-03-04T16:05:49.693Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQSt3WreKgvaiqGjZPH9ew.jpeg" /></figure><h3>Rails探索：Active Record篇</h3><p>探索 Active Record 最直接的方法可能就是自己動手做一個吧!?</p><p>這篇文章將會做一個簡單版的 Active Record ，讀者有興趣的話可以跟著說明一起來做一個。這自製的 Active Record 有部分寫法是直接參考現有 Rails 的 Active Record ，也有部分則是依據我們需要的功能直接寫的程式，整體來說不管在效能、複雜度還是嚴謹性都和 Rails 的 Active Record 差很多，但整個 gem 的製作過程讓我對 Rails 還有 Ruby 都有更深一層的認識，所以在這裡寫成文章分享一下。</p><blockquote>這篇文章預設讀者已經有安裝 PostgreSQL Rails Bundler 這些東西囉！所以還沒安裝的人可能還需要先安裝一下~</blockquote><h4>目錄</h4><ul><li>準備工作</li><li>新增Gem</li><li>加入測試</li><li>資料庫設定</li><li>程式碼實作</li><li>步驟0: 環境設定</li><li>步驟1: 通過 attrbutes 測試</li><li>步驟2: 通過 save 測試</li><li>步驟3: 通過 find 測試</li><li>步驟4: 通過 where 測試</li><li>補充</li><li>結論</li></ul><h4>準備工作</h4><h4>新增Gem</h4><p>Rails 的 Active Record 是一個 gem ，我們也將做一個名為 activerecord_0216002 的 gem ，使用 bundler 來幫我們快速產生 gem 吧，首先在 terminal 使用 bundler 新增一個 gem</p><pre>bundler gem activerecord_0216002</pre><p>第一次設定時可以設定要選擇 rspec 還是 minitest ( 文章範例使用 rspec )</p><pre>Do you want to generate tests with your gem?<br>Type &#39;rspec&#39; or &#39;minitest&#39; to generate those test files now and in the future. rspec/minitest/(none):</pre><p>建立完成專案後我們可以用 rspec 指令來看看專案還缺少甚麼東西所以不能跑測試</p><p>輸入 rspec 看看會發生什麼事？</p><pre>The validation error was &#39;&quot;FIXME&quot; or &quot;TODO&quot; is not a description&#39;</pre><p>這時候要到 activerecord0216002.gemspec 檔案去設定一下，<br> 修改有 &quot;TODO&quot; 字樣的選項，這邊我偷懶一點就是都改成&#39;&#39;</p><pre>spec.summary       = &#39;&#39;<br>  spec.description   = &#39;&#39;<br>  spec.homepage      = &#39;&#39;</pre><p>完成後再一次輸入 rspec ，這時後可能會發現這專案有缺少的 gem 所以就再輸入 bundle install ，接著再輸入 rspec 就能正常測試囉！</p><h4>加入測試</h4><p>首先我們要覆蓋掉 bundler 幫我預設的測試，將我們的 activerecord_0216002_spec.rb 改成下面這樣，以下測試的的項目也就是我們的 gem 要實作的功能唷！</p><p>activerecord_0216002_spec.rb</p><pre>require &#39;rspec&#39;<br>require &#39;byebug&#39;<br># require &quot;activerecord_0216002&quot;<br>require &quot;active_record&quot;<br><br>ActiveRecord::Base.establish_connection(<br>  adapter: &#39;postgresql&#39;,<br>  database: &#39;my_db&#39;<br>)<br><br>class User &lt; ActiveRecord::Base<br>end<br><br>RSpec.describe &quot;Test User&quot; do<br>  before(:all)do<br>    User.new(name: &#39;Ancestor&#39;, phone: &#39;0932445631&#39;, age: 12).save<br>  end<br><br>  it &#39;1 test model with attrbutes&#39; do<br>    user = User.new(name: &#39;Bob&#39;, phone: &#39;0932445631&#39;, age: 12)<br>    expect(user.name).to eq(&#39;Bob&#39;)<br>    expect(user.phone).to eq(&#39;0932445631&#39;)<br>    expect(user.age).to eq(12)<br>  end<br><br>  it &#39;2 test model save record&#39; do<br>    user = User.new(name: &#39;Bob&#39;)<br>    expect{user.save}.to change{User.all.count}.by(1)<br>    expect{user.save}.to change{User.all.count}.by(0)<br>  end<br><br>  it &#39;2 test model save with value&#39; do<br>    User.new(name: &#39;Peter&#39;).save<br>    expect(User.last.name).to eq(&#39;Peter&#39;)<br>  end<br><br>  it &#39;3 test find&#39; do<br>    user = User.find(User.first.id)<br>    expect(user.id).to eq(User.first.id)<br>  end<br><br>  it &#39;4 test where chain&#39; do<br>    User.new(name: &#39;A&#39;, age: 20, phone: &#39;000&#39;).save<br>    User.new(name: &#39;A&#39;, age: 30, phone: &#39;6666&#39;).save<br>    User.new(name: &#39;B&#39;, age: 30, phone: &#39;000&#39;).save<br>    user = User.where(&quot;name = &#39;A&#39;&quot;).where(&quot;age &gt; 25&quot;).where(&quot;age &gt; 25&quot;).where(&quot;age &gt; 25&quot;).first<br>    expect(user.phone).to eq(&#39;6666&#39;)<br>  end<br>end</pre><blockquote>整份測試會做一個 User Model 然後測試自製的 new、 save、 find 和 where這些功能</blockquote><p>完成後再一次輸入 rspec 看看我們還缺少甚麼？<br> 可能會發現少了一些 gem</p><pre>LoadError:<br>  cannot load such file -- pg</pre><p>所以我們再一次打開 activerecord_0216002.gemspec 設定我們的 gem 要使用哪些其他 gem</p><p>activerecord_0216002.gemspec</p><pre>spec.add_development_dependency &quot;pg&quot;<br>  spec.add_development_dependency &quot;byebug&quot;</pre><ul><li>pg 是讓我們的 Ruby 程式碼可以更方便的使用 postgresql 的 gem</li><li>byebug 是幫助我追蹤程式碼使用的 gem</li></ul><p>再一次輸入 rspec 會發現有一些沒設定的常數，因為我們還沒開始設計我們的 Active Record 嘛！</p><pre>NameError:<br>  uninitialized constant ActiveRecord</pre><p>在開始設計 Active Record 之前，我們可以測試一下<br> 我們的測試在 Rails 原本的 Active Record 下能不能正常運作？</p><p>老樣子到 activerecord_0216002.gemspec 加上<br> spec.add_development_dependency &quot;activerecord&quot;<br> 接著修改一下測試，讓我們直接用 Rails 原本的 Active Record</p><pre># require &quot;activerecord_0216002&quot;<br>require &quot;active_record&quot;</pre><p>使用 rspec 跑跑看！ 這時候會發現…</p><pre>ActiveRecord::NoDatabaseError</pre><p>其實一般在 Rails 專案裡面的時候， Rails 幫我們做完太多事了<br> 還記得在 Rails 專案的時候我們常會輸入 rails db:create (建立資料庫)和rails db:migrate (設定資料表)這些指令嗎？</p><p>現在我們要自己到 psql 的介面手動設定這些東西啦&gt;&lt;</p><h4>資料庫設定</h4><p>到 PostgreSQL 的介面建立資料庫和資料表<br> 在 terminal 輸入 psql 進入 PostgreSQL 資料庫<br> 進入 psql 介面後有以下指令可以使用</p><p>常用指令說明:</p><ul><li>\l 列出資料庫</li><li>\q 離開psql介面</li><li>\c 連接資料庫</li><li>\d 列出該資料庫的所有資料表</li><li>\d 資料表名 列出資料表內的欄位</li></ul><p>首先我們要建立名為 my_db 的資料庫<br> 在資料庫介面輸入 CREATE DATABASE my_db;<br> 建立完成後可以輸入 \c my_db 進入 my_db 資料庫<br> 進入後可以看到輸入介面變成my_db=#<br> 接著輸入\d可以發現我們的 my_db 資料庫應該是空的還沒有資料表</p><p>我們要做兩個資料表，一個是 users 資料表，另一個是 users_id_seq 資料表，這是 users 資料表的 id 欄位<br> 輸入以下 SQL 指令</p><pre>CREATE SEQUENCE users_id_seq START 1;<br>CREATE TABLE users(id bigint DEFAULT nextval(&#39;users_id_seq&#39;) PRIMARY KEY<br>,name character varying, phone character varying, age integer);</pre><p>輸入完後再用\d確認是否新增資料表成功，<br> 也可以在使用 \d users \d users_id_seq 確認這兩張資料表的欄位<br> 確認完成後輸入 \q 離開psql介面！</p><h4>程式碼實作</h4><p>以上資料庫設定完成後，讓我們再輸入一次 rspec 看看吧！<br> 沒意外的話應該是能順利通過這五個測試<br> 接下來把測試的3,4行調整成</p><pre>require &quot;activerecord_0216002&quot;<br># require &quot;active_record&quot;</pre><p>也就是我們要用自己的 Active Record 啦</p><p>提示：</p><ul><li>接下來的教學會分成 0–4 個步驟來一步步完成</li><li>每個步驟也會對應到1–2個測試</li><li>每個測試名稱開頭的號碼就是第幾個步驟</li><li>每個 method 上面也會註解一個數字，代表這是第幾步驟需要用到</li></ul><h4>步驟0 : 環境設定</h4><p>所謂環境設定也就是我想要通過測試檔的5–8行<br> 要做出 ActiveRecord::Base 且讓他有 establish_connection 方法<br> 這其實就是跟 Active Record 說你可以去找哪個資料庫</p><pre>ActiveRecord::Base.establish_connection(<br>  adapter: &#39;postgresql&#39;,<br>  database: &#39;my_db&#39;<br>)</pre><p>首先我們要先把 Active Record 的框架做出來<br> 我們會將程式碼拆成6個rb檔</p><pre>lib<br>  ├── activerecord_0216002.rb<br>  └── activerecord_0216002<br>    ├── base.rb<br>    ├── method.rb<br>    ├── relation.rb<br>    ├── persistence.rb<br>    └── connection_adapter.rb</pre><p>activerecord_0216002.rb</p><pre>module ActiveRecord<br>  autoload :Base, &quot;activerecord_0216002/base&quot;<br>  autoload :Method, &quot;activerecord_0216002/method&quot;<br>  autoload :Relation, &quot;activerecord_0216002/relation&quot;<br>  autoload :Persistence, &quot;activerecord_0216002/persistence&quot;<br>  autoload :ConnectionAdapter, &quot;activerecord_0216002/connection_adapter&quot;<br>end</pre><p>在 activerecord_0216002.rb 中我們會把需要的檔案都 autoload 進來，以第三行 autoload :Base, &quot;activerecord_0216002/base&quot; 來說就是程式執行後看到常數譬如ActiveRecord::Base 就知道要去找activerecord_0216002/base 的檔案，autoload就和 require 很像，不會重複讀取同份檔案多次浪費資源，而且autoload 比 require 更聰明的地方是他的動作就像是 &quot;登記&quot;，假如今天 ActiveRecord::Base 這常數沒被使用到，那 activerecord_0216002/base 檔案也不會被讀取</p><p>再來將activerecord_0216002資料夾下的5個rb檔案新增出來</p><p>base.rb</p><pre>module ActiveRecord<br>  class Base<br>    include Persistence<br>    extend Method<br>  end<br>end</pre><p>在Rails中有著這樣的關係 YourModel &lt;&lt; ActiveRecord::Base ，也就是說我們平常我們在操作的 model 其實也就是繼承了 ActiveRecord::Base 的 class 。在 base.rb 中我將 instance method 放在 persistence.rb 中，而class method 放在 method.rb ，因此分別使用了 include 和 extend</p><p>method.rb</p><pre>module ActiveRecord<br>  module Method<br>    #0<br>    def establish_connection(option)<br>      case option[:adapter]<br>      when &#39;postgresql&#39;<br>        @@connection = ConnectionAdapter::PostgreSQLAdapter.new(option[:database])<br>      when &#39;sqlite&#39;<br>        #TODO<br>      end<br>    end<br><br>    #0<br>    def connection<br>      @@connection<br>    end<br>  end<br>end</pre><blockquote>method.rb 裡面的每個method都是 ActiveRecord::Base 的 class method 唷！</blockquote><p>在 establish_connection 這動作中會設定我們的 ActiveRecord::Base 將如何連線到資料庫，用 option[:adapter] 決定&quot;哪種&quot;資料庫，用option[:database] 決定&quot;哪個&quot;資料庫!可以看到測試那邊選了 postgresql 這種資料庫下面的 my_db 資料庫！</p><p>另一個比較特別的是這邊使用 @@connection 類別變數來儲存資料，原因是我們需要用 &quot;類別變數&quot; 來讓之後繼承了 ActiveRecord::Base 的 User 這個 class 可以使用這個變數</p><p>connection_adapter.rb</p><pre>module ActiveRecord<br>  module ConnectionAdapter<br>    class PostgreSQLAdapter<br>      def initialize(dbname)<br>        require &#39;pg&#39;<br>        @db = PG.connect(dbname: dbname)<br>      end<br><br>      def execute(sql)<br>        @db.exec(sql)<br>      end<br>    end<br>  end<br>end</pre><p>在Rails中我們可能使用不同的資料庫(PostgreSQL, SQLite等等)，為了讓ActiveRecord能支援多種資料庫而且不浪費記憶體，ConnectionAdapter 會依據使用者選了不同類型的資料庫然後 require 不同的資料庫進來(如第5行) require &#39;pg&#39;</p><p>persistence.rb</p><pre>module ActiveRecord<br>  module Persistence<br>  end<br>end</pre><blockquote>還只是第 0 步可以先這樣寫，而relation.rb 部分可以第二部後再開始XD</blockquote><h4>步驟1 : 通過 attrbutes 測試</h4><p>activerecord_0216002_spec.rb</p><pre>it &#39;1 test model with attrbutes&#39; do<br>    user = User.new(name: &#39;Bob&#39;, phone: &#39;0932445631&#39;, age: 12)<br>    expect(user.name).to eq(&#39;Bob&#39;)<br>    expect(user.phone).to eq(&#39;0932445631&#39;)<br>    expect(user.age).to eq(12)<br>  end</pre><p>我們要通過第一個 attrbutes 的測試，希望可以讓 Model 的 class 可以 new 出一個 instance ，而且 instance 可以帶有參數如上面測試的 name、phone 之類的</p><p>persistence.rb</p><pre>#1<br>    def initialize(attributes = {})<br>      self.class.set_column_name_to_method_attribute<br>      @attributes = attributes<br>    end</pre><p>我們在 persistence.rb 加上initialize 這個 instance method ，這也就是讓 ActiveRecord::Base 有這 instance method ，這也就像一般在寫Ruby時我們會直接寫 def initialize ... 而非 def self.new ...。</p><p>其中我用 @attributes 來儲存model初始化的參數，而 set_column_name_to_method_attribute 是用來動態為model產生 attribute method ，因為 set_column_name_to_method_attribute 本身是class method所以我就統一整理在 method.rb 囉！</p><blockquote>attribute method 就是說 user.phone、user.name 這些</blockquote><p>method.rb</p><pre>#1<br>    def set_column_name_to_method_attribute<br>      columns = self.connection.execute(&quot;SELECT column_name FROM information_schema.columns<br>        WHERE table_name= &#39;#{self.table_name}&#39;&quot;).map{|m|  m[&quot;column_name&quot;]}<br>      columns.each{ |e| define_method_attribute(e) }<br>    end<br><br>    #1<br>    def define_method_attribute(name)<br>      class_eval &lt;&lt;-STR<br>        def #{name}<br>          @attributes[:#{name}] || @attributes[&quot;#{name}&quot;]<br>        end<br><br>        def #{name}=(value)<br>          @attributes[:#{name}] = value<br>        end<br>      STR<br>    end<br><br>    #1<br>    def table_name<br>      name.downcase + &quot;s&quot;<br>    end</pre><p>在 set_column_name_to_method_attribute 方法中我先透過 columns 取得一個model在資料表中擁有的欄位，譬如能從User中找到 [&quot;id&quot;, &quot;name&quot;, &quot;phone&quot;, &quot;age&quot;] 這些欄位，接下來在第二個 define_method_attribute 方法中透過class_eval動態產生 id、name、phone 這些 attribute method。</p><p>為什麼是使用 class_eval 來定義 method 呢？</p><blockquote>現在的情境是我們在 class 的 scope 裡定義方法，我們直接定義方法的話都會變成class method，也就是把 id、name 之類的方法直接定義在 User 上，而 clsss_eval 的功能就是他能讓你在 class 的 scope 裡定義 instance method!</blockquote><p>為什麼使用 &lt;&lt;-STR ... STR 字串型態而非常見的do ... end呢？</p><blockquote>因為我想要定義的method名稱是個變數，他可能是 id、name 之類的，所以透過 STR 我能用#{name}這種方法來讓def後面的 method 名稱是個傳進來的值。其中這個 STR 你可以換成其他你喜歡的字譬如 &lt;&lt;-abc 之類的</blockquote><p>我們可以做個小小的實驗看 class_eval 有什麼樣的功能！<br> 執行以下這檔案<br> test.rb</p><pre>module Machine<br>  def start<br>    class_eval do<br>      def go<br>        puts &#39;Go!!&#39;<br>      end<br>    end<br><br>    def stop<br>      puts &#39;Stop!!&#39;<br>    end<br>  end<br>end<br><br>class Car<br>  extend Machine<br>end<br><br>c = Car.new<br>Car.start<br>c.go<br>c.stop</pre><p>執行 ruby test.rb 結果是...</p><pre>Go!!<br>test.rb:24:in `&lt;main&gt;&#39;: undefined method `stop&#39; for #&lt;Car:0x007fca0c8a03d0&gt; (NoMethodError)</pre><p>go 方法成功定義成 instance method ，而 stop 方法會變成 Car 的 class method ，因為第16行做了這事 extend Machine ，想要在這情況下做出instance method就要靠 class_eval 啦！</p><h4>步驟2 : 通過 save 測試</h4><p>activerecord_0216002_spec.rb</p><pre>it &#39;2 test model save record&#39; do<br>    user = User.new(name: &#39;Bob&#39;)<br>    expect{user.save}.to change{User.all.count}.by(1)<br>    expect{user.save}.to change{User.all.count}.by(0)<br>  end<br><br>  it &#39;2 test model save with value&#39; do<br>    User.new(name: &#39;Peter&#39;).save<br>    expect(User.last.name).to eq(&#39;Peter&#39;)<br>  end</pre><p>26–30行的測試是測驗 user 呼叫 save 之後，能不能成功新增一筆資料，同時第29行測第二次呼叫save後會不會重複新增資料，32-35行的測試要看 save 後能否將正確的 attributes 存入資料庫。</p><p>步驟二的程式分成部分，第一部分是 “儲存” 資料，第二部分是 “讀取” 資料</p><p>persistence.rb 完全解鎖</p><pre>module ActiveRecord<br>  module Persistence<br>    #1<br>    def initialize(attributes = {})<br>      self.class.set_column_name_to_method_attribute<br>      @attributes = attributes<br>      @new_record = true<br>    end<br><br>    #2<br>    def new_record?<br>      @new_record<br>    end<br><br>    #2<br>    def save<br>      if new_record?<br>        self.class.connection.execute(&quot;INSERT INTO #{self.class.table_name}<br>        (#{@attributes.keys.join(&#39;,&#39;)}) VALUES (#{&quot;&#39;&quot;+@attributes.values.join(&quot;&#39;, &#39;&quot;)+&quot;&#39;&quot;})&quot;)<br>        @new_record = false<br>        true<br>      else<br>        false<br>      end<br>    end<br>  end<br>end</pre><p>persistence 的程式就是在做 &quot;儲存&quot; 資料的工作，在 initialize 部分我們新增了 @new_record 用來檢查這個 model 有沒有被 save 過，在下方 save method也可以看到對應的判斷。</p><p>save method 中將使用 connection 方法來讓 SQL 指令直接對資料表插入資料，而我們能取的的原始資料( @attributes.keys、@attributes.kes )格式還需經過 .join(&#39;,&#39;) 來轉換，<br> @attributes.keys 和 @attributes.values 轉換方式如下</p><blockquote>[:name, :phone, :age] =&gt; “name, phone, age”</blockquote><blockquote>[“Ancestor”, “0932445631”, 12] =&gt; “‘Ancestor’, ‘0932445631’, ‘12’”</blockquote><p>method.rb</p><pre>#2<br>    def all<br>      Relation.new(self).records<br>    end<br><br>    #2<br>    def last<br>      all.last<br>    end<br><br>    #2<br>    def find_by_sql(sql)<br>      connection.execute(sql).map do |attributes|<br>        new(attributes)<br>      end<br>    end</pre><p>relation.rb</p><pre>module ActiveRecord<br>  class Relation<br>    #2<br>    def initialize(klass)<br>      @klass = klass<br>    end<br><br>    #2<br>    def to_sql<br>      &quot;SELECT * FROM #{@klass.table_name}&quot;<br>    end<br><br>    #2<br>    def records<br>      @records ||= @klass.find_by_sql(to_sql)<br>    end<br>  end<br>end</pre><p>講完儲存資料後，接下來是 “讀取” 資料的部分。</p><p>這邊你會發現我們特別做了一個 Relation 的 class 來處理 &quot;讀取&quot; 資料的部分，為什麼要這麼大費周章呢？其實是在幫步驟4 where 的功能鋪路，記得在Rails中 where 或是 all 方法會回傳什麼東西嗎？不是 array 而是 XX_model::ActiveRecord_Relation ，現在我們也就是要做出類似的功能唷！</p><p>在 method.rb 的 all 方法中我們將 User 這個 class 丟進參數中，做出一個 User 的 Relation 的物件，現階段這個物件功能最主要就是 records 方法，他會再呼叫再 method.rb 中定義的 find_by_sql<br> 來回傳一個 User的物件陣列。</p><p>在這邊我很偷懶的直接讓 method.rb 中的 all 方法就是等於直接回傳呼叫 records 的結果，也就是說測試中的 User.all 其實是直接回傳一個陣列喔！這跟一般Rails裡面的狀況不一樣！</p><h4>步驟3 : 通過 find 測試</h4><p>activerecord_0216002_spec.rb</p><pre>before(:all)do<br>    User.new(name: &#39;Ancestor&#39;, phone: &#39;0932445631&#39;, age: 12).save<br>  end</pre><pre>it &#39;3 test find&#39; do<br>    user = User.find(User.first.id)<br>    expect(user.id).to eq(User.first.id)<br>  end</pre><p>到第三個測試時我們就會使用 before(:all) 來確保測試之前資料庫裡面至少有一筆資料XD，步驟3 相對前面的步驟相對簡單，只要在做出 find 功能就好囉！</p><p>method.rb</p><pre>#3<br>    def first<br>      all.first<br>    end<br><br>    #3<br>    def find(id)<br>      find_by_sql(&quot;SELECT * FROM #{table_name} WHERE id = #{id.to_i}&quot;).first<br>    end</pre><p>這個 first 就和步驟2的 last 一樣意思，就是把 all 回傳的陣列直接用 ruby 的方式取出第一個或最後一個值。</p><p>find 其實跟 relation.rb 裡的 records 方法很像，就是透過 find_by_sql 來跑一段SQL指令而已，這時候會回傳一個陣列所以我在最後面加上 .first 。</p><h4>步驟4 : 通過 where 測試</h4><p>activerecord_0216002_spec.rb</p><pre>it &#39;4 test where chain&#39; do<br>    User.new(name: &#39;A&#39;, age: 20, phone: &#39;000&#39;).save<br>    User.new(name: &#39;A&#39;, age: 30, phone: &#39;6666&#39;).save<br>    User.new(name: &#39;B&#39;, age: 30, phone: &#39;000&#39;).save<br>    user = User.where(&quot;name = &#39;A&#39;&quot;).where(&quot;age &gt; 25&quot;).first<br>    expect(user.phone).to eq(&#39;6666&#39;)<br>  end</pre><p>我們的 where 支援 Chain，也就是你能一直 where 下去User.where(..).where(..)，乍看之下 where 像是 User 的 class method 但是他也是 Relation 的 instance method ，究竟是怎麼回事呢？讓我們看下去...</p><blockquote>我們的 where 相當基本，他只能直接用SQL來查詢，像這樣where(&#39;id = 1&#39;) ，沒辦法用Hash查詢，就是沒有 where(id:1) 這種方法</blockquote><p>method.rb</p><pre>#4<br>    def where(*args)<br>      Relation.new(self).where(*args)<br>    end</pre><p>method.rb 裡的 where 就是 User 的 class method ，裡面在做的事情也就是做出一個 Relation 物件然後再用 Relation 物件呼叫 Relation 的 where ，這也就是我們能一直 where 下去的原因啦！<br> 無論是第一個 User 叫出來的where還是第 n 個 ActiveRecord_Relation 叫出來的 where 都是一樣的！</p><p>relation.rb</p><pre>module ActiveRecord<br>  class Relation<br>    #2<br>    def initialize(klass)<br>      @klass = klass<br>      @where_values = []<br>    end<br><br>    #2<br>    def to_sql<br>      sql = &quot;SELECT * FROM #{@klass.table_name}&quot;<br>      if @where_values.any?<br>        sql += &quot; WHERE &quot; + @where_values.join(&quot; AND &quot;)<br>      end<br>      sql<br>    end<br><br>    #2<br>    def records<br>      @records ||= @klass.find_by_sql(to_sql)<br>    end<br><br>    #4<br>    def where(condition)<br>      @where_values += [condition]<br>      self<br>    end<br><br>    #4<br>    def first<br>      records.first<br>    end<br>  end<br>end</pre><p>我們將步驟2做的 Relation 又更加擴充了，加上了 @where_values 來儲存多個 where 的資料，如何儲存的呢？在每一次 where 後都會 @where_values += [condition] 讓這個陣列越來越長，最後在呼叫 records 方法時，就會在 to_sql 方法中用 @where_values.join(&quot; AND &quot;) 把陣列的值都取出來然後用 AND 接再一起！</p><blockquote>to_sql 方法就是把測試的資料從<br> where(“name = ‘A’”).where(“age &gt; 25”)<br> 變成<br> “SELECT * FROM users WHERE name = ‘A’ AND age &gt; 25”</blockquote><p>最後最後，再一次輸入 rspec 看看會發生什麼事 ?</p><pre>Test User<br>  1 test model with attrbutes<br>  2 test model save record<br>  2 test model save with value<br>  3 test find<br>  4 test where chain<br><br>Finished in 0.46207 seconds (files took 0.52716 seconds to load)<br>5 examples, 0 failures</pre><p>就這樣我們完成了四個步驟，通過了五個測試，做出了自己的 Active Record 啦 :)</p><h4>補充</h4><p>範例程式碼放在我的 <a href="https://github.com/shes50103/activerecord_0216002">GitHub</a><br> 如果你想把整份 gem 安裝在自己電腦裡可以輸入</p><p>gem install activerecord_0216002</p><p>把這個 gem 裝在自己的電腦裡，裝完後可以再輸入</p><p>gem env</p><p>然後找 INSTALLATION DIRECTORY: 對應的位置就能知道你電腦安裝 gem 的位置在哪裡唷！裝好這 gem 後你就能輕鬆的在你的 Ruby 檔案中 require &quot;activerecord_0216002&quot; 啦！</p><h4>結論</h4><p>在學習 Rails 的過程中我們會好奇各種 Rails 的魔法是怎麼做出來的？這時候去看了下 Rails 的原始碼才發現裡面博大精深我真的是看不懂。後來隨著對 Ruby 有越來越多的認識後，再加上網路上找到的一些資料，總算能做出一個超簡單 ActiveRecord ，雖然東西是做出來了，但能進步的空間還很大！希望未來在寫 Rails 時候遇到問題後我除了可以上網查外，還可以因為對 Rails 的本身的了解，從 Rails 的原始法裡找答案，如果這樣可以比較快的話XD</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f06a6667e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RubyKaigi 2018 心得]]></title>
            <link>https://medium.com/@johnsonzhan/rubykaigi-2018-%E5%BF%83%E5%BE%97-77d2e1bd96c1?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d2e1bd96c1</guid>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 13:47:56 GMT</pubDate>
            <atom:updated>2018-09-10T13:48:22.286Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>RubyKaigi 是一年一度的 Ruby 開發者聚會，這一個活動除有為期三天一共三軌滿滿的議程之外，還有數不清的各種 Party。所以不管是要學習 Ruby 還是認識其他的開發者又或是品嚐各種日本清酒，來日本的 RubyKaigi 都絕對可以滿足以上的需求，但是，不管是飛一趟日本、RubyKaigi 的門票還是在日本的住宿等等花費都不便宜，幸好以上五倍紅寶石公司已經全部都補助了，所以對我來說這趟旅程基本上是花不到自己的錢的，只能說有機會去這樣 RubyKaigi 真的蠻幸運的！</p><h4>日本 remote 工作體驗</h4><p>RubyKaigi 的議程會在我們到仙台的第三天開始，所以在仙台的第二天我們會在飯店或咖啡廳 remote 工作! 在各種不同的地方遠端工作都是很不同的體驗、我試過在山上、淡水河邊、咖啡廳等等不同的地方，在飯店遠端工作還算是第一次！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DNnAisBKDnV4Zr6i.jpg" /></figure><p>這是我們的飯店，仙台車站旁邊的先台大都會大飯店，早上的時候把窗簾拉開可以俯瞰整個仙台車站，可惜當時忘了拍照所以只有這張相片了</p><figure><img alt="飲料" src="https://cdn-images-1.medium.com/max/1024/0*l6eMYUG6l-pJsgrQ.jpg" /></figure><p>在日本吃東西大多都比台灣貴一點，唯獨這種鋁箔包包裝的飲料超級便宜，不管是牛奶、咖啡還是果汁，近一公升容量只要日幣不到 100 元。想像隨便吃個便當都要 1000 日幣但是一公升牛奶或果汁只要 100 日圓，所以一到日本馬上買了一堆飲料把冰箱塞滿，時而不時就可以來喝兩口。</p><h4>Pre Party</h4><p>在 remote 工作後，接下來就是晚上的 Pre Party 啦，這是由 RubyKaigi 的贊助商之一 Speee 主辦的活動，一進入 Party 的會場…</p><figure><img alt="Imgur" src="https://cdn-images-1.medium.com/max/640/0*DN-EiuBjkbT-xogP.jpg" /></figure><p>就看到場內滿滿的食物，各種美食、啤酒還有生魚片吃到飽。除了以上食物外，在會場最重要的事就是多多找其他的 Ruby 工程師聊天交流囉，對我來說這是一件蠻有難度的事，跟一個不認識的人從無到有開始聊天，而且還在兩個人的英文都不太好但只能用英文溝通的狀態下，真的只能恥度全開硬著頭皮上了！</p><figure><img alt="Imgur" src="https://cdn-images-1.medium.com/max/640/0*VJ3QDc7uvr_yxG48.jpg" /></figure><p>在這種社交場合，如果要搭訕就要找對人，有些人肚子餓拿著餐盤拼命吃東西，這種人不適合，我專門挑那種只拿著酒瓶，然後環顧四周好像在找著什麼的，這種人讓我感覺起來，似乎他也在找人搭話但還猶豫著，於是我就會隨便找幾個蠢問題上前聊天。</p><p>靠著這個方法，在2018台灣的 Ruby conf 認識了不少外國人，有趣的是這一些當時認識的外國人大多也會出現在 RubyKaigi，所以對我來說，除了找完全陌生的人搭話，我也可以遇到一些有一面之緣人在聊幾句，只能說只要恥度夠能做的事真的很多XD</p><h4>Kaigi 開始</h4><figure><img alt="走到會場" src="https://cdn-images-1.medium.com/max/1024/0*Yo54SZOa5XdaduGe.jpg" /></figure><p>Kaigi 的會場離車站非常近</p><figure><img alt="會場" src="https://cdn-images-1.medium.com/max/1024/0*xAFY7v-vPIrC5KTL.jpg" /></figure><p>Kaigi 的第一個議程由 Matz 開場的演講，講解關於命名的重要以及 Ruby 的發展方向。同時也是會場這也是最多人參與的議程，目測大概有1000多位 Rubyist 吧！</p><figure><img alt="Stan" src="https://cdn-images-1.medium.com/max/1024/0*Vw01j0DDzHOdSWq0.png" /></figure><p>對我來說，最有感覺的議程是 What would your own version of Ruby look like? 這演講在介紹 Goby 這一個台灣本土程式語言，因為之前有參與過開發 Goby 的開源專案，所以在聽這議程的時候格外深刻。</p><p>這演講主要在分享 Goby 程式語言目前開發狀況、未來展望，以及 Stan 在開發這程式語言過程的一些心路歷程，看著自己有參與過一點的專案也是 RubyKaigi 中的一部分，感覺真的是蠻特別的，這也是少數我比較聽得懂的議程XD</p><h4>Kaigi 後的晚上</h4><figure><img alt="酒" src="https://cdn-images-1.medium.com/max/1024/0*lGsQVT9p-WcM8IHe.jpg" /></figure><p>在聽完各種議程之後，晚上最特別的就是 After Party 啦！ After Party 就是在正式 Party 之後的聚會，可能是 3–5 個工程師一起去酒吧喝酒又或是大型一點的由公司贊助的中型 Party。</p><figure><img alt="酒2" src="https://cdn-images-1.medium.com/max/1024/0*bIXSMJXxHR9-4IaV.jpg" /></figure><p>上圖是清酒很強的 ESM 公司贊助的 Party，而且這 Party 感覺不是隨便就能報名參加的，我們運氣很好可以參加這活動，只可惜我真的喝不太了酒精濃度大於啤酒的酒QQ</p><h4>初訪秋葉原</h4><figure><img alt="秋葉原" src="https://cdn-images-1.medium.com/max/1024/0*rg7Sv6EWZZAvFVN6.jpg" /></figure><p>在 RubyKaigi 結束後，我們搭了電車到了東京，接下來兩天除了有部分同事要花一些時間去拜訪日本客戶外，剩下的時間我們就在東京當觀光客。最讓我期待的行程就是「秋葉原」啦！雖然我完全沒有買任何玩偶、漫畫等動漫周邊產品，但由於看過「命運石之門」的動畫，所以一直想來看看秋葉原這個地方。</p><figure><img alt="秋葉原街景" src="https://cdn-images-1.medium.com/max/1024/0*G2dk321DNMF5IWNy.jpg" /></figure><p>這可能是運氣很好才看得到的街景吧？不曉得開一次多少錢有點想試試看</p><h4>好友聚會</h4><figure><img alt="Hub" src="https://cdn-images-1.medium.com/max/1024/0*-ruUN35tjz9qDr48.jpg" /></figure><p>在秋葉原那晚我也約了在台灣的 Ruby conf 認識的 Matt(右1) 還有在 Kaigi 認識的 200 公分巨人 Lee(左1) ，我們在 Hub(酒吧連鎖店)喝了一整晚，對我來說真的是蠻特別的經驗，原本只是隨意在 Party 期間找人聊天，沒想到居然可以認識一群到東京都約得到的朋友！聊天內容涵括外國人來日本生活的故事，工程師的心路歷程等等，對我來說能在這樣的場合遇到這些人真的是蠻難忘的！</p><h4>感想</h4><p>RubyKaigi 裡議程的內容都相當「硬」，幾乎都是在講 Ruby 底層的各種深奧的東西，尤其是那些日文的演講，本身內容艱深又加上我們只能聽即時英文口譯，所以基本上是聽不懂的！只能看投影片自行理解啦XD，但其實所有 RubyKaigi 的演講都有錄影公告在 Kaigi 的官方網站，所以其實來 RubyKaigi 最有價值的事就是好好玩，感受這裡的氣氛跟認識人啦！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d2e1bd96c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discover Rails: Active Record]]></title>
            <link>https://medium.com/@johnsonzhan/discover-rails-active-record-cc15140adfe7?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc15140adfe7</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Sat, 25 Aug 2018 15:02:13 GMT</pubDate>
            <atom:updated>2018-08-25T15:19:13.472Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwQZifYrt5zzCmycmbxj_A.jpeg" /></figure><h4>Make your own Active Record!</h4><p>One of the best way to study Active Record is to make one by myself?</p><p>I will make a simple Active Record. If you are interesting in this topic you can follow this article and make your own version. Part of my simple Active Record take Rails as reference and I implement the other features directly. Although the performance and quality of my Active Record is worse than real Active Record, this topic is still a chance for me to study Ruby and Rails.</p><blockquote>Before we start, I expect you already install PostgreSQL, Ruby, Bundler and Rails in your environment. If you haven’t installed some of these tools you need to install it first.</blockquote><h4>Category</h4><ul><li>Preparation</li><li>Create gem</li><li>Use rspec</li><li>Database setting</li><li>Write your code</li><li>Step0: Environment settings</li><li>Step1: Pass attributes test</li><li>Step2: Pass save test</li><li>Step3: Pass find test</li><li>Step4: Pass where test</li><li>More information</li><li>Conclusion</li></ul><h4>Preparation</h4><h4>Create gem</h4><p>The Active Record in Rails is a gem. I will create a gem called activerecord_0216002. Use bundler to help us create a gem and input the following command on terminal.</p><pre>bundler gem activerecord_0216002</pre><p>The first time using this command will pop up the rspec or minitest option (we will use rspec to test our code)</p><pre>Do you want to generate tests with your gem?<br>Type &#39;rspec&#39; or &#39;minitest&#39; to generate those test files now and in the future. rspec/minitest/(none):</pre><p>After creating gem we will use rspec command to test whether or not we miss something.</p><p>Input rspec and see what will happen?</p><p>The validation error was &#39;&quot;FIXME&quot; or &quot;TODO&quot; is not a description&#39;</p><p>We need to check out activerecord0216002.gemspec file. We will find some &quot;TODO&quot; options.</p><pre>  spec.summary       = &#39;&#39;<br>  spec.description   = &#39;&#39;<br>  spec.homepage      = &#39;&#39;</pre><p>Replace these options to &#39;&#39; then we can pass rspec. Now we will find out we miss some gem so execute bundle install again and we can pass rspec.</p><h4>Use Rspec</h4><p>First of all, we need to remove the default rspec which made by bundler. We change our activerecord_0216002_spec.rb as the following example. The following example is the features we want to implement in our gem.</p><p>activerecord_0216002_spec.rb</p><pre>require &#39;rspec&#39;<br>require &#39;byebug&#39;<br># require &quot;activerecord_0216002&quot;<br>require &quot;active_record&quot;<br><br>ActiveRecord::Base.establish_connection(<br>  adapter: &#39;postgresql&#39;,<br>  database: &#39;my_db&#39;<br>)<br><br>class User &lt; ActiveRecord::Base <br>end<br><br>RSpec.describe &quot;Test User&quot; do<br>  before(:all)do<br>    User.new(name: &#39;Ancestor&#39;, phone: &#39;0932445631&#39;, age: 12).save<br>  end<br><br>  it &#39;1 test model with attributes&#39; do<br>    user = User.new(name: &#39;Bob&#39;, phone: &#39;0932445631&#39;, age: 12)<br>    expect(user.name).to eq(&#39;Bob&#39;)<br>    expect(user.phone).to eq(&#39;0932445631&#39;)<br>    expect(user.age).to eq(12)<br>  end<br><br>  it &#39;2 test model save record&#39; do<br>    user = User.new(name: &#39;Bob&#39;)<br>    expect{user.save}.to change{User.all.count}.by(1)<br>    expect{user.save}.to change{User.all.count}.by(0)<br>  end<br><br>  it &#39;2 test model save with value&#39; do<br>    User.new(name: &#39;Peter&#39;).save<br>    expect(User.last.name).to eq(&#39;Peter&#39;)<br>  end<br><br>  it &#39;3 test find&#39; do<br>    user = User.find(User.first.id)<br>    expect(user.id).to eq(User.first.id)<br>  end<br><br>  it &#39;4 test where chain&#39; do<br>    User.new(name: &#39;A&#39;, age: 20, phone: &#39;000&#39;).save<br>    User.new(name: &#39;A&#39;, age: 30, phone: &#39;6666&#39;).save<br>    User.new(name: &#39;B&#39;, age: 30, phone: &#39;000&#39;).save<br>    user = User.where(&quot;name = &#39;A&#39;&quot;).where(&quot;age &gt; 25&quot;).where(&quot;age &gt; 25&quot;).where(&quot;age &gt; 25&quot;).first<br>    expect(user.phone).to eq(&#39;6666&#39;)<br>  end<br>end</pre><blockquote>In our test, we will create a User model and test new, save, find and where methods.</blockquote><p>Let’s run rspec again and we will find we miss some gems.</p><pre>LoadError:<br>  cannot load such file -- pg</pre><p>We will set the gem dependency of our Active Record in activerecord_0216002.gemspec file.</p><p>activerecord_0216002.gemspec</p><pre>  spec.add_development_dependency &quot;pg&quot;<br>  spec.add_development_dependency &quot;byebug&quot;</pre><ul><li>pg is the gem to enable our Active Record access postgresql</li><li>byebug is a debug tool help us trace our code</li></ul><p>Run rspec again we will find uninitialized constant. That is because we haven&#39;t implemented gem ActiveRecord.</p><pre>NameError:<br>  uninitialized constant ActiveRecord</pre><p>Before we build our Active Record, we can try to make the Rails Active Record pass our test.</p><p>Same as always, add spec.add_development_dependency &quot;activerecord&quot; in our activerecord_0216002.gemspec file. Update our test as following to require Rails Active Record.</p><pre># require &quot;activerecord_0216002&quot;<br>require &quot;active_record&quot;</pre><p>Run rspec again we will find…</p><pre>ActiveRecord::NoDatabaseError</pre><p>Rails help us too much in most of Rails project. Do you remember rails db:create (build the database) command or rails db:migrate (build the migration) command?</p><p>Now we need to use PostgreSQL interface to set the database and create table ourselves.</p><h4>Database setting</h4><p>Use psql command in terminal to enter PostgreSQL interface. After accessing PostgreSQL interface we can use following commands.</p><p>Common instructions:</p><ul><li>\l list database</li><li>\q quit PostgreSQL interface</li><li>\c connect or enter the database</li><li>\d list the tables of the database</li><li>\d &#39;table_name&#39; list the data field of particular table</li></ul><p>First, we create a database named my_db. Input CREATE DATABASE my_db; in PostgreSQL interface. Then we can use \c my_db to enter my_db database. After entering we can find the left side of our command line become my_db=#. Input \d you will find there are no table in our database.</p><p>We want to make two tables. One is users table another is users_id_seq table. The second one is the id data field of users table. Enter following SQL command.</p><pre>CREATE SEQUENCE users_id_seq START 1;<br>CREATE TABLE users(id bigint DEFAULT nextval(&#39;users_id_seq&#39;) PRIMARY KEY<br>,name character varying, phone character varying, age integer);</pre><p>Use \d to check whether or not we create table. We can also use \d users \d users_id_seq to check the data field of each table. After all the jobs are done, use \q to quit the PostgreSQL interface.</p><h4>Write your code</h4><p>After the settings above, we can try rspec again. If no surprises we an pass these five tests. Now update our rspec file as following.</p><pre>require &quot;activerecord_0216002&quot;<br># require &quot;active_record&quot;</pre><p>That is using our own Active Record~</p><p>Tips:</p><ul><li>The instructions will break down to 0~4 steps</li><li>Every step needs to pass 1 or 2 test</li><li>The number before each test is corresponding to each step</li><li>The number before each method means we will use this method in which steps</li></ul><h4>Step0: Environment settings</h4><p>The so-called environment settings is to pass the following code. We need to build ActiveRecord::Base and implement establish_connection method which is the way to let Active Record know how to connect to the database.</p><pre>ActiveRecord::Base.establish_connection(<br>  adapter: &#39;postgresql&#39;,<br>  database: &#39;my_db&#39;<br>)</pre><p>Build the framework of Active Record. I divide the code into six ruby files.</p><pre>lib<br>  ├── activerecord_0216002.rb<br>  └── activerecord_0216002<br>    ├── base.rb<br>    ├── method.rb<br>    ├── relation.rb<br>    ├── persistence.rb<br>    └── connection_adapter.rb</pre><p>activerecord_0216002.rb</p><pre>module ActiveRecord<br>  autoload :Base, &quot;activerecord_0216002/base&quot;<br>  autoload :Method, &quot;activerecord_0216002/method&quot;<br>  autoload :Relation, &quot;activerecord_0216002/relation&quot;<br>  autoload :Persistence, &quot;activerecord_0216002/persistence&quot;<br>  autoload :ConnectionAdapter, &quot;activerecord_0216002/connection_adapter&quot;<br>end</pre><p>We will use autoload to require other files. Autoload works in a similar way to require, but it only loads the specified file when a constant is used for the first time. For example, autoload :Base, &quot;activerecord_0216002/base&quot; means we will sign up ActiveRecord::Base this constant and when we call it at first time we will load the file at activerecord_0216002/base.</p><p>Let’s add five ruby files in activerecord_0216002 directory.</p><p>base.rb</p><pre>module ActiveRecord<br>  class Base<br>    include Persistence<br>    extend Method<br>  end<br>end</pre><p>In our Rails project, we have the code like this YourModel &lt;&lt; ActiveRecord::Base. It means our model inherit the code from ActiveRecord::Base. In base.rb we put instance method in persistence.rb and put class method in method.rb so we use include and extend methods.</p><p>method.rb</p><pre>module ActiveRecord<br>  module Method<br>    #0<br>    def establish_connection(option)<br>      case option[:adapter]<br>      when &#39;postgresql&#39;<br>        @@connection = ConnectionAdapter::PostgreSQLAdapter.new(option[:database])<br>      when &#39;sqlite&#39;<br>        #TODO<br>      end<br>    end<br><br>    #0<br>    def connection<br>      @@connection<br>    end<br>  end<br>end</pre><blockquote>The methods we define in method.rb is the class method in ActiveRecord::Base.</blockquote><p>In establish_connection method, we will connect ActiveRecord::Base to the database. Use option[:adapter] to determine which kind of database we used and use option[:database] to choose which database we used. We will use postgresql and my_db database in our example.</p><p>The other interesting thing is we use @@connection as class variable. The reason is we use class variable to inherit variable from ActiveRecord::Base and use it in User class.</p><p>connection_adapter.rb</p><pre>module ActiveRecord<br>  module ConnectionAdapter<br>    class PostgreSQLAdapter<br>      def initialize(dbname)<br>        require &#39;pg&#39;<br>        @db = PG.connect(dbname: dbname)<br>      end<br>      <br>      def execute(sql)<br>        @db.exec(sql)<br>      end<br>    end<br>  end<br>end</pre><p>In Rails we support several kinds of databases. To let ActiveRecord support these and not waste the memory we use ConnectionAdapter to determine which kind of database we use and require it. For example, I require pg in PostgreSQLAdapter.</p><p>persistence.rb</p><pre>module ActiveRecord<br>  module Persistence<br>  end<br>end</pre><blockquote>In step0 we can write persistence.rb just like this.</blockquote><h4>Step1: Pass attributes test</h4><p>activerecord_0216002_spec.rb</p><pre>  it &#39;1 test model with attributes&#39; do<br>    user = User.new(name: &#39;Bob&#39;, phone: &#39;0932445631&#39;, age: 12)<br>    expect(user.name).to eq(&#39;Bob&#39;)<br>    expect(user.phone).to eq(&#39;0932445631&#39;)<br>    expect(user.age).to eq(12)<br>  end</pre><p>To pass attributes test, I want a model can use new method to create instance. Instance should have attributes such as name, phone or other data fields.</p><p>persistence.rb</p><pre>    #1<br>    def initialize(attributes = {})<br>      self.class.set_column_name_to_method_attribute<br>      @attributes = attributes<br>    end</pre><p>We add the initialize method in persistence.rb. It means we let ActiveRecord::Base has an instance method initialize. In ruby, we will use Abc.new to new an object. It means we will define an instance method initialize in Abc class not class method new.</p><p>I use @attributes to record the attributes we initialized. The set_column_name_to_method_attribute is a class method to dynamically define attribute method. Because it is a class method, I define it in method.rb file.</p><blockquote>attribute method is like user.phone, user.name</blockquote><p>method.rb</p><pre>    #1<br>    def set_column_name_to_method_attribute<br>      columns = self.connection.execute(&quot;SELECT column_name FROM information_schema.columns <br>        WHERE table_name= &#39;#{self.table_name}&#39;&quot;).map{|m|  m[&quot;column_name&quot;]}<br>      columns.each{ |e| define_method_attribute(e) }<br>    end<br>   <br>    #1<br>    def define_method_attribute(name)<br>      define_method name do<br>        @attributes[name.to_sym] || @attributes[&quot;#{name}&quot;]<br>      end<br><br>      define_method &quot;#{name}=&quot; do |value|<br>        @attributes[name.to_sym] = value<br>      end<br>    end<br><br>    #1<br>    def table_name<br>      name.downcase + &quot;s&quot;<br>    end</pre><p>In set_column_name_to_method_attribute method, we use columns to store the data fields of table from database. For example, from users table we can find [&quot;id&quot;, &quot;name&quot;, &quot;phone&quot;, &quot;age&quot;] data fields. After getting the columns, we use define_method_attribute to dynamically define the attribute methods like id, name and phone.</p><p>Besides define_method method, is there any other way to dynamically define method?</p><blockquote>In addition to define_method, we also can use class_eval to dynamically define method. But the performance of define_method is better than class_eval. After all, the only purpose for define_method is to dynamically define method. The function of class_eval is to create instance method in class scope. More informations aboutdefine_method and class_eval click <a href="https://tenderlovemaking.com/2013/03/03/dynamic_method_definitions.html">here</a>.</blockquote><h4>Step2: Pass save test</h4><p>activerecord_0216002_spec.rb</p><pre>  it &#39;2 test model save record&#39; do<br>    user = User.new(name: &#39;Bob&#39;)<br>    expect{user.save}.to change{User.all.count}.by(1)<br>    expect{user.save}.to change{User.all.count}.by(0)<br>  end<br><br>  it &#39;2 test model save with value&#39; do<br>    User.new(name: &#39;Peter&#39;).save<br>    expect(User.last.name).to eq(&#39;Peter&#39;)<br>  end</pre><p>In the first test, we will test the number increment of User instance when the ruby object calls the save at first time. The second test is to test we save the attribute in database and access it after we saved.</p><p>There are two parts of code in step2. One is to save data, another one is to access data.</p><p>persistence.rb</p><pre>module ActiveRecord<br>  module Persistence<br>    #1<br>    def initialize(attributes = {})<br>      self.class.set_column_name_to_method_attribute<br>      @attributes = attributes<br>      @new_record = true<br>    end<br>    <br>    #2<br>    def new_record?<br>      @new_record<br>    end<br><br>    #2<br>    def save<br>      if new_record?<br>        self.class.connection.execute(&quot;INSERT INTO #{self.class.table_name} <br>        (#{@attributes.keys.join(&#39;,&#39;)}) VALUES (#{&quot;&#39;&quot;+@attributes.values.join(&quot;&#39;, &#39;&quot;)+&quot;&#39;&quot;})&quot;) <br>        @new_record = false<br>        true<br>      else<br>        false<br>      end<br>    end<br>  end<br>end</pre><p>The code in persistence is to save the data into database. Using @new_record to identify whether or not the record has been saved.</p><p>In save method we will use connection method to insert SQL into database. We will use .join(&#39;,&#39;) to convert the original data (@attributes.keys, @attributes.values) into the SQL format. Following is the format translation by join method.</p><blockquote>[:name, :phone, :age] =&gt; “name, phone, age”</blockquote><blockquote>[“Ancestor”, “0932445631”, 12] =&gt; “‘Ancestor’, ‘0932445631’, ‘12’”</blockquote><p>method.rb</p><pre>    #2<br>    def all<br>      Relation.new(self).records<br>    end<br><br>    #2<br>    def last<br>      all.last<br>    end<br><br>    #2<br>    def find_by_sql(sql)<br>      connection.execute(sql).map do |attributes|<br>        new(attributes)<br>      end<br>    end</pre><p>relation.rb</p><pre>module ActiveRecord<br>  class Relation<br>    #2<br>    def initialize(klass)<br>      @klass = klass<br>    end<br><br>    #2<br>    def to_sql<br>      &quot;SELECT * FROM #{@klass.table_name}&quot;<br>    end<br><br>    #2<br>    def records<br>      @records ||= @klass.find_by_sql(to_sql)<br>    end<br>  end<br>end</pre><p>After data was saved, we will go through the data accessing part.</p><p>You will find that we use Relation class to handle access data part. You may wonder why I put so much effort making this class? Do you remember what will return when we call where or all in Rails environment? It isn&#39;t array. It returns something like XX_model::ActiveRecord_Relation. Now, in preparation for step 4 we will make a Relation class to do this.</p><p>In all method of method.rb file, we put User class as a parameter of Relation.new() to create a Relation of User object. The most important method in this Relation is records method. It calls find_by_sql to return an array of User instances.</p><p>To make it simple, the return value of all method is as same as records method. It means the code like User.all will directly return an array. It is different from the real Rails Active Record.</p><h4>Step3: Pass find test</h4><p>activerecord_0216002_spec.rb</p><pre>  before(:all)do<br>    User.new(name: &#39;Ancestor&#39;, phone: &#39;0932445631&#39;, age: 12).save<br>  end</pre><pre>  it &#39;3 test find&#39; do<br>    user = User.find(User.first.id)<br>    expect(user.id).to eq(User.first.id)<br>  end</pre><p>After the third test, I set the before(:all) to make sure there are at least one user instance before each test. Step3 is simpler than Step2. The only thing we need to do is to implement find method.</p><p>method.rb</p><pre>    #3<br>    def first<br>      all.first<br>    end<br><br>    #3<br>    def find(id)<br>      find_by_sql(&quot;SELECT * FROM #{table_name} WHERE id = #{id.to_i}&quot;).first<br>    end</pre><p>This first method is like the last method in step 2. The only different of them is fisrt method use all.first as return value.</p><p>Actually, the implement of find method is like the records method in Relation file. Both of them use find_by_sql to access the database.</p><h4>Step4: Pass where test</h4><p>activerecord_0216002_spec.rb</p><pre>  it &#39;4 test where chain&#39; do<br>    User.new(name: &#39;A&#39;, age: 20, phone: &#39;000&#39;).save<br>    User.new(name: &#39;A&#39;, age: 30, phone: &#39;6666&#39;).save<br>    User.new(name: &#39;B&#39;, age: 30, phone: &#39;000&#39;).save<br>    user = User.where(&quot;name = &#39;A&#39;&quot;).where(&quot;age &gt; 25&quot;).first<br>    expect(user.phone).to eq(&#39;6666&#39;)<br>  end</pre><p>Our where method supports chain feature which means you can use where again and again in one statement such as User.where(..).where(..). At the first glance, where is the class method of User but it is also the instance method of Relation. What is going on? Let&#39;s see it...</p><blockquote>Our where is simple. It can only support the SQL statement such as where(&#39;id = 1&#39;). Our where doesn&#39;t support hash like where(id:1).</blockquote><p>method.rb</p><pre>    #4<br>    def where(*args)<br>      Relation.new(self).where(*args)<br>    end</pre><p>where in method.rb file is a class method of Active Record. The return value of this where method is Relation instance. We also define a where method in Relation class. This is the way we implement chain feature! No matter how many times you call where method in one statement, the return value is always a Relation instance.</p><p>relation.rb</p><pre>module ActiveRecord<br>  class Relation<br>    #2<br>    def initialize(klass)<br>      @klass = klass<br>      @where_values = []<br>    end<br><br>    #2<br>    def to_sql<br>      sql = &quot;SELECT * FROM #{@klass.table_name}&quot;<br>      if @where_values.any?<br>        sql += &quot; WHERE &quot; + @where_values.join(&quot; AND &quot;)<br>      end<br>      sql<br>    end<br><br>    #2<br>    def records<br>      @records ||= @klass.find_by_sql(to_sql)<br>    end<br><br>    #4<br>    def where(condition)<br>      @where_values += [condition]<br>      self<br>    end<br><br>    #4<br>    def first<br>      records.first<br>    end<br>  end<br>end</pre><p>We expand the Relation class by adding @where_values variable. This is a variable to save the SQL information from where. How to save it? Every time we call where will run @where_values += [condition] to save data. At the end we will use records method and it will call to_sql method. Finally, using @where_values.join(&quot; AND &quot;) to make our SQL statement.</p><blockquote>to_sql method translate following statement<br> where(&quot;name = &#39;A&#39;&quot;).where(&quot;age &gt; 25&quot;)<br> into<br> &quot;SELECT * FROM users WHERE name = &#39;A&#39; AND age &gt; 25&quot;</blockquote><p>At the end, run rspec again to see what will happen?</p><pre>Test User<br>  1 test model with attributes<br>  2 test model save record<br>  2 test model save with value<br>  3 test find<br>  4 test where chain<br><br>Finished in 0.46207 seconds (files took 0.52716 seconds to load)<br>5 examples, 0 failures</pre><p>That’s it, we finished 4 steps and 5 tests and made our own Active Record.</p><h4>More information</h4><p>The sample code in my <a href="https://github.com/shes50103/activerecord_0216002">GitHub</a></p><p>If you want to install this gem you can use</p><p>gem install activerecord_0216002</p><p>After install this gem you can use</p><p>gem env</p><p>This command helps you find the gem in your environment. You can find the path from INSTALLATION DIRECTORY:. After installing <br> gem activerecord_0216002, we can require &quot;activerecord_0216002&quot; in our ruby file!</p><h4>Conclusion</h4><p>At my phase of studying Rails, I wonder how magic of Rails make? I dived into Rails source code and found that it is too complicated to understand it. As time goes by, I get familiar with Ruby and find some resources on internet. Finally, I make a simple ActiveRecord myself. Although there are still many places to improve, this process is a good chance for me to study Ruby and Rails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc15140adfe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning How To Deploy Rails]]></title>
            <link>https://medium.com/@johnsonzhan/learning-how-to-deploy-rails-bd5f59359a70?source=rss-41350f042f5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5f59359a70</guid>
            <dc:creator><![CDATA[Johnson Zhan]]></dc:creator>
            <pubDate>Sun, 19 Aug 2018 07:42:10 GMT</pubDate>
            <atom:updated>2018-08-20T09:59:13.633Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T4yPqEF7Pb4qIqlCGc3AQ.jpeg" /></figure><p>If you are studying in Rails deployment, you must heard about the tool like Nginx, Passenger, Capistrano! In this article, I will give you a brief introduction of these tools and the common features of them!</p><p>How is the way deploy like? Maybe is like the following picture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g6sdSzzqKeTApZP-.png" /></figure><p>Remote server is like GCP, AWS or DigitalOcean. Git repositories is a place to put your code, e.g., GitHub, GitLab and Bitbucket. The deploy flow is to make remote server get the code from git repositories and build the project to provide services. We need to install Passenger and Nginx on our remote server, using Capistrano to supports the scripting and execution of arbitrary tasks.</p><h4>Category</h4><ul><li>Nginx &amp; Passenger</li><li>Why Nginx with Passenger ?</li><li>Advantage of Passenger ?</li><li>Commond of Passenger</li><li>Nginx configuration file</li><li>Setting your Nginx</li><li>Capistrano</li><li>Capistrano features</li><li>Capistrano structure</li><li>Capistrano configuration file</li><li>Commond of Capistrano</li><li>Conclusion</li></ul><h4>Nginx &amp; Passenger</h4><p>Nginx is a Web Server. It manage the http request and return http response. Nginx dosen’t know how to read ruby, we used to set up Nginx with Passenger which is an App Server to manage the number of web application processes.</p><blockquote>In the following article I will use these three terms<br> Web Server is Nginx<br> App Server is Passenger<br> Web Application is Rails App</blockquote><h4>Why Nginx with Passenger ?</h4><p>This is one of the part hard to understand. In my original imagination, the structure is web application with some service or software which handle the job my web application dosen’t do. Why we need both Passenger and Nginx to complete this work?</p><p>Nginx and Apache are web server which are good at handling http request and static file. Generally, we put the web application or its application server behind a real web server in a reverse proxy setup. This structure make our system more secure and robust.</p><p>Additionally, web server also take care with performance issue. Such as slow client issue, these clients may send http request slowly and response http slowly. Some HTTP server may spend so much time waiting I/O and spend very littile time doing actual work. To solve this problem without reinvent their wheel, the better way is to let web server handle this issue. That is why we need both Nginx and Passenger to build our system!</p><h4>Advantage of Passenger ?</h4><p>Passenger takes care of application spawning, which means we can start server application process depends on situation. Passenger also play a role between web application and web server. It communicate with Nginx and speak with Rails app under rake protocol. On the structure side, Passenger is stable and flexible. Following is Phusion Passenger architecture overview</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*wkq2U23SR-I2cjvF.png" /></figure><p>source：www.phusionpassenger.com</p><p>Passenger consists of multiple components, including Phusion Passenger module which compile with Nginx. These passenger components run on serveral process. Watchdog one of this components which monitoring other components and restart them preventing passenger crash.</p><p>Due to there are several processes running in this system, they need to communicate with each other by some files. We stored these files in a directory call instance directory. In nginx.conf we can set up which folder is instance directory. The Passenger commond such as passenger-status also use instance directory to get the information.</p><blockquote>I used to be unable to run Passenger, and I don’t know the reason.<br> It turns out that the directory instance directory is missing!</blockquote><p><a href="https://www.phusionpassenger.com/documentation/Design%20and%20Architecture.html#_web_server_module">More information about this architecture</a>.</p><h4>Commond of Passenger</h4><p>To use the commond of Passenger, we need to place Passenger’s bin directory under our path. We can find Passenger’s execution file under this bin directory.</p><pre>passenger  passenger-config  passenger-install-apache2-module  passenger-install-nginx-module  passenger-memory-stats  passenger-status</pre><blockquote>These execution files is also the commond available!</blockquote><p>I usually use these two commonds</p><pre># checkout passenger status<br>passenger-status <br><br># restart Rails app by Passenger  <br>passenger-config restart-app</pre><p>Where to set up Passenger configuration file? Remembering there is a Phusion Passenger module which compile with Nginx. By Phusion Passenger module, we can set some Passenger config on Nginx configuration file.</p><h4>Nginx configuration file</h4><p>We will have nginx.conf configuration file after you installed Nginx. We can directly modify this file or set the config like include site-enabled/*.conf; to include other configuration file. In the meantime, we need to create site-enabled directory under the path where you have nginx.conf file.</p><p>If you commond out part of settings in nginx.conf, this file like so:</p><pre># Tips0<br>worker_processes  1;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>    passenger_root /usr/local/passenger/passenger-5.3.3;<br>    passenger_ruby /usr/local/ruby-2.4.3/bin/ruby;<br>    include       mime.types;<br>    default_type  application/octet-stream;<br>    sendfile        on;<br>    keepalive_timeout  65;<br>    <br>    server {<br>        listen       80;<br>        server_name  localhost;<br>        location / {<br>            root   html;<br>            index  index.html index.htm;<br>        }<br>        error_page   500 502 503 504  /50x.html;<br>        location = /50x.html {<br>            root   html;<br>        }<br>    }<br>    <br>    # We add this line manually<br>    include site-enabled/*.conf;<br>}</pre><p>In nginx.conf you will find http { ... } block and there are server{...} blocks inside it. Our include site-enabled/*.conf; is inside http { ... } block and beside server{...} block. We will implement several server{...} block in our configuration file. You can get more information about this structure from <a href="http://nginx.org/en/docs/beginners_guide.html">official documents</a>.</p><blockquote>Tips 0</blockquote><blockquote>Set the number of Nginx worker_processes. Nginx has one master process and several worker processes. Master process can read the configuration and maintain worker processes. Worker process is who really handel http request!</blockquote><h4>Setting your Nginx</h4><p>We can set our configuration file by the following commond</p><pre>$ mkdir site-enabled<br>$ cd site-enabled<br><br># usually we will use domain name as the name of configuration file<br>$ vim xxx.conf</pre><p>Setting xxx.conf like this (# is commond out symbol)</p><pre># set instance directory of Passenger<br>passenger_instance_registry_dir /var/run/passenger-instreg;<br><br># first server block <br>server {<br><br>    # listen on port 80 （ http request ）<br>    listen 80; <br>    <br>    # tips 1 setting server name<br>    server_name dodeploy.tk;<br>    <br>    # tips 2, redirect http request to second server block<br>    return 301 https://dodeploy.tk$request_uri;<br>}<br><br># second server block<br>server {<br><br>    # listen on port 443 （ https request ）<br>    listen       443 ssl;<br>    <br>    server_name dodeploy.tk;<br>    <br>    # SSL certification setting<br>    ssl on;<br>    ssl_certificate      /etc/letsencrypt/live/dodeploy.tk/fullchain.pem;<br>    ssl_certificate_key  /etc/letsencrypt/live/dodeploy.tk/privkey.pem;<br>    <br>    # tips 3<br>    location ~ /.well-known {<br>        allow all;<br>        root /opt/nginx/html;<br>    }<br>    <br>    # set the directory of static file<br>    root /home/deploy/do_deploy.com/current/public;<br>    <br>    # enable Passenger<br>    passenger_enabled on;<br>}</pre><blockquote>Tips 1</blockquote><blockquote>We can set several domain name point to out server. First of all, apply serveral domain name to the server IP. Then we can use several server blocks to listen on each http request with different domain name.</blockquote><blockquote>Tips 2</blockquote><blockquote>In this example, we will redirect http request to https request. To implement this feature we need a least two server block. One listen on port 80 whcih is http request. After receive the http request it will redirect it to https request which will received by the other server block listening on port 443.</blockquote><blockquote>Tips 3</blockquote><blockquote>At the second server block we set the SSL certificate. The purpose of location block is to let the request with ~/.well-known path return the files in opt/nginx/html directory. This is the way to pass Let&#39;s Encript.</blockquote><p>After completing the above settings, use the following commond to check the nginx config file.</p><pre>sudo /opt/nginx/sbin/nginx -t</pre><p>If all the things on the way, use following commond to restart nginx.</p><pre>sudo systemctl restart nginx</pre><h4>Capistrano</h4><h4>Capistrano features</h4><p>Capistrano is a remote server automation tool. Without Capistrano we need to do a lot effort to complete the deploy flow. If wee need deploy mulitple server or the deploy task is more complicated, we will definitely want to ues Capistrano.</p><p>Capistrano support multiple stages. The stage means environment run web application such as production or staging. We only need to define the deploy configuration one time then we can use these settings on every stage.</p><p>Define your deployment once, and then easily parameterize it for multiple stages (environments), e.g. qa, staging, and production. No copy-and-paste necessary: you only need to specify what is different for each stage, like IP addresses.</p><p>Your application may need many different types of servers: a database server, an app server, two web servers, and a job queue work server, for example. Capistrano lets you tag each server with one or more roles, so you can control where to execute what tasks.</p><h4>Capistrano structure</h4><p>Following is Capistrano structure</p><pre>├── current -&gt; /home/deploy/do_deploy.com/releases/20150120114500/<br>├── releases<br>│   ├── 20150080072500<br>│   ├── 20150090083000<br>│   ├── 20150100093500<br>│   ├── 20150110104000<br>│   └── 20150120114500<br>├── repo<br>│   └── &lt;VCS related data&gt;<br>├── revisions.log<br>└── shared<br>    └── &lt;linked_files and linked_dirs&gt;</pre><p>Capistrano will create a project directory after every deployment. The latest code is in latest prodject directory in relaeses folder. The source of current folder is also symlink from the latest prodject directory.</p><p>There are some directory or file we want to share between each releases such as log directory in 20150080072500 and 20150090083000 release. There are also some sensitive file like database.yml or settings.yml whcih isn&#39;t in version control we will put it in shared folder. How to put them into shared folder? It depends on the setting in Capistrano.</p><h4>Capistrano configuration file</h4><p>The configuration file of Capistrano</p><pre>├── Capfile<br>├── config<br>│   ├── deploy<br>│   │   ├── production.rb<br>│   │   └── staging.rb<br>│   └── deploy.rb<br>└── lib<br>    └── capistrano<br>            └── tasks</pre><blockquote>In this part I will introduce these files Capfile、deploy.rb、prdouction.rb</blockquote><p>You can define your Capistrano by add the setting on Capfile. The setting include which commond you can use and what happen after you execute the commond.</p><p>A new Capfile after removing the code which is commented out.</p><pre># Load DSL and set up stages<br>require &quot;capistrano/setup&quot;<br><br># Include default deployment tasks<br>require &quot;capistrano/deploy&quot;<br><br>require &quot;capistrano/scm/git&quot;<br>install_plugin Capistrano::SCM::Git<br><br># require &quot;capistrano/bundler&quot;<br># require &quot;capistrano/rails/assets&quot;<br># require &quot;capistrano/rails/migrations&quot;<br># require &quot;capistrano/passenger&quot;<br><br># Load custom tasks from `lib/capistrano/tasks` if you have any defined<br>Dir.glob(&quot;lib/capistrano/tasks/*.rake&quot;).each { |r| import r }</pre><p>To deploy Rails App and smooth the deploy process, I will add following lines in Capfile.</p><pre>require &quot;capistrano/bundler&quot;<br>require &quot;capistrano/rails/assets&quot;<br>require &quot;capistrano/rails/migrations&quot;<br>require &quot;capistrano/passenger&quot;<br>require &#39;capistrano/upload-config&#39;</pre><p>Above settings is for Rails deployment. What is the actual functionality of these settings? We can find the difference when we run cap production deploy commond. More information will introduced later.</p><p>Configuration in Nginx can be either global or specific to your stage. The stage is the environment run the web application such as staging or production. The configuration for all the stage is global such as deploy.rb. The file under config/deploy/ directory is the specific configuration file.</p><p>config/deploy.rb</p><blockquote>global setting</blockquote><pre>lock &quot;~&gt; 3.10.1&quot;<br><br># set project name<br>set :application, &quot;do_deploy&quot;<br><br># set the url link of git repository<br>set :repo_url, &quot;git@github.com:shes50103/do_deploy.git&quot;<br><br># the files in shared folder and not in version control<br>append :linked_files, &quot;config/database.yml&quot;, &quot;config/secrets.yml&quot;, &quot;config/settings.yml&quot;<br><br># the directories in shared folder and shared by each release<br>append :linked_dirs, &quot;log&quot;, &quot;tmp/pids&quot;, &quot;tmp/cache&quot;, &quot;tmp/sockets&quot;, &quot;public/system&quot;</pre><p>config/deploy/production.rb</p><blockquote>stage specific setting</blockquote><pre># set the deployment environment of Rails<br>set :rails_env, :production<br><br># set the branch to deploy<br>set :branch, &#39;master&#39;<br><br># set the path to deploy project<br>set :deploy_to, &#39;/home/deploy/do_deploy.com&#39;<br><br># find information from following explanation<br>role :web, %w{deploy@178.128.xxx.xxx}<br>role :db, %w{deploy@178.128.xxx.xxx}</pre><blockquote>Although it is not a good idea, we can set all the configuration in config/deploy/production.rb file. It still work but the problem is if you want to set another stage such as staging. You need to set all your configuration again.</blockquote><p>During deploy flow, we will ssh from localhost to remote server. To use ssh we need remote server IP and the account. I will use the account deploy to ssh to remote server which means there are also a user named deploy in remote server. At the same time, we need to have ssh public key in deploy&#39;s ~/.ssh/authorized_keys file.</p><p>Besides, when I logging as deploy user I still need to ssh from remote server to repository. I also need to set the deploy ssh public key to git repository. Remember server roles which is one of the feature of Capistrano. The role :web and role :db is the server roles we have mentioned.</p><p>Opps!? Do we need to set more configuration? There are a lot of default settings in Capistrano like</p><pre># the maximum number of directories in release folder is five<br>set :keep_releases, 5<br><br># default version control system is Git<br>set :scm, :git</pre><p>Cause there are a lot of default values we can just set the configuration we want to modify. More information on official <a href="https://capistranorb.com/documentation/getting-started/configuration/">document</a>.</p><h4>Commond of Capistrano</h4><p>After set the configuration. We need to type commond to do something. How do I know which commond I can use? You can checkout from the following commond.</p><pre>bundle exec cap -T</pre><p>You can list the commond which is available in the Capistrano. The commonds Capistrano provide depends on what you require in Capfile. Try to comment out part of require code in Capfile. You will find out the number of commonds you can use is decreased.</p><pre>bundle exec cap production config:pull<br>bundle exec cap production config:push</pre><p>Before use these commonds, you need to install gem &#39;capistrano-upload-config&#39; and add require &#39;capistrano/upload-config&#39; in Capfile. These two commonds help you push and pull the linked_files in remote server.</p><pre>bundle exec cap production deploy:check</pre><p>This commond help us check the project directory, linked_dirs and linked_files. If there are something we don&#39;t have, Capistrano help us to create the corresponding directory. Before a new project deployment, we will use this commond to create shared directory. Then use cap production config:push to push the config file.</p><p>The next one is the commond of deployment!</p><pre>bundle exec cap production deploy</pre><p>What can this commond do? It depends on the content of Capfile. If there are only the following two lines in Capfile</p><pre>require &quot;capistrano/setup&quot;<br>require &quot;capistrano/deploy&quot;</pre><p>It will execute following task when you run deploy commond</p><pre>git:wrapper<br>git:check<br>deploy:check:directories<br>deploy:check:linked_dirs<br>deploy:check:make_linked_dirs<br>git:clone<br>git:update<br>git:create_release<br>deploy:set_current_revision<br>deploy:symlink:linked_files<br>deploy:symlink:linked_dirs<br>deploy:symlink:release<br>deploy:cleanup<br>deploy:log_revision</pre><p>To deploy Rails projecy we need to add more settings in Capfile</p><pre>require &quot;capistrano/bundler&quot;<br>require &quot;capistrano/rails/assets&quot;<br>require &quot;capistrano/rails/migrations&quot;</pre><p>Then you can find more step when you run deploy commond</p><pre>bundler:install<br>deploy:assets:precompile<br>deploy:assets:backup_manifest<br>deploy:migrate<br>deploy:migrating</pre><blockquote>These five tasks will run between deploy:symlink:linked_dirs and deploy:symlink:release</blockquote><p>There are two common mistakes when I use Capistrano. First is some of tasks will only execute under specific role. Another mistakes is during some installation process we need to specific the correct path or the error will happen. More information about deploy flow <a href="https://capistranorb.com/documentation/getting-started/flow/">click here</a></p><h4>Conclusion</h4><p>Although I already work through the hole process of deployment. I still not really know how is the deployment work. Sometime I find the way to solve problem but I don’t know the principle behind my way. This article is a chance for me to study more about deployment and master my skill.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5f59359a70" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>