<?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"><channel><title><![CDATA[Cloud Chronicles with Melvin - a DevOps Blog]]></title><description><![CDATA[I am currently working as a Cloud Consultant. 3 years experience with AWS and Docker. 9 years of total IT experience in the Linux, Networking, and Data Visualization domains.]]></description><link>https://blog.melvincv.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 11 Nov 2026 00:51:41 GMT</lastBuildDate><atom:link href="https://blog.melvincv.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[I quit DevOps for good.]]></title><description><![CDATA[Hi readers, There are times when we make huge decisions in our lives. These may not be easy to make due to several reasons. Like the decision I made to…]]></description><link>https://blog.melvincv.com/i-quit-devops-for-good</link><guid isPermaLink="true">https://blog.melvincv.com/i-quit-devops-for-good</guid><category><![CDATA[quit]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Tue, 11 Jun 2024 17:14:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1718125965871/f8cc4acf-0c64-4361-a5d4-d600dd92ea9c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi readers,</p>
<p>There are times when we make huge decisions in our lives. These may not be easy to make due to several reasons. Like the decision I made to quit DevOps completely.</p>
<p>You may feel that I quit suddenly, but I took this decision years ago.</p>
<p>It started in 2020 during the pandemic. I decided to take a Simplilearn course that promised placement support. But they just left us at the mercy of another company called Hirist. It was exactly like being pushed to a job platform after completing the course! We students were left high and dry and were fuming at Simplilearn. We students then formed a Whatsapp group and started self-learning. The group still exists today.</p>
<p>I soon realized that the amount of stuff to learn was way too much. There are several categories with skills under them - each skill is a separate course! Also, I had preferences and dislikes for some technologies. I liked AWS, Docker, and Kubernetes and disliked Ansible, Terraform, and Python. From the dislike list, I found that I had an aversion to coding and scripting.</p>
<p>I joined Internet Leads Training (Kochi) in 2021. The course went well but without placement. My job hunt ended with a job in the twenty-twenty party.</p>
<p>But something was nagging me - the pain of leaving a field that had been my passion since the beginning of my working life. IT Ops. It made me come back to the DevOps field and land a few gigs as a freelancer.</p>
<p>After the contracts were over, I hustled through the pain and made it as a DevOps Engineer in TokenMetrics. This went on for 6 months till they gave me a huge Cloud migration project - from AWS to GCP using Cloud Buckets, CDN, Load Balancers, Kubernetes (GKE), GitHub Actions, and Argo CD. And I had to integrate everything within a few weeks.</p>
<p>I did not know GCP and was scolded for spending time "learning" it. I deployed their backend on GKE but was getting errors that I could not troubleshoot. Also, I did not know how to proceed with the project. The lack of cooperation from the devs was a significant roadblock. It was foolish to continue with the project without being able to draw an architecture diagram! That's when I put in my papers. I value work-life balance and sustainable employment over all else.</p>
<p>I went back to self-learning and working as a freelancer. Joined several Discord servers. Did community projects successfully and posted them to my blog. Attended community days of AWS and GCP. But the job market became bad to worse (2024). Realised that most companies are going to move to platform engineering where I do not have any role as a non-developer. I could not land a job, no matter what I did. I revamped my resume style and content. I kept learning under a mentor and doing several projects - but to no avail.</p>
<p>I finally decided to quit DevOps for good after seeing a LinkedIn post that said "DevOps is not for those who don't want to code". No turning back. As of yesterday, I paid the course fee and attended the first class of a renowned Digital Marketing institute in Kochi, Kerala. It is a great experience; to attend their live classes.</p>
]]></content:encoded></item><item><title><![CDATA[CI/CD with Github Actions, Sonarqube and Ansible]]></title><description><![CDATA[Target the code at: Switch to main-v2 branch. Build the code using GitHub Actions. Deploy the code on two AWS EC2 servers. (independently)]]></description><link>https://blog.melvincv.com/cicd-with-github-actions-sonarqube-and-ansible</link><guid isPermaLink="true">https://blog.melvincv.com/cicd-with-github-actions-sonarqube-and-ansible</guid><category><![CDATA[GitHub]]></category><category><![CDATA[github-actions]]></category><category><![CDATA[sonarqube]]></category><category><![CDATA[ansible]]></category><category><![CDATA[ansible-playbook]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Mon, 29 Apr 2024 06:44:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714373031075/957a66a8-bcac-4b63-9fa8-0d464be50408.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-objectives"><strong>Objectives</strong></h1>
<ul>
<li><p>Target the code at: <a target="_blank" href="https://github.com/melvincv/java-basic-practice-app">https://github.com/melvincv/java-basic-practice-app</a></p>
</li>
<li><p>Switch to main-v2 branch.</p>
</li>
<li><p>Build the code using GitHub Actions.</p>
</li>
<li><p>Deploy the code on two AWS EC2 servers. (independently)</p>
<ul>
<li><p>Implement approval process for deployment on EC2 servers.</p>
</li>
<li><p>Once the application is stable, try implementing the blue-green.</p>
<ul>
<li><p>Make a change in the codebase and deploy the updated code to ONLY one of the EC2 instances.</p>
</li>
<li><p>Upon deployment, your load balancer should serve from both the EC2 instances and show your updated page when refreshed (randomly)</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<hr />
<h1 id="heading-architecture"><strong>Architecture</strong></h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714368624336/759fd6e0-0f19-49e5-a1a4-71f87b17db48.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-workflow"><strong>Workflow</strong></h1>
<p>Complete Github Workflow: <code>.github/workflows/main-pipeline.yml</code></p>
<p><a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/blob/main-v2/.github/workflows/main-pipeline.yml">https://github.com/melvincv/java-basic-practice-app/blob/main-v2/.github/workflows/main-pipeline.yml</a></p>
<h2 id="heading-jobs">Jobs</h2>
<ol>
<li><strong>build job</strong></li>
</ol>
<ul>
<li><p>set up JDK 8 Temurin</p>
</li>
<li><p>build using maven</p>
</li>
<li><p>cache dependencies using the same action</p>
</li>
<li><p>upload WAR file as an artifact</p>
</li>
</ul>
<ol start="2">
<li><strong>code-quality job</strong></li>
</ol>
<ul>
<li><p>set up JDK 11 Temurin</p>
</li>
<li><p>cache sonarqube packages</p>
</li>
<li><p>build and analyze using Maven and sonar-maven-plugin</p>
</li>
</ul>
<ol start="3">
<li><strong>test job</strong></li>
</ol>
<ul>
<li><p>runs maven test</p>
</li>
<li><p>uses JDK 8</p>
</li>
<li><p>requires build and code-quality jobs</p>
</li>
</ul>
<ol start="4">
<li><strong>deploy-a</strong> job</li>
</ol>
<ul>
<li><p>is triggered on the main-v2 branch only + manual input</p>
</li>
<li><p>is part of the production  environment</p>
</li>
<li><p>requires the test job</p>
</li>
<li><p>downloads the artifact uploaded by the build job</p>
</li>
<li><p>renames WAR file to ROOT.war</p>
</li>
<li><p>scp action copies it to /tmp</p>
</li>
<li><p>ssh action deploys it to the tomcat webapps dir</p>
</li>
</ul>
<ol start="5">
<li><strong>deploy-b job</strong></li>
</ol>
<ul>
<li>similar to deploy-a</li>
</ul>
<h1 id="heading-sonarqube-setup"><strong>Sonarqube Setup</strong></h1>
<p>Start an EC2 instance with the following parameters:</p>
<ul>
<li><p>name: sonarqube</p>
</li>
<li><p>ami: Ubuntu 22.04 LTS 64 bit</p>
</li>
<li><p>type: t3.medium</p>
</li>
<li><p>security group: open ports 80, 443, 22</p>
</li>
<li><p>spot instance: true</p>
</li>
<li><p>user data: (check and modify shell script variables first)</p>
</li>
<li><p><a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/prereq.sh">https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/prereq.sh</a></p>
<p>  The script configures kernel settings, installs Docker and Caddy reverse proxy.</p>
</li>
</ul>
<p>Be sure to set the DNS A record to the IP address of your Sonarqube instance asap.</p>
<p>SSH to the sonarqube instance</p>
<p>Check for instance init progress</p>
<pre><code class="lang-bash">tail -f /var/<span class="hljs-built_in">log</span>/cloud-init-output.log
Cloud-init v. 23.4.4-0ubuntu0~22.04.1 finished at Sat, 20 Apr 2024 09:33:31
</code></pre>
<p>and lookup your domain name. Confirm that it is pointing to your instance before starting the Caddy service.</p>
<pre><code class="lang-bash">nslookup jenkins.aws.melvincv.com
sudo systemctl start caddy
sudo systemctl status caddy
</code></pre>
<p>Check for the certificate issue in the logs of the status command.</p>
<p>But Sonarqube is not ready yet and you will get an HTTP error 502 (Bad gateway). This is because the upstream server is not available.</p>
<h2 id="heading-install-sonarqube-using-docker-compose"><strong>Install Sonarqube using Docker Compose</strong></h2>
<p>Create a folder for the Docker files</p>
<pre><code class="lang-bash">mkdir sonar; <span class="hljs-built_in">cd</span> sonar
</code></pre>
<p>Create a .env file with a random, strong PostgreSQL Password.</p>
<pre><code class="lang-bash">cat &gt; .env
POSTGRES_PASSWORD=xxxxxxxxxxxxxxxxxxxx
</code></pre>
<p>Create a compose.yml file</p>
<pre><code class="lang-bash">cat &gt; compose.yml
</code></pre>
<p>My compose file: <a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/compose.yml">https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/compose.yml</a></p>
<p>Start Sonarqube using Compose:</p>
<pre><code class="lang-bash">docker compose pull
docker compose up -d
</code></pre>
<p>The Compose file starts 3 containers:</p>
<ul>
<li><p>sonarqube lts version</p>
</li>
<li><p>postgres 12</p>
</li>
<li><p>adminer (optional, for DB management)</p>
</li>
</ul>
<pre><code class="lang-bash">$ docker compose ps
NAME                IMAGE                     COMMAND                  SERVICE     CREATED              STATUS              PORTS
sonar-adminer-1     adminer                   <span class="hljs-string">"entrypoint.sh php -..."</span>   adminer     About a minute ago   Up About a minute   0.0.0.0:10000-&gt;8080/tcp, :::10000-&gt;8080/tcp
sonar-db-1          postgres:12               <span class="hljs-string">"docker-entrypoint.s..."</span>   db          About a minute ago   Up About a minute   5432/tcp
sonar-sonarqube-1   sonarqube:lts-community   <span class="hljs-string">"/opt/sonarqube/dock..."</span>   sonarqube   About a minute ago   Up About a minute   0.0.0.0:9000-&gt;9000/tcp, :::9000-&gt;9000/tcp
</code></pre>
<p>Wait for a minute or two...</p>
<p>... and Sonarqube is ready</p>
<p>Eg: <a target="_blank" href="https://sonar.aws.melvincv.com/">https://sonar.aws.melvincv.com/</a></p>
<p>Login with the default credentials and change your password asap.</p>
<p>user: admin</p>
<p>pass: admin</p>
<h3 id="heading-create-a-project"><strong>Create a Project</strong></h3>
<p>Sonarqube &gt; Projects &gt; Manually</p>
<p>Project display name = Java Practice App v2</p>
<p>Project key = Java-Practice-App-v2</p>
<p>Main branch name = main-v2</p>
<p><img src="https://lh7-us.googleusercontent.com/VOMnXCb_wOMXukk9-P4mmeHmfbbhrnOrrfKxkvIvmI2L_Y2IWaaIoyT02__9rlxzJHZvp0xLU4JAQn4I2uMHQ1OzxzkTv8uDimQCn2vRwZrHUxb8CqFOrQQwyG5MWZGMKa8VMNchH_ItBzkvF4_1JpY" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/l7ItM1kxvZHsctxc73j-BWsTrEC0avZ01YJkc0BhG67QUkSv1XkuwYiPg0oCY01fSIj8N3InTlJNgcJW4QFTnwl82LhrATtaaLVsrIwcPiY1S1zxPTKEJztuSKDMzqes1o139qYsxNW0a8CvdB-1peI" alt /></p>
<p>Follow the given instructions:</p>
<ol>
<li><p>Create 2 GitHub Repo Secrets- SONAR_TOKEN and SONAR_HOST_URL</p>
<p> <img src="https://lh7-us.googleusercontent.com/lPLypUt0zHNkBlP7obNlCLM24kHBhaj-4fFsrECp8PzzQx1SPeDYmh5sWHyPdq3D4iQcQP-sWlp_F1vP3kNvkwOy69GYT9nohyG3qxlm_P2MhuP6tOgG7Vim0RXqKJv7jpb1j7WULvS-hk5erLnG2P4" alt /></p>
</li>
</ol>
<p>Update workflow. Sample code will be shown. (already updated)</p>
<h1 id="heading-cd-target-servers">CD Target Servers</h1>
<p>Start 2 target ec2 instance - server-a and server-b</p>
<ul>
<li><p>ami: Ubuntu 22.04 LTS 64 bit</p>
</li>
<li><p>type: t3.micro</p>
</li>
<li><p>security group: open ports 8080, 22</p>
</li>
<li><p>spot instance: true</p>
</li>
</ul>
<h2 id="heading-ansible-playbook"><strong>Ansible Playbook</strong></h2>
<p>Write and execute an Ansible playbook to install Tomcat 9 on the Target servers.</p>
<p>Code: <a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/tree/main-v2/ansible">https://github.com/melvincv/java-basic-practice-app/tree/main-v2/ansible</a></p>
<p>Test connectivity to the instances using the ping module:</p>
<p><img src="https://lh7-us.googleusercontent.com/1kaoxl3TVq89CtyFmK3KPe3hK4zEcV7wSvAmR1qw2uwbOiiaNTxtkcYd3LsesF2c-3auMfYsNlpVTZUxpzhS6l7zm7ciguiRJyoSJQQCj7BJdhftgvE2sDo7-8sa8EwzDWwjCQ0A15vTyagYvboqMWs" alt /></p>
<p>Run the playbook:</p>
<p><img src="https://lh7-us.googleusercontent.com/0TDPNv5T7ofRaHukRsayPeczgll2YfBz0UiOQXYLtwsA7VEoYqx4k4myMvzdN-aNfoVg7zWgUIjltP6DhZ6Ce71QFKiG323ZYIjFAekUDIKiFoa5LKxVOL1YjHnUBLCghhWB2sE2Ds62CdzY9_t_OLQ" alt /></p>
<h1 id="heading-add-github-variables-and-secrets"><strong>Add Github Variables and Secrets</strong></h1>
<p>Settings &gt; Secrets and Variables &gt; Actions &gt; Variables</p>
<p>Add HOST_A and HOST_B as repo variables. In the value box, add the IP of the target server A / B.</p>
<p><img src="https://lh7-us.googleusercontent.com/Dl2s2A6JHKCQqGDR1EkIxp0Bg9ayLPVYmvvsW9X61MZLkbGMlxkDmsV1wOiOk4_ifL6HSMzg715TKnbC4mnFqgRzhEoX1Bum_n4i5g9nGwXPnha6oXMdviFRMD_ic3t5anPsXLdFT6HLyrMyax_imGU" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/nCoeofCM5Lw8b9r5N5iAdAZ6z78FSXFlKJ6rSNEsa529euWOFAc13dLrRwV93dF4yf4oKDBcrVqO5vCfSMwe-lVWmL68lokXCXkeX9PjLbofUewpqsGRoVlI0_rVqNmItMJGbyGT16m30seuYxVx9j4" alt /></p>
<p>Settings &gt; Secrets and Variables &gt; Actions &gt; Secrets</p>
<p>Add repo secrets: </p>
<ul>
<li><p>SONAR_HOST_URL  (URL of the Sonarqube instance)</p>
</li>
<li><p>SONAR_TOKEN  (Token obtained from the sonarqube project)</p>
</li>
<li><p>USERNAME  (ubuntu)</p>
</li>
<li><p>PRIVATE_KEY  (private key for the target servers)</p>
</li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/UCxedw8w58PJuFJpnnDzboSAq4V-qYmpJjyUPT4z43vWcYUtd3PpDegqTPEU5XWTuryEQKGpwQ9m1DSNTS6xlWqDwF0Q8s7rpOiXwvzhF6-aZ75LwHzSRrzCcQoWWsYR9d5KvlHJe20EWIGmTcEPmBA" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/nh1B-30-TgzsCa2MegLHlZXwHZHSSw-CPWhbu74-2AG8fKtYZHElmAX8GkKvMT6vnRnUGc0_-VKu0vIuOcyvLkFjdiL7PtXmxAwU0djzx9DevlXNSeRj7yPVCOWo7F9nALrS4_bPOAcGL57johMm5zk" alt /></p>
<p>Add Branch Protection for the main and main-v2 branches</p>
<p><img src="https://lh7-us.googleusercontent.com/6T3svojUDs-nTG1SGvFWL0H1PAKvg39XE1hMoRnCMqmMO-6dWZPkSYfurABs5r5z0OwhQywA7YFkbfgQuldhjBB46eZ8_sNELBgS2vUR_hIwt4MUHilBofdAMIo8tkA1RkJvtdsLPvruTv5zXugxoN8" alt /></p>
<p>Add a production environment for the workflow</p>
<p>Add a reviewer to check and confirm the deployment to production. You may create a new Github account to try this out...</p>
<p><img src="https://lh7-us.googleusercontent.com/PxYrULpwgc9ufjFB1esjFf7h0N_PSsw-sokQQtpULIFWeA9aesvVHgRMr5BiY2b0kHO8xpmBLKmXPRsFK99KhVYPRBazHmHRC9wS_CJQCNZp9tCYnqAEtpHYe-CxNcMlpy4-u7a9cdJMlleLm3rKoho" alt /></p>
<h1 id="heading-approval-process"><strong>Approval Process</strong></h1>
<ol>
<li><p>I make a commit to the devel branch</p>
</li>
<li><p>Raise a PR to the main-v2 branch</p>
</li>
<li><p>PR workflow runs</p>
</li>
<li><p>Reviewer approves the PR and code is merged from <strong>devel</strong> to <strong>main-v2</strong></p>
</li>
<li><p>the workflow runs for main-v2</p>
</li>
</ol>
<p><img src="https://lh7-us.googleusercontent.com/mHiYESJ1ZkWnEzttW36Ttq4-6xyfPWhtQVFWTE7tDHPPspIS5cLLIYl-YeP2puTpnwU1EeSo0qLc_gNMAutelaoaBLO8QoEB9RTYcna6SRGrcAAVfZdZAyqLeoqbnpZ9SgyItoEsXfYBVRujK5RroW4" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/7VWNJ9z7STU3DD2J0LRzlm9RO9UJLBxlRftqHCQwCchEhI_0ceAoO6U-3aC8kLjeYQDaWSh8KQs_olPMAVcQYroQnV32YMfjSU_-1qcEiZo0V7MsqlLEZ6UcwRyfsTLUfqRBjh6GmS-VcKP--Gw89nY" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/gJ04kHFMwpkuo7UlBHI2lDDu-m1JjLQL0EbUTdA-hMKdk5nX28J96Z8V5_sE1RYGA25Mk1bM07tsqrwrQbRQOC0-aBxeApqN0Jc9_5d1grfaOCZiphNGQlDmee8Ti8y-Q9_AQy9c9qoHs82Z1yeJ5tE" alt /></p>
<p>On the reviewer's account, approve the PR:</p>
<p><img src="https://lh7-us.googleusercontent.com/jWV4xPQy6oRaZqgTjWys6orWlWKIwxBSBChYlq6fOyYJIzCDWDFvNa0aj-CerrcwH3WB-O7AE_nGCXE6ZlTu6EEwaE8LKDB5hhf_yaT5n-2mfcZaFEWWN67QeY4HwPelPFAOdmJJ5ulenXo80RJERJ8" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/fwJZ6Uqf4_xdYBa12N8fiRQ0TKaCtF5tBRToYYFeQWp_iuLJnDUW6NiFRtoNiRxq1M3qAAMyUiFCnT6KxugYJeJv4UaoGJvkm7hThN37o14jvE8YPkxuG-pVufeaM5hu5HekRYNDPYlcj8j0SHbaqDw" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/3RKFOh47Y0EeXRiEXReBLlS5pXVzL6miS_WRqZggZWk2N1i0VKURuyFHPRGlICpmbHAU_NxDbQAiOfsD2kppRUlOXimMJjBcQQTl5C2NYbixqqZadFwB-kkL823BQs6Gi7HfrBKU2fAytenAVWZEZ6s" alt /></p>
<p>Production environment deployment approval prompt will be displayed when the workflow reaches the deploy jobs:</p>
<p><img src="https://lh7-us.googleusercontent.com/FwAeD9rlZudMTMvxzfI7Bfy5T4ggJ0Hg7MliThF4kcFV1DB3R7I2u9b0P54SAjZReu6TZVIiqM_ElUF4hpjsNuJIl8ersCKbgL9mSgkuWK8xgOk_hk8K6nn5BB4iPU1p-ZhM-MBXIiD9VDrdAsgmJe0" alt /></p>
<p>The reviewer approves the PR from his account:</p>
<p><img src="https://lh7-us.googleusercontent.com/mnNOuiRhOw2gUB708qGOZVer7dbJrRaZ1OUlhM2sGZWDDjODN33yabxUbE8J5D7u-6A9inaM_yie6_9WS-dsfHqPHn-8ivEJ9Yg-Z5bnogbxXwdqiSsEfwidB2cwgIk1-TyN0qAuN-FCgxIN-BgHnUY" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/hTaohwYOUe8d7M7Obg8DsEMPeZo0mTcQYGm4LyOgImsifgo5YMKz05jp80d4J2EPMTTBqBmmTM0GYB1mJSMPBKGuEsGktSwdpPuOBnh4N86odoQ1PJffdazO2Zw5NJoxIB_3dJjDoHcDKReUWV26VWY" alt /></p>
<p>The deploy jobs start running and the app is deployed to production.</p>
<h1 id="heading-aws-setup"><strong>AWS Setup</strong></h1>
<h2 id="heading-instances"><strong>Instances</strong></h2>
<p>These instances have already been set up:</p>
<p><img src="https://lh7-us.googleusercontent.com/St7hkypjTKg8ohJopwkctovla95tDNoxk4Qv_z4f0jOsNzkcbzW5hgvkoNc3iwUHSE_2jlttvhTFDTrtc3Stq1zBCJLqE-0e85tUYzPHOupP4ispxlIBqJpOJSqHwmHgQT2AoLTp4UqbQKuPn2Gxyd0" alt /></p>
<h2 id="heading-create-a-target-group"><strong>Create a target group</strong></h2>
<p><img src="https://lh7-us.googleusercontent.com/bcVUExsyxqrTcFicAifuM5ZElGF-MmHRBjaptA0m4QE1NoVVlwWqK_Zd0CdNrNj-XGUIrxS6zXDsbTOaYHjv-p_owCVoWzPsyQzcFALxQZUn4W5g1zEOrNZwTTZ7gJ7PY4W4L6bT-vQ9WeQ15YCrRAA" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/818GoRjL0b3299OHKjGnb_eGqa6HG5b_4o3Gig9xd9rG9ao60n5Zp93hpe7x7gAyu_Ad8S2veKyNyY8pvvtZB-HkB61LUaY7i33bV42MPeWoOFc5Yn81dP-JDkqe4XW7ach_08hrks_Z-au5xsdtbi8" alt /></p>
<h2 id="heading-create-app-load-balancer"><strong>Create App Load Balancer</strong></h2>
<p>Name: akhil-p2-alb</p>
<p>Internet facing, IPv4, Select all subnets</p>
<p>Select security group (akhil-project-1-alb-sg)</p>
<p>Add listeners:</p>
<p><img src="https://lh7-us.googleusercontent.com/D16cTfqGfadY1VZ6Roe2d6Pw4sCy-mEOkrt4TiQSyqD9yR9ZvudUXDsq-fX1Q9dAjZ9-TTTrjSoikX_eoABPQ8nAPL77r8YARFY7UNcnLBEeJWwRd5ln599lNSpD2cA-1DWDD2bPJguX2o5o02R1krg" alt /></p>
<p>Selecting the wildcard SSL certificate created in the previous project</p>
<p><img src="https://lh7-us.googleusercontent.com/CkxhuwvBo8oRieapdYvgJkJn7HM4LaggUApxB9rBh70jTeR0-GOUd2C40zuw262dlUTX3knIR6SeZyasPY9_LfZusYyfjDxuH37XbpXDV1ZKPoACVQzrEO18vYcSHrEO8RGQjfOJ0QJM2mfXN2Z1yaI" alt /></p>
<p>Create Load Balancer</p>
<p>DNS Name will be like this: <a target="_blank" href="http://akhil-p2-alb-1468339209.ap-northeast-1.elb.amazonaws.com">akhil-p2-alb-1468339209.ap-northeast-1.elb.amazonaws.com</a></p>
<h3 id="heading-add-alias-record-to-route-53"><strong>Add Alias record to Route 53</strong></h3>
<p><img src="https://lh7-us.googleusercontent.com/A4JhQqyyXGudvt6RBo2qENOArXMji3DBuATO6b05NJ32jNClNkiD6HtLzC2jyAR6WQt7FIruXbKTpAthCY--mecO-d7b8Pd7rzpXjOpS46GkW6N4Mx8kRkq_MC1g64Zz0iCp4-1tY4pBnEcGBJ1kTns" alt /></p>
<h3 id="heading-redirect-http-to-https"><strong>Redirect HTTP to HTTPS</strong></h3>
<p><img src="https://lh7-us.googleusercontent.com/WR7HUdM3Y5dynG_ik7xnXJjhtLi9bNvU76nop5dXB_7xlV8O9wWRkaOvrYDFp3UmPAu1kWsafnNhaym9oOPNDNAX5mMHGDgVBrR-4EEA0IVtsfox01NSoocUTc43w7d0TbnA-tO9SVIGLk4wMGiQbiE" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/ejc8d2-96GZxdZ66ASkbC6WzSSzWRbJvf1BtsKNDjC-SkNtTGLjHdgXP6nHttKAhgneMFP0pM_1Fpin3d1mDvIKon84N8lbD4Cy5z-zfqKZ0hxoI1-1sxEYbTXE2p2FSBySk8M9qXuk_4UDwgIrYQN0" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/QTEEt_e8HGppt1e18DeWWYg-59Q9zOIficqnwj00IUTdDrwX4kr33ul-Dm5kIaLQiTiKGJixPm_4Et9dLSBYMcPJOzdULmpL3NaBKFBQs4gi7xDI_aPKR7ooeRdB92TMpEZKRi4Sp5YRz3px24JrLRI" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/Wnw9cxz6DdScPCurcrZLkNVO1P8oveEnjH6x_nRlWji_qvxSUyp4qfLHDJCpwEUKy3RRqg5VaS05-LtootJLYAu7gc2uZ5bBHnGubxxZjvRqCZv4STg5RKp16YCoXkLFT66bYjbpBGpi6vTIp3TxSDk" alt /></p>
<p><strong>Edit Health check settings</strong></p>
<p>Since the health checks are reporting that the instances are Unhealthy, </p>
<p>To troubleshoot, check the HTTP status code in your browser's dev tools.</p>
<p>It is giving a 302 redirect. So, change the health check path to /login to get a 200 OK.</p>
<p><img src="https://lh7-us.googleusercontent.com/hWmnTtyFIXsxSRtLcd2BCo7PguPot7Z3e0srDxvWDbRVvthmrm1uipIzv4w1O8OBbszOT-hp-EtWq0G6PsCjTf2o8mEKN3-QbQVDO4nYP8EODL54GzZElJdUH6sYR6aQcBTXt20SnvSwbGF2y5mi2GY" alt /></p>
<h1 id="heading-blue-green-deployment"><strong>Blue Green Deployment</strong></h1>
<p>Note: The workflow has to be present in the default branch for Manual triggering to work via workflow_dispatch. I changed the default branch to main-v2 for this project.</p>
<p><img src="https://lh7-us.googleusercontent.com/XUviO_zINwL7wvwxRnG3tKQ1CB8EXeuKGzcvgOHY8vUm0THM-6d9KTlnWEZKlMqGr1MrCnsu1Fr-cyrX2xQwxfyDKJUmj0TD6Zil15dfoZr58pmSxbHbOsAS6K05ViF5aRnFxMsB-kBKULwe0ocvQdw" alt /></p>
<p>Added boolean inputs to the workflow for selective deployment...</p>
<pre><code class="lang-bash">on:
  workflow_dispatch:
    inputs:
      deploy-a:
        <span class="hljs-built_in">type</span>: boolean
        description: <span class="hljs-string">'Deploy to Server A?'</span>
        required: <span class="hljs-literal">true</span>
        default: <span class="hljs-literal">true</span>
      deploy-b:
        <span class="hljs-built_in">type</span>: boolean
        description: <span class="hljs-string">'Deploy to Server B?'</span>
        required: <span class="hljs-literal">true</span>
        default: <span class="hljs-literal">true</span>
</code></pre>
<p>Raised a PR to the main-v2 branch and merged the PR.</p>
<p>Now, there is an option to trigger the workflow manually with the inputs.</p>
<p><img src="https://lh7-us.googleusercontent.com/GMfj_kuxpKJxyndNX1t4FssVw4N1HtsCCpE8TnaUzPt6Wx-qV4IFwo0oXqWSqZpUZKZvXEUVI6RxyOPts_vfP-4i16swl_KXj1S0BE8XWEfxes3o2TNQd8bPgaKtALpjxXxW3vk2vxG3Uu20b4rwdZs" alt /></p>
<p>Check one of the servers (B) &gt; Run</p>
<p>The workflow will run the deploy-b job only:</p>
<p><img src="https://lh7-us.googleusercontent.com/olGudXeP4NJBvMP9736m2oaz1UArtBR31ASG3TRdv_1n6FJ5Yh4mM1-UfNe8kNQqBeQEgyocCXl50PHAhmeziMU5RMHdczmfLyMIAPCIBuuWUDj0JzurT8c8nkCfJ2xbwIW8U4qPTw6ec5nKXe8Xsjk" alt /></p>
<h1 id="heading-results"><strong>Results</strong></h1>
<p>After the Blue/Green deployment, the app is available at the below URL:</p>
<p><a target="_blank" href="https://javaappv2.aws.melvincv.com/login">https://javaappv2.aws.melvincv.com/login</a></p>
<p><img src="https://lh7-us.googleusercontent.com/oDI49BCTVivjcl-vTMiGemc9ANfu2RT2Q66ldT2XvFhr1W7oPJZHdjlWWoE_wRWbSeSH4dYix0AbXgLGr74U9-3rrH5W97pcjMwhh_mbUycHMTeAOPAguxYfG-IY-0SFv6QLsAouTv1xC5W8LwtrZ7o" alt /></p>
]]></content:encoded></item><item><title><![CDATA[Jenkins CI CD Project 1]]></title><description><![CDATA[with Sonarqube, Ansible and Blue / Green deployment]]></description><link>https://blog.melvincv.com/jenkins-ci-cd-project-1</link><guid isPermaLink="true">https://blog.melvincv.com/jenkins-ci-cd-project-1</guid><category><![CDATA[ci-cd]]></category><category><![CDATA[Jenkins]]></category><category><![CDATA[Devops]]></category><category><![CDATA[sonarqube]]></category><category><![CDATA[ansible]]></category><category><![CDATA[Tomcat]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Mon, 22 Apr 2024 09:16:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713776882042/a161f455-35f9-44c4-ae98-74e77f48c59c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713769393330/39023508-9959-4026-bede-7da66f39ee5f.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-objectives">Objectives</h1>
<ul>
<li><p>Build the code using Jenkins</p>
</li>
<li><p>Integrate Sonar</p>
</li>
<li><p>Deploy the generated artifact to two EC2 instances.</p>
</li>
<li><p>The two EC2 instances should have Apache Tomcat installed using Ansible.</p>
</li>
<li><p>Load balance the traffic to two EC2 servers using load balancer.</p>
</li>
<li><p>Once the application is stable, try implementing the blue-green.</p>
<ul>
<li><p>Make a change in the codebase and deploy the updated code to ONLY one of the EC2 instances.</p>
</li>
<li><p>Upon deployment, your load balancer should serve from both the EC2 instances and show your updated page when refreshed (randomly)</p>
</li>
</ul>
</li>
</ul>
<h1 id="heading-github-repo">Github Repo</h1>
<p><a target="_blank" href="https://github.com/melvincv/java-basic-practice-app">https://github.com/melvincv/java-basic-practice-app</a></p>
<h1 id="heading-steps">Steps</h1>
<h2 id="heading-jenkins-setup"><strong>Jenkins Setup</strong></h2>
<p>Start an EC2 instance with the following parameters:</p>
<ul>
<li><p>name: jenkins-aio</p>
</li>
<li><p>ami: Ubuntu 22.04 LTS 64 bit</p>
</li>
<li><p>type: t3.small</p>
</li>
<li><p>security group: open ports 80, 443, 22</p>
</li>
<li><p>spot instance: true</p>
</li>
<li><p>user data: (check and modify shell script variables first)</p>
</li>
<li><p><a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/install-jenkins.sh">https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/install-jenkins.sh</a></p>
</li>
</ul>
<p>The script installs openjdk 17, maven 3.9.6, Jenkins from the official repos, Docker, Ansible and Caddy reverse proxy.</p>
<p>Be sure to set the DNS A record to the IP address of your Jenkins instance asap.</p>
<p>SSH to the jenkins-aio instance, Check for instance init progress</p>
<pre><code class="lang-bash">tail -f /var/<span class="hljs-built_in">log</span>/cloud-init-output.log
Cloud-init v. 23.4.4-0ubuntu0~22.04.1 finished at Sat, 20 Apr 2024 09:33:31
</code></pre>
<p>and lookup your domain name. Confirm that it is pointing to your instance before starting the Caddy service.</p>
<pre><code class="lang-bash">nslookup jenkins.aws.melvincv.com
sudo systemctl start caddy
</code></pre>
<pre><code class="lang-bash">ubuntu@jenkins-aio:~$ sudo systemctl status caddy
● caddy.service - Caddy
     Loaded: loaded (/lib/systemd/system/caddy.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2024-04-19 05:57:00 UTC; 1 day 3h ago

{<span class="hljs-string">"level"</span>:<span class="hljs-string">"info"</span>,<span class="hljs-string">"ts"</span>:1713506223.091408,<span class="hljs-string">"logger"</span>:<span class="hljs-string">"tls.obtain"</span>,<span class="hljs-string">"msg"</span>:<span class="hljs-string">"certificate obtained successfully"</span>,<span class="hljs-string">"identifier"</span>:<span class="hljs-string">"jenkin&gt;</span>
</code></pre>
<p>At this point, Jenkins will be available on your domain with Let's Encrypt SSL.</p>
<p>Eg: <a target="_blank" href="https://jenkins.aws.melvincv.com/">https://jenkins.aws.melvincv.com/</a></p>
<p>Fill in the Admin password:</p>
<pre><code class="lang-bash">sudo cat /var/lib/jenkins/secrets/initialAdminPassword
</code></pre>
<p>Install Suggested Plugins</p>
<p>Create an Admin User and Log In</p>
<h3 id="heading-adding-tools"><strong>Adding Tools</strong></h3>
<p>Now, you may configure the Tools section.</p>
<p>Manage Jenkins &gt; Tools &gt; Add JDK</p>
<p>name: openjdk17</p>
<p>path: /usr/lib/jvm/java-1.17.0-openjdk-amd64</p>
<p>Get the path using this command:</p>
<pre><code class="lang-bash">ubuntu@jenkins-aio:~$ update-java-alternatives --list
java-1.17.0-openjdk-amd64      1711       /usr/lib/jvm/java-1.17.0-openjdk-amd64
</code></pre>
<p><img src="https://lh7-us.googleusercontent.com/WJN4MvZjWXdYJRb90hajxL-2tLBf6AIy-fUh3PnC0aWfcDrpzXm6TiQhVK7FyAJhbQUR3DQ2SauCJVe5B0hWfb8T5OyY3SBUjur9HAtH9uFBOEE0_kFf1j9Ho-53yQyxpITpfPiEwvfKh3_HiacmKZQ" alt /></p>
<p>Manage Jenkins &gt; Tools &gt; Add Maven</p>
<p>name: maven3.9</p>
<p>path: /opt/apache-maven</p>
<p>Get the path using this command: (you get the Java path too)</p>
<pre><code class="lang-bash">ubuntu@jenkins-aio:~$ mvn -v
Apache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae)
Maven home: /opt/apache-maven
Java version: 17.0.10, vendor: Private Build, runtime: /usr/lib/jvm/java-17-openjdk-amd64
</code></pre>
<h3 id="heading-adding-plugins"><strong>Adding Plugins</strong></h3>
<p>Add Plugins to extend the functionality of Jenkins.</p>
<p>Manage Jenkins &gt; Plugins &gt; Available</p>
<ul>
<li><p>sonarqube scanner</p>
</li>
<li><p>ssh agent</p>
</li>
</ul>
<h3 id="heading-create-a-pipeline-job"><strong>Create a Pipeline Job</strong></h3>
<p>Dashboard &gt; New item &gt; give a name &gt; Pipeline</p>
<p><img src="https://lh7-us.googleusercontent.com/YKdEJagXn6SQ8gErmw3CJS4WYb8pejJiAYNaN56Ng8x2MF0YIUuD_eCstMpdwjJr63OX3JbahdNIRJbOhyP0CvaDk9B99yNVxbz4Mwgs0FIhhTZoxuIycj_XJ-79gkdVJr61nIfva8uJ8nHsJJusNx4" alt /></p>
<p>Configure section will be opened.</p>
<p>Pipeline &gt; Pipeline script from SCM &gt; Git &gt; Enter the repo URL</p>
<p>Branch Specifier = */main</p>
<p>Save.</p>
<p><img src="https://lh7-us.googleusercontent.com/yOHZPZpNWIdfIUQ23yLQlmBal_7CpLruVguFDjJyRP3nxgBAAmR_jEJHyw7FElciFQwyGxf09de1Ehnq5M0uIVQ6tdtC0bgxp2drwTgLUZ0QxxTo9OKfpMoRW_f18BfGMhVCn-AbS_p_q_wQRtVV9cI" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/ZjyOEwP1D0mW_kFAe1MkglijpfbqzXMU-UZr76oyAF0vs-Iy6yck0vCSCXBqKhAOnJIYcUZEdUmm2IQ9f3Rn2ei4jkgFv9sbm7Pejvg2enAFyhBUcf25EOvnNFHEdrVZfLyn5N_sxM8utUXnlTXUMkg" alt /></p>
<h2 id="heading-sonarqube-setup"><strong>Sonarqube Setup</strong></h2>
<p>Start an EC2 instance with the following parameters:</p>
<ul>
<li><p>name: sonarqube</p>
</li>
<li><p>ami: Ubuntu 22.04 LTS 64 bit</p>
</li>
<li><p>type: t3.medium</p>
</li>
<li><p>security group: open ports 80, 443, 22</p>
</li>
<li><p>spot instance: true</p>
</li>
<li><p>user data: (check and modify shell script variables first)</p>
</li>
<li><p><a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/prereq.sh">https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/prereq.sh</a></p>
</li>
</ul>
<p>The script configures kernel settings, installs Docker and Caddy reverse proxy.</p>
<p>Be sure to set the DNS A record to the IP address of your Sonarqube instance asap.</p>
<p>SSH to the sonarqube instance, Check for instance init progress</p>
<pre><code class="lang-bash">tail -f /var/<span class="hljs-built_in">log</span>/cloud-init-output.log
Cloud-init v. 23.4.4-0ubuntu0~22.04.1 finished at Sat, 20 Apr 2024 09:33:31
</code></pre>
<p>and lookup your domain name. Confirm that it is pointing to your instance before starting the Caddy service.</p>
<pre><code class="lang-bash">nslookup jenkins.aws.melvincv.com
sudo systemctl start caddy
sudo systemctl status caddy
</code></pre>
<p>Check for the certificate issue, similar to Jenkins.</p>
<p>But Sonarqube is not ready yet and you will get an HTTP error 502 (Bad gateway). This is because the upstream server is not available - the server(s) behind the reverse proxy.</p>
<h3 id="heading-install-sonarqube-using-docker-compose"><strong>Install Sonarqube using Docker Compose</strong></h3>
<p>Create a folder for the Docker files</p>
<pre><code class="lang-bash">mkdir sonar; <span class="hljs-built_in">cd</span> sonar
</code></pre>
<p>Create a .env file with the PostgreSQL Password</p>
<pre><code class="lang-bash">cat &gt; .env
POSTGRES_PASSWORD=xxxxxxxxxxxxxxxxxxxx
</code></pre>
<p>Create a compose.yml file</p>
<p>My compose file: <a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/compose.yml">https://github.com/melvincv/java-basic-practice-app/blob/main/scripts/sonarqube/compose.yml</a></p>
<p>Start Sonarqube using Compose:</p>
<pre><code class="lang-bash">docker compose pull
docker compose up -d
</code></pre>
<p>The Compose file starts 3 containers:</p>
<ul>
<li><p>sonarqube lts version</p>
</li>
<li><p>postgres 12</p>
</li>
<li><p>adminer (optional, for DB management)</p>
</li>
</ul>
<pre><code class="lang-bash">$ docker compose ps
NAME                IMAGE                     COMMAND                  SERVICE     CREATED              STATUS              PORTS
sonar-adminer-1     adminer                   <span class="hljs-string">"entrypoint.sh php -..."</span>   adminer     About a minute ago   Up About a minute   0.0.0.0:10000-&gt;8080/tcp, :::10000-&gt;8080/tcp
sonar-db-1          postgres:12               <span class="hljs-string">"docker-entrypoint.s..."</span>   db          About a minute ago   Up About a minute   5432/tcp
sonar-sonarqube-1   sonarqube:lts-community   <span class="hljs-string">"/opt/sonarqube/dock..."</span>   sonarqube   About a minute ago   Up About a minute   0.0.0.0:9000-&gt;9000/tcp, :::9000-&gt;9000/tcp
</code></pre>
<p>Wait for a minute or two...</p>
<p>... and Sonarqube is ready!</p>
<p>Eg: <a target="_blank" href="https://sonar.aws.melvincv.com/">https://sonar.aws.melvincv.com/</a></p>
<p>Login with the default credentials and change your password ASAP.</p>
<p>user: admin</p>
<p>pass: admin</p>
<h3 id="heading-sonarqube-integration-with-jenkins"><strong>Sonarqube Integration with Jenkins</strong></h3>
<p>A sonarqube token is necessary for Jenkins to authenticate to your sonarqube instance.</p>
<p>In Sonarqube, go to Administrator &gt; My Account &gt; Security &gt; Generate Token</p>
<p><img src="https://lh7-us.googleusercontent.com/InOgREyJSeoZ42YDAksr2dbT1Ug0n9-YVkFn73qbfOKsAJe4diAKB-uGu6GGz1W7WNIHUWE_MqH-HXvUIGw7zoSeUm73Atl8p4ynRH23BKh-DDZe_r1NeuP9P7PPuZXJ7xSDTIgytNQ2bMlGUAwGdcI" alt /></p>
<p>Copy the token and add it as a Jenkins credential of type "Secret Text" with id "sonar-token"</p>
<p><img src="https://lh7-us.googleusercontent.com/gxLmGe2h5SlJ9fqJXi1Rp7RWa7nhGLNG98TZIdIf0I5SHxp2AMOYQ8lPoLy0i4mBLkoQLYx2HDxcXm8pRbVMyjP1BxXMqnG1q_uXIYJnW-sdQy9d82eblC2T0leo25TVfi5ZzEj6tCiNt3r_4raNd64" alt /></p>
<p>Now add a Sonarqube Server.</p>
<p>Manage Jenkins &gt; System &gt; SonarQube servers &gt; SonarQube installations</p>
<ul>
<li><p>name: sonar</p>
</li>
<li><p>server url: <a target="_blank" href="https://sonar.aws.melvincv.com/">https://sonar.aws.melvincv.com/</a></p>
</li>
<li><p>token: sonar-token (select yours)</p>
</li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/nn-0LtTltSFUmc9nxEc8hIvwklcGMJfFwP-47OsNjK2spIsYLr0fqvwqSm4Hioj3VKqLydJxXSox5BZpcM7GIrrTfK2vlKimRh6U-RsFIb2eOn44kQIqeyp8F9taQfk_zDjEjgFo5MO1Krog4DR_LMY" alt /></p>
<p>The connection to Sonarqube is set up. After code scanning and quality gate analysis, Sonarqube needs to contact Jenkins with the stats. For this, you need a Webhook. Add a Webhook pointing to a URL on your Jenkins instance.</p>
<p><img src="https://lh7-us.googleusercontent.com/QSTr2nFS6rRMBO4pKnGj7Sh_CRASVaBYc08rbssSKy2GwWAHx3yB1rkMAmGi2NQnFDb2hTRHoQbFgnWKyXYShuPuc3MwQQ0BY2djfzZ1r2tTpSiY6lmPTFWvAG0jpQyEEWpZA38skLVPKMNyvDu-vsk" alt /></p>
<p>URL would be the IP / Domain of your Jenkins with <code>/sonarqube-webhook/</code></p>
<p>Eg: <a target="_blank" href="https://jenkins.aws.melvincv.com/sonarqube-webhook/">https://jenkins.aws.melvincv.com/sonarqube-webhook/</a></p>
<h2 id="heading-build-the-jenkins-job"><strong>Build the Jenkins Job</strong></h2>
<p>Go to the Jenkins Pipeline and "Build with Parameters". Leave them as is and click Build. The Code Quality and Test stage should pass.</p>
<p><img src="https://lh7-us.googleusercontent.com/T2fmQ_Q46B_mBjAsgrEPkCPjJbDrflRO_lBlQgTj0Jx6CHGwlWIz2pNn9gbS8MvXTSBghBVnwGDc1rT-MJ6ww0DWVGD1MMogqYykOhZD7CuoX1QXLZsPtNmQNhgOWbsLRchFNyNEyXRFckkTPJfan_E" alt /></p>
<p>The "CD to Server" stages will fail as the servers are not ready yet.</p>
<h2 id="heading-start-and-configure-the-cd-servers-using-ansible"><strong>Start and Configure the CD Servers using Ansible</strong></h2>
<p>Start 2 EC2 instances with the following parameters:</p>
<ul>
<li><p>name: cd-target-svrA, cd-target-svrB</p>
</li>
<li><p>ami: Ubuntu 22.04 LTS 64 bit</p>
</li>
<li><p>type: t3.micro</p>
</li>
<li><p>security group: open ports 8080, 22</p>
</li>
<li><p>spot instance: true</p>
</li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/DwLWspItX-Vsg7aVH1nWbwZv3SaV2lN7SyyIkEW0NvWlctet26N-OlsLebIQsaQQ8R4_IZ16QtQJaJneCMo3Yvwz1tG46CKeT8ycpCNs7ijDdbj6Xg01vhLh3rsc5AuKQBoVec61krICZ3kBCqoiNbQ" alt /></p>
<p>Create an inventory file and an Ansible playbook to install Tomcat on both servers.</p>
<p>Refer my Ansible files: <a target="_blank" href="https://github.com/melvincv/java-basic-practice-app/tree/main/ansible">https://github.com/melvincv/java-basic-practice-app/tree/main/ansible</a></p>
<p>Set up an Ansible Controller locally and run ansible ad-hoc command to ping the servers</p>
<pre><code class="lang-bash">ansible all -i inventory.ini -m ping
</code></pre>
<p><img src="https://lh7-us.googleusercontent.com/sCHDPHr6LsHznEOxxZpo8MZs3TjJ24IOA9KcY8ex6zAR7irhhF3Hsckuru7E_ZM9Bk-fH111IDj-0OkLEYhQCe34cet_9TtOGpynThtFGfhheQZqbMbDRqjlWmntuia5pXPsOl_DRaANyVZt5DNzbZ4" alt /></p>
<p>Run the Ansible playbook after you get a successful ping.</p>
<pre><code class="lang-bash">ansible-playbook -i inventory.ini playbook.yml
</code></pre>
<p><img src="https://lh7-us.googleusercontent.com/yMnwVmZ3NNIlsCLJJ1JaLjS3dB7pfNkzhl4tm2S5_hi-2MW2Hn589lYPOyIzVQDPIhH1ABDr4_rf9tRjv_4kFweg3bAXDjJWO2_RXM3PfS0ZMeOZofMAujbu4T6w4d6OBNZnD5N1XPwqUelJDigGqns" alt /></p>
<p>Now you have tomcat running in both instances.</p>
<p>You will be able to access the default page of Tomcat using the IP and Port</p>
<p>Eg: <a target="_blank" href="http://43.206.158.1:8080/">http://43.206.158.1:8080/</a></p>
<h2 id="heading-continuous-deployment-using-jenkins"><strong>Continuous Deployment using Jenkins</strong></h2>
<p>We had installed the SSH Agent plugin earlier.</p>
<p>Now create a Jenkins Credential of type "SSH Username with private key". Jenkins will use this to log in to your target servers.</p>
<p>Set an ID and username and enter the Private Key.</p>
<p><img src="https://lh7-us.googleusercontent.com/GyjP9yELsvmxJHk0Va4VQ7V9ujLGduSWW2qeoAbSDwOyDYRTxx7sQxJfMQNTeSLGea9s7VYFV6wj9sPYeb_i-65GBfM2cAGi4a72BWdiPJnQmRurzbCOJTJwasaAKYUh8NvX3PBzueYefQInJwpU2Z8" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/20ZOgjOAQciiF9hR2nDDuuOTd5jospbqvs-byTM3ZXZeQBckJri8xs4sDca8R_4EKqCcbFxywj_22m0r-BzxSO4A0k7dOkrCgrTzDTpPeX9_BlrlcSJXItc2gGWhi0huXPU7ypWwr4uR10_2BNG2P10" alt /></p>
<p>Modify the Jenkins Pipeline to reflect the new ID</p>
<p>Stages: <strong>CD to Server A</strong> and <strong>CD to Server B</strong></p>
<pre><code class="lang-bash">sshagent(credentials: [<span class="hljs-string">'akhil-p1-ssh-key'</span>])
</code></pre>
<p>Run the Build with Parameters. Jenkins should now be able to deploy the WAR file to both instances.</p>
<p><img src="https://lh7-us.googleusercontent.com/1G-K1NqVYjmzIFCkD-RGwsFhURb6ryZK9QKDiFgf1LGYavLszJYlTxzbewAfL5HcmyUBR0jYG8Fs5IUVLvi2z7uyLGgT2u4ZgOaW9OtTueQcDdDrIA9jbOQ9Imj3hKibBgaVq5uRisPpOx0B7YftnpY" alt /></p>
<h2 id="heading-aws-setup"><strong>AWS Setup</strong></h2>
<h3 id="heading-create-a-target-group"><strong>Create a Target Group</strong></h3>
<p>EC2 &gt; Target Groups &gt; Create Target Group</p>
<p>Basic Config &gt; Instances</p>
<p>Target group name = akhil-p1</p>
<p>Protocol : Port = HTTP 8080</p>
<p>VPC: default</p>
<p>Protocol version: HTTP1</p>
<p>Health check path: /</p>
<h3 id="heading-register-targets">Register targets</h3>
<p>Add the Server A and B to the target group.</p>
<p><img src="https://lh7-us.googleusercontent.com/QCg-02R-q3B8CX0nQt0k86l_pgV8vIVpnnp9zjPx0T3J_x9PvCbgCszO1zR50XhSCsshF1NOwbwHRUNmHAyqdVD2OSDX_OkRyRuEOduMnQ3OmTLL733kkxJviAePxClWjt1yvgjMDA9RIGtbUVcLbGQ" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/OZWpSFExouCsjkvy7KTX3Q-BQpzsmOPJ1uydmv90bNnPye0_qAiI5BYJCVIdUrV8Sykpsq1zx1hwXVLN0G_at85lIfHXbnANXclf7pf_3ki3WE5CotulwHZRTdNCTa7S_fXRoPPTfKDQrbcAV3zCFaA" alt /></p>
<h3 id="heading-application-load-balancer"><strong>Application Load Balancer</strong></h3>
<p>EC2 &gt; Load Balancers &gt; Create &gt; Application Load Balancer</p>
<p>Internet facing, IPv4, default VPC, select all subnets, </p>
<p>Create a Security Group</p>
<ul>
<li>open ports 80, 443</li>
</ul>
<p>Listeners and routing </p>
<ul>
<li>select your target group</li>
</ul>
<p>Create ALB<br />Get it's DNS Name: <a target="_blank" href="http://ahkil-project-1-1938854889.ap-northeast-1.elb.amazonaws.com">ahkil-project-1-1938854889.ap-northeast-1.elb.amazonaws.com</a></p>
<h2 id="heading-blue-green-deployment">Blue / Green Deployment</h2>
<p>The pipeline has many parameters that we can select at build time.</p>
<p><img src="https://lh7-us.googleusercontent.com/9wmm_HqgzT7pSKT9TtqR4-GT2lQ_Qgp7tpT9DdVLEZqrCuBY-m4MtPkrRMMdKQIZ0u9S1en1ocm3oToGJq6On4OtS3Cv3vQ2o7kaWk8EWeD8G6RWNhq7nu3Ztbo_oOiOXQ9iWGxMO0QorwpUplBzlfU" alt /></p>
<p>While deploying a new version of the app, you can select which server to deploy to using the check boxes for SERVER_A and SERVER_B. These are Boolean Parameters in the pipeline and are "true" by default. This will deploy the app to both servers. </p>
<p>To deploy it only to server B, uncheck server A. </p>
<p>Made a change to the "message" in src/main/java/com/akhilsharma/web/<a target="_blank" href="http://HelloController.java">HelloController.java</a></p>
<p>Commit and Push</p>
<p>Build with Parameters &gt; Select Server B Only</p>
<p><img src="https://lh7-us.googleusercontent.com/9mFsuwKd_hMfRpC_jR9UQEbdd6t64X2DPhiUxTWzuhAhnCFjVKM_duI0nVv52CRjMAeLRLi6mjD8WBcwWedqsERUk26HJ_3QpNJQIeg6Rwn4R1BrH7zqjkph5529LxXeQ0kx8Zno8qETzIdWsiSda7k" alt /></p>
<p>Now access the ALB DNS name. You can see 2 versions of the app upon refreshing the page.</p>
<h2 id="heading-ssl-setup"><strong>SSL Setup</strong></h2>
<p>Route 53 &gt; Select Zone &gt; Create Alias record</p>
<p><img src="https://lh7-us.googleusercontent.com/zY6CijoRBM8Eu8JAAlJdDS-RyK5sTOQz1HumeUEWjNwWJTXEz0WOvTPgSeF-ItCLNtK4vTguwc6W_2ilfH0suf6y__c72kVRB8u3GWID8CT6Vbs20CsWaFIoubfj3l2ftrvITYENtHckOFQKq3wVua0" alt /></p>
<p><a target="_blank" href="http://javaapp1.aws.melvincv.com/">http://javaapp1.aws.melvincv.com/</a> </p>
<p>Your URL is now available.</p>
<h3 id="heading-create-an-ssl-certificate-using-aws-acm"><strong>Create an SSL certificate using AWS ACM</strong></h3>
<p>Add a CAA Record for your zone</p>
<p><strong>Amazon will not issue a certificate without this record.</strong></p>
<p>Add the below value to the record. You may use <code>issuewild</code> or <code>issue</code>. <code>issuewild</code> is used to authorize the issue of wildcard SSL certificates.</p>
<p>Value:</p>
<pre><code class="lang-bash">0 issuewild <span class="hljs-string">"amazon.com"</span>
0 issuewild <span class="hljs-string">"amazontrust.com"</span>
</code></pre>
<p><img src="https://lh7-us.googleusercontent.com/rMXUAGMtVmFFtJvGRX9WeUFg9ZjKeFz15Dpztaquhz4rT4ODCnBNsFwQmk4fJ3PU1jMkRz27UlItMvDdJg8Ig7BdgzsRrDnPwx5rWffT1fuNoJyX4kAKoXm2mP4C5Bq0Qk4gG3UQuyPhJ8hr_k3Df0g" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/xQJMQgQ_yKe7-O2RLsTyhmIQpTxSwxH9ppfhlZ8bT5yTP9QRuj37Us13w_N3C7-yKseav4a3Q3nu8tQul7S_kk2MA7RfnFzViRwh72EoFy-9zf765ka7oUEah4Y2fR5K_e7OrSE2XnCMqvg8Rx0A2kQ" alt /></p>
<p>AWS Certificate Manager &gt; Request a public certificate &gt; </p>
<p>FQDN:  *.aws.melvincv.com</p>
<p>Key algorithm: RSA</p>
<p>Create CNAME record in Route 53 (or automatically)</p>
<p><img src="https://lh7-us.googleusercontent.com/HOoOunWJILQaxq3W2XXAZ9Utu5BOgXk_UBweaE72dWdRiivQcjWp0O2pRYanfSsQM3_p2WHob_yVwdt9vsfPfo0gFN2jvgghTTjFKvjRVs8wszfpAkLTWDeu6mp851QRBJ_WqbGOSxkVZTmAyR78F3U" alt /></p>
<h3 id="heading-configure-app-load-balancer"><strong>Configure App Load Balancer</strong></h3>
<p>EC2 &gt; Load balancers &gt; ahkil-project-1</p>
<p><strong>Listeners and rules</strong></p>
<p>Add listener &gt; HTTPS 443</p>
<p>Forward to target group &gt; akhil-p1</p>
<p>Default SSL/TLS server certificate &gt; *.aws.melvincv.com</p>
<p><strong>Forward HTTP to HTTPS</strong></p>
<p>HTTP listener &gt; Edit Rules</p>
<p><img src="https://lh7-us.googleusercontent.com/gPaWXhdknj6Of-LMjmG6Bbgxl1AtTbxzs7GkTw-JOsuL8L7UZCcVz3PSUu0_fxlimmHGZIS43RWO1P3JSgFxHn7951HDtxlKCqlWCpF1fGDqEIpjk4RshrEMi1yu98uuEC2n6mxBEvPyACTPhwWddmI" alt /></p>
<p>Edit Rule &gt; Default &gt; Redirect to URL</p>
<p><img src="https://lh7-us.googleusercontent.com/PXI5U_QMTs7diCk8qQG_v6nr1MmDqPSecDN0ajIU2tftChaFs7_r6cmcsUiUQ-XAeT81GQYwmO0eEs65htoB6zR7Pw1DQmuIWAnr8AylmmmYoG-bGqkX5CI6JYT6wfORqFiGJkCinQ5Nid3-2kRwxtM" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/zlSf4GWqHW6Tijsr8T7yK9FNr-bNI_Qs9TyvXlIQC0hGMLgYJChVTdCH_H4znsW9aqgDnyqWnP5Jr42Cj3dXQKaIcEpDfWnwijLx5mZhEJxEPEKAbk-Z-zUa6pqgnWi8D3-h36tkEpvh5YtNZSsx2oQ" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/qKTiPe2BjC6FmTcIejGw_Ed01TXCx0PeA4mULdCzbsGDg2es7bE23Izz-dflhtCrMlFgRCVrSAwkLBCuKBVdt_xIH80_buaVlGWEML8mFrjOJMrS88OSOdcyi7lCZ2ubc8Euuyo7GHHAhtaELH6997E" alt /></p>
<h1 id="heading-results"><strong>Results</strong></h1>
<p>On accessing the URL and refreshing the page, we get 2 versions of the app with different messages due to the blue/green deployment.</p>
<p><img src="https://lh7-us.googleusercontent.com/EQbwKlF1MqCw0DNbHX3pTEGtKjZaebOSuw_iyeHJ8_g7dHLb1SCHkdRn_uTVKxPizTVGMrHs_P8zPBBCab28pBnTAqtumM4uo-aOYrZL3feGrnlT5XplJgN8LR3iZ-5ip_Kp9idlD4T2CaeeCrLH4L4" alt /></p>
<p><img src="https://lh7-us.googleusercontent.com/d1-1vInwFPjbBt2aPdfGt_qIYzEm7nItV8u6rD2U9bhRF3rHgH-YccxEikJa3MFE433noV0zahsE6zlU92mHOk7VpakwRdkf0_eXto0IRbpjy3Var0fE4huoKp092vHoKkjuC5fsupn-HGzj8lj7DXM" alt /></p>
<h2 id="heading-jenkins-console-output">Jenkins Console Output</h2>
<p><a target="_blank" href="https://docs.google.com/document/d/1we90623_GcuqjKwXQz3QNYi1EIUwJOcj17U3SDECrxc/edit?usp=sharing">Blue/Green Deployment</a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1BigCrXl7nWI4lklMCUXHk54CzS0Qps1dtnmuDHe2XUE/edit?usp=sharing">Normal Deployment</a></p>
<hr />
<p>Hope you found this article useful. You are free to make modifications to this project. Linking to the original article will be much appreciated! Let me know what you think of this project in the comments!</p>
]]></content:encoded></item><item><title><![CDATA[Jenkins Pipeline with Maven, SonarQube, Docker, and AWS ECR]]></title><description><![CDATA[The controller is the main Jenkins instance that will co-ordinate the connections and tooling for the agents. Agents are the workhorse instances used to…]]></description><link>https://blog.melvincv.com/jenkins-pipeline-with-maven-sonarqube-docker-and-aws-ecr</link><guid isPermaLink="true">https://blog.melvincv.com/jenkins-pipeline-with-maven-sonarqube-docker-and-aws-ecr</guid><category><![CDATA[ Jenkins, DevOps]]></category><category><![CDATA[sonarqube]]></category><category><![CDATA[AWS ECR]]></category><category><![CDATA[ec2]]></category><category><![CDATA[Docker]]></category><category><![CDATA[ansible]]></category><category><![CDATA[maven]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Mon, 15 Apr 2024 09:27:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713173131651/2b7b24c3-0b14-45b3-b694-be0bd4698bb0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-jenkins-install">Jenkins Install</h2>
<h3 id="heading-controller-and-agent">Controller and Agent</h3>
<p><strong>The controller</strong> is the main Jenkins instance that will co-ordinate the connections and tooling for the agents.</p>
<p><strong>Agents</strong> are the workhorse instances used to run jobs and pipelines. It can have various tools and unique tags to build different kinds of projects.</p>
<p>Let's set up a Jenkins controller on AWS EC2. It is not recommended to run jobs on the controller for security reasons. But this is a single instance setup and will run jobs... I will also set up a Caddy reverse proxy with SSL to direct traffic to Jenkins. Caddy is chosen for its simplicity, performance, and security. <a target="_blank" href="https://caddyserver.com/features">Read more about Caddy.</a></p>
<p>EC2 Instance settings:</p>
<ul>
<li><p>Instance type: t3.small</p>
</li>
<li><p>AMI: Ubuntu Server 22.04 LTS</p>
</li>
<li><p>Select / Create an "SSH Key pair"</p>
</li>
<li><p>Select / Create a "Security Group" with the following inbound rules:</p>
<ul>
<li><p>Port 22, SSH - Your IP</p>
</li>
<li><p>Port 80 - Anywhere</p>
</li>
<li><p>Port 443 - Anywhere</p>
</li>
</ul>
</li>
<li><p>Storage: increase it by a few GB, I used 15 GB</p>
</li>
<li><p>Advanced details:</p>
<ul>
<li><p>Spot instances (Optional, to save costs)</p>
</li>
<li><p>IAM instance profile (Optional)</p>
</li>
<li><p>User data: <a target="_blank" href="https://raw.githubusercontent.com/melvincv/blog-melvincv/main/jenkins/udemy-202403/jenkins/install.sh">Enter this script to install Jenkins automatically</a></p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-add-to-route-53">Add to Route 53</h3>
<p>Add a DNS A record to Route 53 for your Jenkins domain to point to your IP address.</p>
<h3 id="heading-log-in-to-jenkins">Log in to Jenkins</h3>
<p>Set the hostname</p>
<pre><code class="lang-plaintext">sudo hostnamectl set-hostname jenkins-svr
sudo vim /etc/hosts
bash
</code></pre>
<p>Check the cloud-init log to confirm that the script execution was a success.</p>
<pre><code class="lang-plaintext">tail -f /var/log/cloud-init-output.log
</code></pre>
<p>Start the caddy server</p>
<pre><code class="lang-plaintext">sudo systemctl start caddy
journalctl -u caddy -f
---
"msg":"certificate obtained successfully"
</code></pre>
<p>Access Jenkins in the browser</p>
<p>Eg: <a target="_blank" href="https://jenkins.aws.melvincv.com/">https://jenkins.aws.melvincv.com/</a></p>
<p>Unlock Jenkins</p>
<pre><code class="lang-plaintext">sudo cat /var/lib/jenkins/secrets/initialAdminPassword
</code></pre>
<p>Install Suggested Plugins.</p>
<p>Get the <strong>JDK</strong> and <strong>Maven</strong> paths and add them to <strong>Manage Jenkins &gt; Tools</strong></p>
<pre><code class="lang-plaintext">$ mvn --version
Apache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae)
Maven home: /opt/apache-maven
Java version: 17.0.10, vendor: Private Build, runtime: /usr/lib/jvm/java-17-openjdk-amd64
</code></pre>
<p>Name: openjdk17</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713156998647/5d743546-d657-4f3c-8d80-641601b700db.png" alt class="image--center mx-auto" /></p>
<p><strong>Name</strong>: maven3.9</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713157045962/b763fc4c-054c-421d-ab44-c2333e5d4f02.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-plaintext">sudo usermod -aG docker jenkins
sudo systemctl restart jenkins
</code></pre>
<h3 id="heading-install-jenkins-plugins">Install Jenkins Plugins</h3>
<p>Manage &gt; Plugins &gt; Available</p>
<ul>
<li><p>sonarqube scanner</p>
</li>
<li><p>AWS Credentials</p>
</li>
<li><p>Amazon ECR</p>
</li>
<li><p>docker</p>
</li>
<li><p>docker pipeline</p>
</li>
<li><p>ansible</p>
</li>
</ul>
<h1 id="heading-sonarqube-install">Sonarqube Install</h1>
<p>Create a new EC2 instance for Sonarqube.</p>
<p>EC2 Instance settings:</p>
<ul>
<li><p>Instance type: t3.medium</p>
</li>
<li><p>AMI: Ubuntu Server 22.04 LTS</p>
</li>
<li><p>Select / Create an "SSH Key pair"</p>
</li>
<li><p>Select / Create a "Security Group" with the following inbound rules:</p>
<ul>
<li><p>Port 22, SSH - Your IP</p>
</li>
<li><p>Port 80 - Anywhere</p>
</li>
<li><p>Port 443 - Anywhere</p>
</li>
</ul>
</li>
<li><p>Storage: increase it by a few GB, I used 15 GB</p>
</li>
<li><p>Advanced details:</p>
<ul>
<li><p>Spot instances (Optional, to save costs)</p>
</li>
<li><p>IAM instance profile (Optional)</p>
</li>
<li><p>User data: <a target="_blank" href="https://raw.githubusercontent.com/melvincv/blog-melvincv/main/jenkins/udemy-202403/sonarqube/prereq.sh">Enter this script to install prerequisites automatically</a></p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-log-in-to-sonarqube">Log in to sonarqube</h3>
<p>Set hostname</p>
<pre><code class="lang-plaintext">sudo hostnamectl set-hostname sonarqube
sudo vim /etc/hosts
bash
</code></pre>
<p>Log in to the instance and create a folder and the docker-compose file</p>
<pre><code class="lang-plaintext">mkdir sonar; cd sonar
cat &gt; compose.yml
</code></pre>
<p>Paste the <a target="_blank" href="https://github.com/melvincv/blog-melvincv/blob/main/jenkins/udemy-202403/sonarqube/compose.yml">contents of this file</a> and press Ctrl+D</p>
<p>Create a .env file in the same folder with the Postgres password:</p>
<pre><code class="lang-plaintext">POSTGRES_PASSWORD=xxxxxxxxxxxxxxxxxxx
</code></pre>
<p>Start the compose stack:</p>
<pre><code class="lang-plaintext">docker compose pull
docker compose up -d
</code></pre>
<p>Wait for a minute for it to initialize...</p>
<pre><code class="lang-plaintext">ubuntu@sonarqube:~/sonar$ docker compose ps
NAME                IMAGE                     COMMAND                  SERVICE     CREATED              STATUS              PORTS
sonar-adminer-1     adminer                   "entrypoint.sh php -…"   adminer     About a minute ago   Up About a minute   0.0.0.0:10000-&gt;8080/tcp, :::10000-&gt;8080/tcp
sonar-db-1          postgres:12               "docker-entrypoint.s…"   db          About a minute ago   Up About a minute   5432/tcp
sonar-sonarqube-1   sonarqube:lts-community   "/opt/sonarqube/dock…"   sonarqube   About a minute ago   Up About a minute   0.0.0.0:9000-&gt;9000/tcp, :::9000-&gt;9000/tcp
</code></pre>
<p>In AWS Route 53, add an A record to point to your instance IP Address.</p>
<p>Wait for a few minutes for the DNS entries to take effect... Then start the Caddy server and check its logs to see if the Let's Encrypt certificate got issued:</p>
<pre><code class="lang-plaintext">sudo systemctl start caddy
journalctl -u caddy -f
---
"msg":"certificate obtained successfully"
</code></pre>
<p>Log in with the default credentials and change your password to a strong one:</p>
<blockquote>
<p>user: admin pass: admin</p>
</blockquote>
<p>In the Sonarqube dashboard, create a token for Jenkins:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711373672696/7fc3b925-9ce3-4281-ac18-e92a60fd64b9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711373701449/d376abb5-5abd-4923-91f2-6ed4dd8df1c9.png" alt class="image--center mx-auto" /></p>
<p>In Jenkins, add a credential of type "Secret text" with ID "sonar-token"</p>
<p>Go to "Manage Jenkins &gt; System &gt; Sonarqube installations" and "Add a Sonarqube server."</p>
<blockquote>
<p>Name: sonar</p>
<p>URL: <a target="_blank" href="https://sonar.aws.melvincv.com/">https://sonar.aws.melvincv.com/</a></p>
<p>Token: sonar-token</p>
</blockquote>
<p>In Sonarqube, create a webhook that allows it to ping Jenkins after the code passes the quality gate. Administration &gt; Config &gt; Webhooks</p>
<pre><code class="lang-plaintext">https://jenkins.aws.melvincv.com/sonarqube-webhook/
</code></pre>
<p>Make sure you replace <code>jenkins.aws.melvincv.com</code> with your jenkins URL. Slash at the end of the URL is important.</p>
<p>To login and push to AWS ECR, we need Access Key ID and Secret Key of a user with AWS ECR Full Access permissions.</p>
<p>Create "AWS Credentials" with ID <code>jenkins-ecr-login-credentials</code></p>
<p>Add your Access Key ID and Secret Key.</p>
<h2 id="heading-aws-ecr">AWS ECR</h2>
<p>Create a new Private repository called <code>springbootapp</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713165929894/88c2be64-0339-4b3b-9980-fe8bd49070bf.png" alt class="image--center mx-auto" /></p>
<p>Create an IAM user with permission to read and write to the repo. (<a target="_blank" href="https://us-east-1.console.aws.amazon.com/iam/home?region=ap-northeast-1#/policies/details/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FAmazonEC2ContainerRegistryFullAccess">AmazonEC2ContainerRegistryFullAccess</a>)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713166076366/0d120314-c666-459f-a6e5-2dea43d59d16.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-create-a-jenkins-job">Create a Jenkins Job</h2>
<p>Create a Job of type "Pipeline"</p>
<p>Tick the option "<strong>GitHub hook trigger for GITScm polling</strong>"</p>
<p>Paste the Pipeline file and save it.</p>
<h3 id="heading-create-a-github-webhook">Create a Github Webhook</h3>
<p>You may create a webhook for the app repo so that Github can ping Jenkins when a commit is pushed to the repo branch.</p>
<p><strong>Payload URL:</strong><a target="_blank" href="https://jenkins.aws.melvincv.com/github-webhook/">https://jenkins.aws.melvincv.com/github-webhook/</a></p>
<p>👷‍♂️ Build Now.</p>
<p>Sonarqube Project will be added to the Projects page by Jenkins. ⬇️</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711374542994/a63ff53d-b9fc-4f31-8f30-588474502f31.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-email-notifications">Email Notifications</h2>
<p>Send email notifications of the build status to your email ID using AWS SES.</p>
<p>Manage Jenkins &gt; System &gt; Scroll to end</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711374783405/50587e88-f170-4077-a591-fc843669c6e3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711374872822/31f8c7a7-4b6c-4ae2-bdeb-00aaeed268ea.png" alt class="image--center mx-auto" /></p>
<p>Scroll up and add the From address</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711374936644/ed18c204-3acd-4a81-b8ca-6ed9069c5a0a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-cd-using-ansible">CD using Ansible</h2>
<p>The "CD with Ansible" Step would have failed while building the job in Jenkins.</p>
<p>Start / Prepare a Target CD Instance with the following user data:</p>
<pre><code class="lang-plaintext">#!/bin/bash
# Upgrade packages
sudo apt update &amp;&amp; sudo apt upgrade -y
# Install Docker
curl -fsSL https://get.docker.com -o install-docker.sh
sudo sh install-docker.sh
sudo usermod -aG docker $USER
# Install AWS CLI v2
sudo apt install -y unzip
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
</code></pre>
<p>Update the IP address in the inventory file.</p>
<p>Create Jenkins Credentials of type "SSH Username with private key" with ID "cd-server-creds"</p>
<p>Create an <a target="_blank" href="https://github.com/melvincv/blog-melvincv/blob/main/jenkins/udemy-202403/ansible/playbook.yml">Ansible Playbook (present in repo)</a> that pulls the docker image from AWS ECR and runs a container from it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1713165745425/ab653171-b126-41b3-b958-fb2113707661.png" alt class="image--center mx-auto" /></p>
<p>Finally, you should have the app running as a Docker container on port 8080 of the target instance.</p>
<h2 id="heading-github-repos">GitHub Repos</h2>
<p>Scripts: <a target="_blank" href="https://github.com/melvincv/blog-melvincv/tree/main/jenkins/udemy-202403">https://github.com/melvincv/blog-melvincv/tree/main/jenkins/udemy-202403</a></p>
<p>App and Ansible files: <a target="_blank" href="https://github.com/melvincv/springboot-maven-micro">https://github.com/melvincv/springboot-maven-micro</a></p>
]]></content:encoded></item><item><title><![CDATA[#10weeksofCloudOps - Week 4]]></title><description><![CDATA[Docker, Kubernetes and GitOps]]></description><link>https://blog.melvincv.com/10weeksofcloudops-week-4</link><guid isPermaLink="true">https://blog.melvincv.com/10weeksofcloudops-week-4</guid><category><![CDATA[ArgoCD]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[docker images]]></category><category><![CDATA[gitops]]></category><category><![CDATA[Terraform]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[github-actions]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Tue, 02 Jan 2024 06:24:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704176622269/871ab190-c1b2-4852-b4e5-c41a001eb8ae.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>This is Melvin C V, your Cloud Buddy. I am back after a long break with Week 4 of the #10weeksofCloudOps challenge! This project is meant to demonstrate my proficiency in containerization, orchestration, continuous integration, and continuous deployment (CI/CD) in a Kubernetes environment.</p>
<p><strong>Containerization</strong> is a method of packaging software applications into standardized units called <strong>containers</strong>. Containers are lightweight, portable, and self-sufficient, making them ideal for deploying applications across different environments.</p>
<p><strong>Orchestration</strong> is the process of managing the lifecycle of containers within a distributed environment. It streamlines the process of deploying, scaling, configuring, networking, and securing containers, freeing up engineers to focus on other critical tasks. Orchestration also helps ensure the high availability of containerized applications by automatically detecting and responding to container failures and outages.</p>
<p><strong>Continuous Integration and Continuous Deployment (CI/CD)</strong> is a software development practice that enables developers to build, test, and deploy code changes to production quickly and safely. CI/CD pipelines automate the entire software delivery process, from code changes to production deployment, ensuring that code changes are thoroughly tested and validated before they are released to end-users.</p>
<p><strong>Kubernetes</strong> is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. It provides a powerful and flexible platform for deploying and managing containerized applications at scale, making it an ideal choice for organizations looking to modernize their application infrastructure.</p>
<h1 id="heading-solution">Solution</h1>
<h2 id="heading-github-code">GitHub Code</h2>
<p><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w4/">melvincv/10weeksofcloudops-w4: CICD on Kubernetes (github.com)</a></p>
<h2 id="heading-architecture">Architecture</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704176261524/8fecf7a2-780d-4b4c-b0c9-1dadabe7134a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-steps">Steps</h2>
<h3 id="heading-dockerize-a-web-application">Dockerize a Web Application</h3>
<p>I started with the <a target="_blank" href="https://www.youtube.com/watch?v=FHTbsZEJspU">YouTube clone app</a> by <a target="_blank" href="https://www.youtube.com/@javascriptmastery">JS Mastery</a>.</p>
<p>It is a Nodejs-based app that is a frontend to a hosted <a target="_blank" href="https://rapidapi.com/ytdlfree/api/youtube-v31?utm_source=youtube.com%2FJavaScriptMastery&amp;utm_medium=referral&amp;utm_campaign=DevRel">YouTube API</a>. It gets videos from that API and displays them to the user.</p>
<ol>
<li><p>Subscribe to the hosted API at <a target="_blank" href="https://rapidapi.com/developer/billing/subscriptions-and-usage">Billing, Subscriptions And Usage | Rapid API Hub | Developer Dashboard</a></p>
</li>
<li><p>In my repo, go to <code>app/youtube-clone/.env</code> and enter the value of your API key in <code>REACT_APP_RAPID_API_KEY</code></p>
</li>
<li><p>Check out my Dockerfile at <code>app/youtube-clone/Dockerfile</code></p>
</li>
</ol>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Multi-stage Dockerfile</span>
<span class="hljs-comment"># Stage 1</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">16</span> AS builder
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-keyword">COPY</span><span class="bash"> package*.json .</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm ci</span>

<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm run build</span>

<span class="hljs-comment"># Stage 2</span>
<span class="hljs-keyword">FROM</span> nginx:<span class="hljs-number">1.25</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /usr/share/nginx/html</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=builder /app/build .</span>
</code></pre>
<p><strong>Multi-stage Dockerfiles</strong> are a way of organizing Dockerfiles to minimize the size of the final container, improve runtime performance, and provide a standardized method of running build actions.</p>
<p>With multi-stage builds, you use multiple <code>FROM</code> statements in your Dockerfile. Each <code>FROM</code> instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image.</p>
<p>A multi-stage Dockerfile is used to first build the nodejs app using the <code>node:16</code> image The build artifacts are then copied to an <code>nginx</code> based image from the previous image.</p>
<p>Build the final image using this <code>Dockerfile</code> and push it to Docker Hub:</p>
<pre><code class="lang-bash">docker build -t melvincv/ytclone .
docker login
docker push melvincv/ytclone
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703048801977/2a086528-b806-40a7-8731-4d92520a349a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-provision-a-kubernetes-cluster-on-gke">Provision a Kubernetes Cluster on GKE</h3>
<p>Using Terraform to provision a multi-zonal GKE cluster with 2 node pools on Google Cloud:</p>
<p>You may check out my terraform code at <code>tf-gcp-kubernetes</code></p>
<p><strong>Creating the infrastructure...</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703135757594/48f41714-38af-4827-bb7a-fa16a4be5be7.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703135817972/3d4722da-cfae-4da2-8e4f-342e43407676.png" alt class="image--center mx-auto" /></p>
<p>...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703135845645/2aed4351-e777-4d1b-a37a-a1862322357c.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703136051236/1e5a7faa-0da1-43e1-901a-7891119ce89a.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137179246/683f0475-7c7b-4aaf-bf59-a63731086bfb.png" alt class="image--center mx-auto" /></p>
<p><strong>Code Explanation</strong></p>
<p><code>tf-gcp-kubernetes/1_main.tf</code></p>
<ul>
<li><p>line numbers in brackets []</p>
</li>
<li><p>there are 2 blocks of code: terraform block and provider block</p>
</li>
<li><p>terraform block [8-19] is used to</p>
<ul>
<li><p>store remote state in a Cloud Storage bucket called <code>melvincv2023-tf-cloudops-w4-dev</code></p>
</li>
<li><p>initialize the Google Cloud provider <code>hashicorp/google</code> that handles the provisioning of resources on Google Cloud by communicating with it's API's.</p>
</li>
<li><p>the remote state enables a central storage for the state of the infrastructure created. This facilitates collaboration between team members via the storage of Terraform code in a git repo.</p>
</li>
<li><p>State locking is also used to prevent more than one person from modifying infrastructure at the same time.</p>
</li>
</ul>
</li>
<li><p>provider block [2-5] is used to provide arguments to the <code>google</code> provider.</p>
<ul>
<li>project name and region</li>
</ul>
</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/2_vpc.tf</code></p>
<ul>
<li><p>line numbers in brackets []</p>
</li>
<li><p>[2 - 8]: enable the compiute and container API's of GCP</p>
</li>
<li><p>[11 - 20]: create a regional VPC named <code>main</code></p>
</li>
<li><p>[23-38]: create a subnet named <code>private1</code> with variables</p>
<ul>
<li><p><code>main_cidr</code> CIDR range of the VPC</p>
</li>
<li><p><code>main_cidr_sec1</code> Secondary CIDR range 1 (for pods)</p>
</li>
<li><p><code>main_cidr_sec2</code> Secondary CIDR range 2 (for services)</p>
</li>
</ul>
</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/3_cloud-router.tf</code></p>
<ul>
<li>create a Cloud Router for use in <a target="_blank" href="https://www.geeksforgeeks.org/network-address-translation-nat/">Network Address Translation</a>. Since you are creating a private k8s cluster, the nodes will need access to the Internet through a NAT router.</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/4_nat.tf</code></p>
<ul>
<li><p>[2-16]: create a NAT service in the Router we created earlier</p>
<ul>
<li>using attributes to refer to the router, private subnet and public IP</li>
</ul>
</li>
<li><p>[19-25]: create an external IP address and bind it to the NAT service via <code>self_link</code></p>
</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/5_firewalls.tf</code></p>
<ul>
<li>create a firewall named <code>allow-ssh</code> and associate it with the VPC</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/6_kubernetes.tf</code></p>
<ul>
<li><p>[2-54]: create a GKE cluster named 'primary'</p>
<ul>
<li><p>[3-12]: specify the zone, remove the default node pool, specify the private subnet created earlier and set deletion protection to false.</p>
</li>
<li><p>[15-26]: add another zone to make it a multi-zonal cluster.</p>
</li>
<li><p>[19-26]: configure addons to GKE</p>
<ul>
<li><p>enable k8s services to create Load balancers on GCP via the "HTTP (L7) load balancing controller"</p>
</li>
<li><p>disable horizontal pod autoscaling</p>
</li>
</ul>
</li>
<li><p>[28-34]</p>
<ul>
<li><p>set the release channel of Kubernetes to REGULAR. Other options include RAPID and STABLE</p>
</li>
<li><p>set the workload identity</p>
</li>
</ul>
</li>
<li><p>[36-45]</p>
<ul>
<li><p>set the pod CIDR and service CIDR that we defined earlier</p>
</li>
<li><p>enable the creation of private VPC nodes and enabled access to the cluster through both private and public endpoints</p>
</li>
<li><p>set the CIDR for the hosted master node network, must be /28</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/7_node-pools.tf</code></p>
<ul>
<li><p>[2-4]: create a service account named 'kubernetes'</p>
</li>
<li><p>[7-32]: create a standard node pool that contains nodes of a particular config</p>
<ul>
<li><p><s>set the node count to 1. since it is a multi zonal cluster, this will actually create 1 node in each zone. (disabled)</s></p>
</li>
<li><p>added autoscaling with a min. of 0 nodes and max. of 2 nodes</p>
</li>
<li><p>set auto repair and auto upgrade to true</p>
</li>
<li><p>set machine type, disk size via variables, set disk type to balanced (standard SSD)</p>
</li>
<li><p>add labels, specify service account and oauth scopes</p>
</li>
</ul>
</li>
<li><p>[34-67]: create a spot node pool (much cheaper, uses spare capacity on GKE and can be terminated to make resources available to standard nodes)</p>
<ul>
<li><p>similar to the standard node pool, adding autoscaling to a max. of 5 nodes.</p>
</li>
<li><p>set the spot instance type via variable</p>
</li>
</ul>
</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/8_serviceaccount.tf</code></p>
<ul>
<li><p>[2-4]: add a service account called <code>service-a</code> and</p>
</li>
<li><p>[7-11]: give the service account the role (permission) of "Storage Admin"</p>
</li>
<li><p><s>[14-18]: give the service account the role of "workloadIdentityUser"</s></p>
</li>
</ul>
<hr />
<p><code>tf-gcp-kubernetes/terraformvars</code></p>
<p>rename this file to <code>terraform.tfvars</code> and fill in the values for the variables.</p>
<p><code>tf-gcp-kubernetes/variables.tf</code></p>
<p>Variable definitions and descriptions</p>
<hr />
<p><code>tf-gcp-kubernetes/9_outputs.tf</code></p>
<p>output the id and endpoint of the cluster</p>
<hr />
<h3 id="heading-connecting-to-the-k8s-cluster-using-wsl2">Connecting to the K8s cluster using WSL2</h3>
<p>Install the gcloud CLI on Ubuntu on WSL2:</p>
<p><a target="_blank" href="https://cloud.google.com/sdk/docs/install#deb">Install the gcloud CLI  |  Google Cloud CLI Documentation</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137357140/6cf718a2-a96e-4b3d-924d-a188831d7714.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137530085/fba8a28f-6448-4340-bec7-2cd2f4086053.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-kubernetes-manifests">Kubernetes Manifests</h3>
<ol>
<li><p><code>kubernetes-manifests/1_ns.yml</code>: Creates a Namespace called yt-clone</p>
</li>
<li><p><code>kubernetes-manifests/2_deployment.yml</code>: Creates a Deployment with 2 replicas of the yt-clone pod</p>
</li>
<li><p><code>kubernetes-manifests/3_service.yml</code>: Creates a Service with the yt-clone pods as Endpoints</p>
</li>
<li><p><code>kubernetes-manifests/4_ingress.yml</code>: Creates an Ingress object for the NGINX ingress controller (which needs to be installed on the cluster first)</p>
</li>
<li><p><code>kubernetes-manifests/README.md</code>: Instructions to install the Ingress controller and bring up the app.</p>
</li>
</ol>
<h2 id="heading-what-is-argocd">What is ArgoCD?</h2>
<p>Argo CD is a <strong>declarative continuous delivery tool</strong> for Kubernetes that can be used as a standalone tool or as part of your CI/CD workflow to deliver needed resources to your clusters. It enables developers to manage both infrastructure configuration and application updates in one system.</p>
<p>Argo CD offers manual or automatic deployment of applications to a Kubernetes cluster, automatic synchronization of application state to the current version of declarative configuration, web user interface and command-line interface (CLI), ability to visualize deployment issues, detect and remediate configuration drift, role-based access control (RBAC) enabling multi-cluster management, and support for webhooks triggering actions in GitLab, GitHub, and BitBucket.</p>
<h2 id="heading-install-the-nginx-ingress-controller">Install the NGINX ingress controller</h2>
<pre><code class="lang-bash">kubectl create clusterrolebinding cluster-admin-binding \
  --clusterrole cluster-admin \
  --user $(gcloud config get-value account)
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/cloud/deploy.yaml
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703140962860/cdcf62d6-601f-4e9a-bec6-5bf29080c284.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-install-argocd">Install ArgoCD</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137726334/0c944752-44e1-408b-96af-d766bee20b3f.png" alt /></p>
<p>...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137760216/62e91104-ad10-48d2-90a0-aaf4f1a7f979.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137781125/dcb9fd74-fddf-49ea-91ab-cafe11e15e03.png" alt /></p>
<p>Access the API Server on your PC using <code>kubectl port-forward</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137871120/05a3e181-0672-485c-b3fe-a0ab99751b4d.png" alt class="image--center mx-auto" /></p>
<p>Access the UI from your browser: <a target="_blank" href="https://localhost:10000/">https://localhost:10000/</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703137985801/0c3de806-786f-4206-8cb7-019924a37401.png" alt class="image--center mx-auto" /></p>
<p>User: admin<br />Password: get it from the secret: <code>argocd-initial-admin-secret</code></p>
<p><code>argocd admin initial-password -n argocd</code></p>
<p>Log in using the CLI and change the admin password asap...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703138561243/9648d5b4-9639-4863-8bd7-fe354cd20b58.png" alt class="image--center mx-auto" /></p>
<p>Log in to the GUI:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703138628529/4aca7f8a-026a-497e-b1a5-486e8a71b08e.png" alt class="image--center mx-auto" /></p>
<p>Create an Application for your Git repo that you intend to deploy into Kubernetes.</p>
<p>An <strong>application</strong> in ArgoCD is a collection of Kubernetes-native manifests that make up all the pieces of your application. It is a <strong>Custom Resource Definition (CRD)</strong> used to define an application source type. ArgoCD is a Kubernetes-native continuous deployment tool that can pull updated code from Git repositories and deploy it directly to Kubernetes resources. It enables developers to manage both infrastructure configuration and application updates in one system.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703140151197/e77c3e84-1bf2-4f34-aab4-3e5b13e8ddf8.png" alt class="image--center mx-auto" /></p>
<p>Enter the App details...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141333219/3cc0fcf3-0f92-4b2b-a1f0-aa4f823c5507.png" alt class="image--center mx-auto" /></p>
<p>Enter your repo and path to the manifests or Helm chart...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141153752/db3eaaeb-d09d-4e4a-8732-1b0700ec49ef.png" alt class="image--center mx-auto" /></p>
<p>For deploying to the same cluster to which ArgoCD is installed, give the default...</p>
<p><code>https://kubernetes.default.svc</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141176503/0781ff5f-1a3f-4205-94c2-bb57e5cf62d2.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141374812/b181cf79-4132-4855-ae32-1ec56d89be85.png" alt class="image--center mx-auto" /></p>
<p>It takes some time to create the app for the first time...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141713052/ec839043-028c-4325-80ca-47b74093ce8e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141757637/3d093fbc-6738-443f-a036-e37b1409912b.png" alt class="image--center mx-auto" /></p>
<p>Get the ingress details for k8s</p>
<p><code>k get ing -n yt-clone</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703141932189/43e34606-d54a-40df-a9ba-23a26864bedd.png" alt class="image--center mx-auto" /></p>
<p>Connect the domain to the IP using your DNS provider.</p>
<p>Mine is on Cloudflare, so I added an A record for <a target="_blank" href="http://ytclone.gcp.melvincv.com"><code>ytclone.gcp.melvincv.com</code></a> pointing to the IP of the Load balancer created by the NGINX ingress controller, which would be the same IP of the Ingress above.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703142080924/9fa723b6-1674-44de-b6f7-72b105924349.png" alt class="image--center mx-auto" /></p>
<p>And finally, you get your Youtube Clone site!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703142242104/895d4aac-1c63-4d53-950a-647af866d2f8.png" alt class="image--center mx-auto" /></p>
<p>Pod logs show that the requests are reaching the pods:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703142476202/66165e1e-3a1b-4077-b5fa-f4c4e6d10e6d.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article highlights the benefits of containerization, GitOps for deploying applications and the role of orchestration in managing container lifecycles. Melvin explains how he used Docker, Kubernetes, Terraform, and ArgoCD to create a modern and scalable application infrastructure.</p>
]]></content:encoded></item><item><title><![CDATA[FastCGI Micro Cache in NGINX]]></title><description><![CDATA[FastCGI Micro Cache is a caching mechanism that caches dynamic content in front of a web server with NGINX. It is the most efficient way to implement a…]]></description><link>https://blog.melvincv.com/fastcgi-micro-cache-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/fastcgi-micro-cache-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[fastcgi]]></category><category><![CDATA[dynamic cache]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Sat, 02 Sep 2023 05:58:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693634191257/3925ea56-e79b-417a-86e5-2fad62d1bc16.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>FastCGI Micro Cache is a caching mechanism that caches dynamic content in front of a web server with NGINX. It is the most efficient way to implement a dynamic cache mechanism. In this article, we will discuss how to configure FastCGI Micro Cache in NGINX.</p>
<h2 id="heading-configuration">Configuration</h2>
<ol>
<li>Edit the NGINX main configuration file to add the following lines in the <code>http</code> context:</li>
</ol>
<pre><code class="lang-nginx"><span class="hljs-section">http</span> {
<span class="hljs-comment"># Configure microcache (fastcgi)</span>
  <span class="hljs-attribute">fastcgi_cache_path</span> /tmp/nginx_cache levels=<span class="hljs-number">1</span>:<span class="hljs-number">2</span> keys_zone=ZONE_1:<span class="hljs-number">100m</span> inactive=<span class="hljs-number">60m</span>;
  <span class="hljs-attribute">fastcgi_cache_key</span> <span class="hljs-string">"<span class="hljs-variable">$scheme</span><span class="hljs-variable">$request_method</span><span class="hljs-variable">$host</span><span class="hljs-variable">$request_uri</span>"</span>;
  <span class="hljs-attribute">add_header</span> X-Cache <span class="hljs-variable">$upstream_cache_status</span>;
</code></pre>
<ol>
<li>Edit the virtual host configuration file in which caching is to be enabled.</li>
</ol>
<ol>
<li>Add the following content to the <code>server</code> context:</li>
</ol>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {
    <span class="hljs-comment"># Cache by default</span>
    <span class="hljs-attribute">set</span> <span class="hljs-variable">$no_cache</span> <span class="hljs-number">0</span>;
    <span class="hljs-comment"># Check for cache bypass</span>
    <span class="hljs-attribute">if</span> (<span class="hljs-variable">$arg_skipcache</span> = <span class="hljs-number">1</span>) {
      <span class="hljs-attribute">set</span> <span class="hljs-variable">$no_cache</span> <span class="hljs-number">1</span>;
    }

    <span class="hljs-attribute">location</span> / {
      <span class="hljs-attribute">try_files</span> <span class="hljs-variable">$uri</span> <span class="hljs-variable">$uri</span>/ =<span class="hljs-number">404</span>;
    }

    <span class="hljs-attribute">location</span> ~\.php$ {
      <span class="hljs-comment"># Pass php requests to the php-fpm service (fastcgi)</span>
      <span class="hljs-attribute">include</span> fastcgi.conf;
      <span class="hljs-attribute">fastcgi_pass</span> unix:/run/php/php7.1-fpm.sock;

      <span class="hljs-comment"># Enable cache</span>
      <span class="hljs-attribute">fastcgi_cache</span> ZONE_1;
      <span class="hljs-attribute">fastcgi_cache_valid</span> <span class="hljs-number">200</span> <span class="hljs-number">60m</span>;
      <span class="hljs-attribute">fastcgi_cache_bypass</span> <span class="hljs-variable">$no_cache</span>;
      <span class="hljs-attribute">fastcgi_no_cache</span> <span class="hljs-variable">$no_cache</span>;
    }
  }
</code></pre>
<p>Here’s a brief explanation of the code:</p>
<ul>
<li><p>The <code>server</code> block is the top-level configuration context for NGINX. It defines the settings for a virtual server.</p>
</li>
<li><p>The <code>set</code> directive is used to set a variable to a value. In this case, <code>$no_cache</code> is set to <code>0</code> by default.</p>
</li>
<li><p>The <code>if</code> directive is used to execute a block of code if a certain condition is met. In this case, it checks if the query parameter <code>skipcache</code> is set to <code>1</code>. If it is, <code>$no_cache</code> is set to <code>1</code>.</p>
</li>
<li><p>The <code>location</code> directive is used to define how NGINX should handle requests for a specific URL pattern.</p>
</li>
<li><p>The first <code>location</code> block defines how NGINX should handle requests for the root URL (<code>/</code>). It uses the <code>try_files</code> directive to check if the requested file exists and serve it if it does. If it doesn’t exist, it returns a 404 error.</p>
</li>
<li><p>The second <code>location</code> block defines how NGINX should handle requests for PHP files (files ending in <code>.php</code>). It includes the <code>fastcgi.conf</code> file, which contains common FastCGI configuration settings. It then passes the request to the PHP-FPM service using the <code>fastcgi_pass</code> directive.</p>
</li>
<li><p>The <code>fastcgi_cache</code> directive enables caching for FastCGI requests. In this case, it uses the cache zone named <code>ZONE_1</code>.</p>
</li>
<li><p>The <code>fastcgi_cache_valid</code> directive sets how long cached content should be considered valid. In this case, it sets it to 60 minutes for responses with a status code of 200.</p>
</li>
<li><p>The <code>fastcgi_cache_bypass</code> and <code>fastcgi_no_cache</code> directives are used to control when cached content should not be used. In this case, they use the <code>$no_cache</code> variable that was set earlier.</p>
</li>
</ul>
<ol>
<li><p>Apply your configuration changes.</p>
</li>
<li><p>Test out FastCGI Micro Cache using Apache Bench, etc.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>FastCGI Micro Cache is an efficient way to implement a dynamic cache mechanism in front of a web server with NGINX. It can help improve website performance and reduce server load. By following the steps outlined in this article, you can easily configure FastCGI Micro Cache in NGINX.</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://www.digitalocean.com/community/tutorials/how-to-setup-fastcgi-caching-with-nginx-on-your-vps">How to Setup FastCGI Caching with Nginx on your VPS | DigitalOcean</a></p>
<p><a target="_blank" href="https://www.udemy.com/course/nginx-fundamentals/learn/lecture/10615254#overview">NGINX Fundamentals: High Performance Servers from Scratch | Udemy</a></p>
<p><a target="_blank" href="https://www.ryadel.com/en/cache-website-nginx-fastcgi-centos-7-php-fpm/">Cache your Web Site with NGINX and FastCGI in CentOS 7 - PHP-FPM (</a><a target="_blank" href="http://ryadel.com">ryadel.com</a><a target="_blank" href="https://www.ryadel.com/en/cache-website-nginx-fastcgi-centos-7-php-fpm/">)</a></p>
]]></content:encoded></item><item><title><![CDATA[#10weeksofCloudOps - Week 3]]></title><description><![CDATA[Implement a 2-tier architecture in AWS using Terraform.]]></description><link>https://blog.melvincv.com/10weeksofcloudops-week-3</link><guid isPermaLink="true">https://blog.melvincv.com/10weeksofcloudops-week-3</guid><category><![CDATA[Terraform]]></category><category><![CDATA[10weeksofcloudops]]></category><category><![CDATA[#week3]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[github-actions]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Thu, 24 Aug 2023 08:37:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1692866180130/34230760-f765-4ea2-8c2b-999239eab28a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692258854558/335d1c89-cb25-452e-82db-16529bda4841.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-introduction">Introduction</h2>
<p>In this article, I will show you how to implement a two-tier architecture in AWS using Terraform and how to automate the deployment process using GitHub Actions.</p>
<p>A two-tier architecture consists of a web tier and a data tier, where the web tier handles the user interface and the data tier handles the data storage and processing.</p>
<p>Terraform is a tool for managing infrastructure as code, which allows you to define and provision various resources in a declarative and consistent way. GitHub Actions is a feature of GitHub that enables you to create workflows for continuous integration and continuous delivery (CI/CD) of your code.</p>
<p>By combining these two tools, you will be able to create a scalable and reliable architecture in AWS and deploy your code changes automatically. You can use these skills to create more complex and scalable architectures in AWS or other cloud providers. Let’s get started!</p>
<h2 id="heading-github-code">GitHub Code</h2>
<p><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w3">melvincv/10weeksofcloudops-w3: Implement a 2 tier architecture in AWS using Terraform (</a><a target="_blank" href="http://github.com">github.com</a><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w3">)</a></p>
<h2 id="heading-architecture">Architecture</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692865259255/02ed7156-f67f-4bce-8ab3-ed468c4d33a8.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-write-a-terraform-block-with-remote-state-storage">Write a terraform block with Remote State Storage</h2>
<p>Remote state storage in Terraform is a feature that allows you to store your Terraform state file in a remote data store instead of locally on your machine. By default, Terraform stores state locally in a file named <code>terraform.tfstate</code>. When working with Terraform in a team, use of a local file makes Terraform usage complicated because each user must make sure they always have the latest state data before running Terraform and make sure that nobody else runs Terraform at the same time. With remote state, Terraform writes the state data to a remote data store, which can then be shared between all members of a team.</p>
<p>Terraform supports storing state in various remote data stores such as Terraform Cloud, HashiCorp Consul, Amazon S3, Azure Blob Storage, Google Cloud Storage, Alibaba Cloud OSS, and more. Remote state is implemented by a backend or by Terraform Cloud, both of which you can configure in your configuration’s root module.</p>
<p>In your Git repo, Create a file called <code>main.tf</code></p>
<pre><code class="lang-json">terraform {
  required_version = <span class="hljs-attr">"&gt;= 1.4"</span>
  backend <span class="hljs-attr">"s3"</span> {
    bucket = <span class="hljs-attr">"melvincv2023-terraform-state"</span>
    key    = <span class="hljs-attr">"cloudops-w3/terraform.tfstate"</span>
    region = <span class="hljs-attr">"us-east-1"</span>
    dynamodb_table = <span class="hljs-attr">"cloudops-w3-terraform-state-lock"</span>
  }
}
</code></pre>
<ul>
<li>Create an S3 bucket to store your remote state file. For me, it is called <code>melvincv2023-terraform-state</code></li>
</ul>
<p>S3 &gt; Buckets &gt; Create bucket</p>
<p>Set a <strong>Name</strong> and <strong>Region</strong> &gt; Public Access: Off &gt; Create bucket.</p>
<ul>
<li>Create a folder (optional). I created <code>cloudops-w3</code></li>
</ul>
<p>Select the bucket &gt; Create Folder &gt; Give a name &gt; Create Folder.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692423136223/f5e2e75a-ec21-42a4-9cbe-7dc18c9d4276.png" alt class="image--center mx-auto" /></p>
<p><strong>Enable Versioning</strong> for the Bucket (following Terraform Best Practices)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692860686423/37047455-76ab-47d8-8ab5-af8767dc2aa3.png" alt class="image--center mx-auto" /></p>
<p>Click Enable &gt; Save changes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692854218649/0a34631d-9021-4ee9-a7f3-899e946ff266.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-state-file-locking">State file locking</h3>
<p>Go to DynamoDB service &gt; Tables &gt; Create</p>
<p>Give a name <code>cloudops-w3-terraform-state-lock</code> &gt; Enter <code>LockID</code> as a String</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692423374699/3d1bd796-d9ac-43c4-83e0-18835f704526.png" alt class="image--center mx-auto" /></p>
<p>Table Settings &gt; Customize settings &gt; <strong>Table Class</strong>: DynamoDB Standard &gt; <strong>Read/write capacity settings</strong>: On-demand &gt; Create Table.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692423524746/edbaa049-4d57-4005-97da-173b124f50a7.png" alt class="image--center mx-auto" /></p>
<p>Create a Dynamo DB Table.</p>
<blockquote>
<p>Note that <strong>State file locking will be commented</strong> in <code>main.tf</code> file for now.</p>
</blockquote>
<h2 id="heading-create-an-aws-provider-block">Create an AWS provider block</h2>
<p>Go to this link and click on <code>AWS</code></p>
<p><a target="_blank" href="https://registry.terraform.io/browse/providers">https://registry.terraform.io/browse/providers</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692423721985/2f29534e-9fea-4af8-bccf-8a0dbc272803.png" alt class="image--center mx-auto" /></p>
<p>Copy the provider's base code. Merge it with the <code>main.tf</code> file created earlier:</p>
<pre><code class="lang-json">terraform {
  required_version = <span class="hljs-attr">"&gt;= 1.4"</span>
  backend <span class="hljs-attr">"s3"</span> {
    bucket = <span class="hljs-attr">"melvincv2023-terraform-state"</span>
    key    = <span class="hljs-attr">"cloudops-w3/terraform.tfstate"</span>
    region = <span class="hljs-attr">"us-east-1"</span>
    dynamodb_table = <span class="hljs-attr">"cloudops-w3-terraform-state-lock"</span>
  }
  required_providers {
    aws = {
      source = <span class="hljs-attr">"hashicorp/aws"</span>
      version = <span class="hljs-attr">"5.13.1"</span>
    }
  }
}

provider <span class="hljs-string">"aws"</span> {
  # Configuration options
}
</code></pre>
<p>Go to the documentation for the aws provider...</p>
<p><a target="_blank" href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">https://registry.terraform.io/providers/hashicorp/aws/latest/docs</a></p>
<p>Add required attributes:</p>
<pre><code class="lang-json">provider <span class="hljs-string">"aws"</span> {
  # Configuration options
  region = <span class="hljs-attr">"ap-southeast-1"</span>
  profile = <span class="hljs-attr">"terraform-user-desktop"</span>
}
</code></pre>
<blockquote>
<p>Note that the line <code>profile = "terraform-user-desktop"</code> has been commented in the repo when I enabled GitOps using GitHub Actions.</p>
</blockquote>
<h2 id="heading-create-an-iam-user-for-terraform">Create an IAM user for Terraform</h2>
<p>Create an IAM user in AWS for Terraform and give it <code>AdministratorAccess</code> permission:</p>
<p>IAM &gt; Users &gt; Create User &gt; Give a name (terraform-user-desktop)</p>
<p>Attach policies directly &gt; AdministratorAccess &gt; Next &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692424578420/481e260c-1a99-41cb-aa6c-eb16eafdacb7.png" alt class="image--center mx-auto" /></p>
<p>Click the newly created user &gt; Security Credentials &gt; Create Access Key</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692424686488/e57e9ba7-9382-4766-8c8b-635dc08d0efa.png" alt class="image--center mx-auto" /></p>
<p>Click CLI &gt; Tick the option "I understand the above recommendation and want to proceed to create an access key." &gt; Next &gt; Create Access Key.</p>
<p><mark>Download and save the CSV file in a safe place</mark></p>
<h2 id="heading-create-an-aws-cli-profile">Create an AWS CLI profile</h2>
<p>An AWS CLI profile is a named set of configuration settings and credentials that you can use to interact with AWS services from the command line. Each profile consists of a set of key-value pairs that define the following settings:</p>
<ul>
<li><p><strong>AWS access key ID</strong>: The access key ID for your AWS user or role.</p>
</li>
<li><p><strong>AWS secret access key</strong>: The secret access key for your AWS user or role.</p>
</li>
<li><p><strong>AWS session token</strong>: The session token for your temporary security credentials (if applicable).</p>
</li>
<li><p><strong>AWS region</strong>: The default region for your AWS services.</p>
</li>
<li><p><strong>Output format</strong>: The default output format for your AWS CLI commands.</p>
</li>
</ul>
<p>You can create multiple profiles in your AWS CLI configuration file (<code>~/.aws/config</code>) and credentials file (<code>~/.aws/credentials</code>) to manage different sets of credentials and settings for different environments or use cases. You can also specify which profile to use when running an AWS CLI command by using the <code>--profile</code> option or setting the <code>AWS_PROFILE</code> environment variable.</p>
<p>From your local PC, <a target="_blank" href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">install the AWS CLI for your OS</a>.</p>
<p>Open a terminal and type</p>
<pre><code class="lang-json">aws configure --profile terraform-user-desktop
</code></pre>
<p>Open the CSV file and copy the Access Key ID and paste it when prompted. Do the same for the Secret Access Key.</p>
<pre><code class="lang-json">$ aws configure --profile terraform-user-desktop
AWS Access Key ID [None]: AKI*********
AWS Secret Access Key [None]: ***********
Default region name [None]: ap-southeast<span class="hljs-number">-1</span>
Default output format [None]:
</code></pre>
<p>Now Terraform will be able to use the profile <code>terraform-user-desktop</code></p>
<h2 id="heading-initialize-terraform">Initialize Terraform</h2>
<p>Save the file <code>main.tf</code> &gt; cd to the folder containing the file &gt; run <code>terraform init</code></p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">cd</span> cloudops-w3
$ terraform init

Initializing the backend...

Successfully configured the backend <span class="hljs-string">"s3"</span>! Terraform will automatically
use this backend unless the backend configuration changes.
...
</code></pre>
<h2 id="heading-create-a-vpc-module">Create a VPC Module</h2>
<p>One of the features of Terraform is the ability to use <strong>modules</strong>, which are reusable blocks of code that can be invoked from different configurations. Modules can be sourced from different locations, such as the Terraform Registry, GitHub, or local directories.</p>
<p>Local modules are useful for several reasons:</p>
<ul>
<li><p>They allow you to organize your code into smaller and more manageable units.</p>
</li>
<li><p>They enable you to reuse common functionality across multiple configurations.</p>
</li>
<li><p>They help you avoid duplication and inconsistency in your code.</p>
</li>
<li><p>They make your code more modular and maintainable.</p>
</li>
</ul>
<p>Here is the code: <a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w3/tree/main/modules/vpc">10weeksofcloudops-w3/modules/vpc at main · melvincv/10weeksofcloudops-w3 (</a><a target="_blank" href="http://github.com">github.com</a><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w3/tree/main/modules/vpc">)</a></p>
<p>We create 3 files: <code>main.tf</code> , <code>variables.tf</code> and <code>outputs.tf</code></p>
<p><code>main.tf</code> contains the resource blocks used to create the individual resources in the VPC.</p>
<p><code>variables.tf</code> contains the input variables [here, without any default values]</p>
<p><code>outputs.tf</code> contains the outputs that can be referenced in our project.</p>
<p>A <code>module</code> block is used to call the module in the <code>main.tf</code> file of our project.</p>
<p>Add a <code>.gitignoew</code> file to the repo root to exclude the <code>.terraform</code> folder and state file. The folder contains the providers and state file that may have secrets in it. So it is a good idea to exclude them before committing any code to the repo.</p>
<p>Commit the <code>.gitignore</code> file first.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Local .terraform directories</span>
**/.terraform*
</code></pre>
<h2 id="heading-project-files">Project files</h2>
<p>We will build the main project in the folder <code>cloudops-w3</code>. You may name it as you wish, but make sure that Terraform commands are run from that folder and that you have excluded the <code>.terraform</code> folder.</p>
<p>Here is the code: <a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w3/tree/main/cloudops-w3">10weeksofcloudops-w3/cloudops-w3 at main · melvincv/10weeksofcloudops-w3 (</a><a target="_blank" href="http://github.com">github.com</a><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w3/tree/main/cloudops-w3">)</a></p>
<p>Here we have the following files:</p>
<ul>
<li><p><code>cloudops-w3/main.tf</code> file contains the</p>
<ul>
<li><p>terraform block</p>
</li>
<li><p>aws provider block</p>
</li>
<li><p>module block to call the local <code>vpc</code> module</p>
</li>
</ul>
</li>
<li><p><code>cloudops-w3/variables.tf</code> file contains the input variables to the vpc module</p>
</li>
<li><p><code>cloudops-w3/terraform.tfvars</code> file contains the actual values of the variables.</p>
</li>
<li><p><code>cloudops-w3/outputs.tf</code> file contains the output values for the created resources. This will be displayed after <code>terraform apply</code> completes.</p>
</li>
<li><p><code>cloudops-w3/security-groups.tf</code> file that has all the security groups for this project.</p>
</li>
<li><p><code>cloudops-w3/ec2-instances.tf</code> file that has a AMI data source block, the <code>aws_key_pair</code> block to import my public key to ec2, <code>aws_instance</code> blocks that will create ec2 instances.</p>
</li>
<li><p><code>cloudops-w3/app-lb.tf</code> file that contains the <code>aws_lb</code> resource block to create an Application Load balancer.</p>
</li>
<li><p><code>cloudops-w3/aurora-db.tf</code> file that contains resource blocks to create a Subnet Group and an Aurora Cluster.</p>
</li>
</ul>
<p>Have a look at the repo for more!</p>
<p>Here are the different parts of a resource block:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692860129937/5215bc09-c2b7-4b91-adf5-3894eec309e1.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Resource type</strong>: The type of the infrastructure object you want to create or manage. For example, <code>aws_instance</code>, <code>google_compute_instance</code>, or <code>azurerm_virtual_machine</code>.</p>
</li>
<li><p><strong>Reference name</strong>: A unique name that you give to the resource block. This name is used to refer to the resource block from other parts of your configuration.</p>
</li>
<li><p><strong>Arguments</strong>: A set of key-value pairs that define the configuration of the resource. These arguments are specific to the resource type and determine how the infrastructure object is created or managed.</p>
</li>
<li><p><strong>Attributes</strong>: A set of values that are exposed by an existing resource. You can reference these attributes from other parts of your configuration.</p>
</li>
</ul>
<p>You may consider Arguments and Attributes to be the Input and Output values of a resource block.</p>
<p><code>main.tf</code> explained:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692860618330/679a383b-9cca-41db-b3ec-8a05ba08d2b6.png" alt class="image--center mx-auto" /></p>
<p>Run terraform commands to initialize the repo, format and validate code and apply immediately (create resources)</p>
<p>In VS Code, Rt. click the project folder and "open in integrated terminal"</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692860983408/12ec6ea6-2233-49f2-9ecc-074acb0aec9d.png" alt class="image--center mx-auto" /></p>
<p>Run the following commands:</p>
<pre><code class="lang-bash">terraform init
terraform fmt
terraform validate
terraform apply
</code></pre>
<p>Apply would succeed and you should see the outputs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692861349095/38cf6107-b325-47e1-825e-4a40c21d85b2.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692861798841/4fc4d1df-6b9c-4dc4-9867-d1ed82a65f52.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-output-resources-on-aws">Output: Resources on AWS</h2>
<p>VPC ID: <code>vpc-0fe6818101d4b8362</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692861958229/b4de1cf4-63a5-477f-8b88-903dd2084cf8.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692861981285/859ef7ba-345a-47c8-9972-a955d4ebd209.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692862034184/4fdec8cb-1989-4bee-9c4d-5308a0a45aab.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692862162521/8713c465-cadb-4f5c-8cca-e958ef52022f.png" alt class="image--center mx-auto" /></p>
<p>EC2 instances:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692861874028/8763af94-b4c5-4f88-b892-544c29ff3888.png" alt class="image--center mx-auto" /></p>
<p>App Load Balancer:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692861898159/4bcd2d0c-5f5c-46f3-a7fa-27fbeef0b887.png" alt class="image--center mx-auto" /></p>
<p>Security Groups:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692862263772/e6d5a3fb-0102-4efc-ae2b-1604a0dde428.png" alt class="image--center mx-auto" /></p>
<p>Aurora DB cluster:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692862322628/a8a84efe-51a4-42a4-a9d2-ac21d713de2e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692862352018/b5e1e164-9649-4092-bfb0-74028743310b.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-github-actions">GitHub Actions</h2>
<p>Add a GitHub Workflow:</p>
<p>Save it as <code>.github/workflows/terraform.yml</code></p>
<p>I have written another workflow to DESTROY the infra from Github itself. It will only run manually: <code>.github/workflows/terraform-destroy.yml</code></p>
<p>Add environment variables as Github Secrets:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692773078052/37bc56c5-334a-4de5-9b70-69a0773f8422.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692773213020/d33f04b2-8465-41bd-ade1-e593069f0f1e.png" alt class="image--center mx-auto" /></p>
<p>Push to the main branch or manually trigger the workflow from the Github web UI.</p>
<p>Uncommenting the line in <code>main.tf</code> to enable state file locking:</p>
<pre><code class="lang-bash">dynamodb_table = <span class="hljs-string">"cloudops-w3-terraform-state-lock"</span>
</code></pre>
<blockquote>
<p>Ensure that the DynamoDB table is created in the same region as the backend s3 bucket: <code>us-east-1</code></p>
</blockquote>
<p>Commit and push changes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692863019396/1edfe8d4-bc47-4747-a951-8c72ca894074.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692863463538/510fbb19-cfba-4678-b2e3-7f52f1ede58b.png" alt class="image--center mx-auto" /></p>
<p>Running <code>terraform destroy</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692863536605/986e2474-9dd7-48a6-a9e7-029fcc57fd00.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692863844545/90b75cfc-1884-478e-b038-845f517acbc7.png" alt class="image--center mx-auto" /></p>
<p><mark>Remember to run this from the terminal if you are following this tutorial without Github Actions to avoid incurring high charges</mark>: <code>terraform destroy</code></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to implement a two-tier architecture in AWS using Terraform and how to automate the deployment process using GitHub Actions.</p>
<p>By following this article, you gained hands-on experience with Terraform and GitHub Actions, two powerful tools for cloud infrastructure automation. You also learned some best practices for writing modular and reusable Terraform code, managing remote state files, and implementing CI/CD pipelines. You may use these skills to create more complex and scalable architectures in AWS or other cloud providers.</p>
<p>If you enjoyed reading this article and want to learn more about cloud infrastructure automation, please subscribe to my blog for more updates and tutorials. You can also connect with me on LinkedIn to share your feedback and ideas. Thank you for reading!</p>
]]></content:encoded></item><item><title><![CDATA[#10weeksofCloudOps - Week 2]]></title><description><![CDATA[Design a 3-tier architecture in AWS]]></description><link>https://blog.melvincv.com/10weeksofcloudops-week-2</link><guid isPermaLink="true">https://blog.melvincv.com/10weeksofcloudops-week-2</guid><category><![CDATA[10weeksofcloudops]]></category><category><![CDATA[AWS 3 Tier Architecture]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[github-actions]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Wed, 16 Aug 2023 09:52:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1691638848901/6ec2f557-f172-413f-835a-0754c5980afe.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692866872430/a870d478-a79b-4eb3-8cb8-1f721f99b11d.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-introduction">Introduction</h2>
<p>In the dynamic landscape of cloud computing, designing a highly available architecture is paramount to ensuring uninterrupted performance and user experience. This becomes even more crucial for modern applications like Node.js apps, where responsiveness and reliability are essential.</p>
<p>Within the intricate web of Amazon Web Services (AWS), a resilient 3-tier architecture comes to life, seamlessly integrating frontend public subnets, backend private subnets, and Aurora DB private subnets. This design ensures secure data handling, efficient traffic management, and continuous availability for Node.js applications.</p>
<h1 id="heading-architecture">Architecture</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692180439630/bc0cc89b-3b51-40aa-bc13-5cf72ec49fb5.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-github-repo">GitHub Repo</h2>
<p><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w2">melvincv/10weeksofcloudops-w2: #10weeksofcloudops challenge - Week 2 (</a><a target="_blank" href="http://github.com">github.com</a><a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w2">)</a></p>
<h1 id="heading-procedure">Procedure</h1>
<h2 id="heading-create-an-s3-bucket">Create an S3 Bucket</h2>
<p>Got to the <strong>S3 service</strong> &gt; Buckets &gt; Create Bucket.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691639549441/08b71e5e-59b8-4712-a2bb-a62680e838fd.png" alt class="image--center mx-auto" /></p>
<p>Block Public Access should be on.</p>
<p>Click <strong>Create Bucket</strong></p>
<h2 id="heading-create-an-iam-role">Create an IAM Role</h2>
<p>Go to the IAM service &gt; Roles &gt; Create role</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691639737281/fe01e557-c7c6-4acc-af0e-992890a08343.png" alt class="image--center mx-auto" /></p>
<p>Next &gt; Add Permissions to the Role:</p>
<ul>
<li><p><strong>AmazonSSMManagedInstanceCore</strong></p>
</li>
<li><p><strong>AmazonS3ReadOnlyAccess</strong></p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691639786530/b3c20873-28a4-46bf-97a7-8d9638506734.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691639842052/16fd3510-11ff-4c9c-8e46-227ab6f0afa9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691639901734/c6c984dd-17a6-4394-9a2f-18906c7f4697.png" alt class="image--center mx-auto" /></p>
<p>Verify that the correct permissions are added:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691639932091/76a3586b-6c52-4141-9ac8-3bd248cd0481.png" alt class="image--center mx-auto" /></p>
<p>Click <strong>Create Role</strong></p>
<h2 id="heading-create-a-custom-vpc">Create a Custom VPC</h2>
<p>Go to the 'VPC' service and select a region of your choice.</p>
<p>Create VPC &gt; Name: cloudops-week2</p>
<p>CIDR Block: 10.0.0.0/16</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640126574/3ae89ea6-bd18-4aae-a4fc-f76e371040ac.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640191020/36eb1e76-09af-49dd-8738-30cd9912ddbf.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-public-and-private-subnets">Create public and private subnets</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691467570414/ad879a0a-921a-40cd-9a4e-c14b907a434c.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>The first pair of subnets, <em>Public /</em> <strong><em>Web</em></strong>, will be accessible from the Internet and contain web tier ec2 instances, load balancers and NAT gateways.</p>
</li>
<li><p>The <strong><em>App</em></strong> pair of subnets will contain app tier ec2 instances containing a nodejs backend app.</p>
</li>
<li><p>The <em>Data /</em> <strong><em>DB</em></strong> pair of subnets will hold your active/passive Aurora database.</p>
</li>
</ul>
<p>VPC &gt; Subnets &gt; Create Subnet &gt; Select VPC</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640359258/710967da-4ea6-4da1-9c9c-ab8c725dfc5d.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640689203/af2922ba-37d4-42e6-a901-3fdcaf1d732a.png" alt class="image--center mx-auto" /></p>
<p>Create 6 subnets:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Sl.No.</td><td>Subnet Name</td><td>Availability Zone</td><td>CIDR Value</td></tr>
</thead>
<tbody>
<tr>
<td>1.</td><td>web-public-1a</td><td>ap-southeast-1a</td><td><strong>10.0.0.0</strong>/24</td></tr>
<tr>
<td>2.</td><td>web-public-1b</td><td>ap-southeast-1b</td><td>10.0.1.0/24</td></tr>
<tr>
<td>3.</td><td>app-private-1a</td><td>ap-southeast-1a</td><td>10.0.2.0/24</td></tr>
<tr>
<td>4.</td><td>app-private-1b</td><td>ap-southeast-1b</td><td>10.0.3.0/24</td></tr>
<tr>
<td>5.</td><td>db-private-1a</td><td>ap-southeast-1a</td><td>10.0.4.0/24</td></tr>
<tr>
<td>6.</td><td>db-private-1b</td><td>ap-southeast-1b</td><td>10.0.5.0/24</td></tr>
</tbody>
</table>
</div><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640733109/f9e30e65-01c9-453c-8fe1-3a297ee60795.png" alt class="image--center mx-auto" /></p>
<p>Click <strong>Create Subnet</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640835399/fae68c12-93a0-48f6-97bf-4a37d7f4dbce.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-an-internet-gateway">Create an Internet Gateway</h3>
<p>To give the web subnets in our VPC Internet access we need to create and attach an Internet Gateway.</p>
<p>VPC &gt; Internet Gateways &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640950325/25f64ac3-c372-4f6a-865d-64c8707c19d6.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691640989938/955aed62-eff6-4bda-bad0-7017cc2de405.png" alt class="image--center mx-auto" /></p>
<p>Attach to the VPC</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645150042/3541594f-2903-49de-b759-89b9d16b76b5.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645172693/d2396bf7-fbef-4ba6-8e9c-677627639ddf.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-nat-gateways-in-public-subnets">Create NAT Gateways in Public Subnets</h3>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p>For our instances in the <strong>App</strong> layer private subnet to be able to access the Internet their traffic will need to go through a NAT Gateway. For high availability, you’ll deploy one NAT gateway in each of your <strong>public</strong> subnets.</p>
<p>Go to VPC &gt; NAT Gateways &gt; Create</p>
<p>Name them:</p>
<ul>
<li><p>NAT GW A</p>
</li>
<li><p>NAT GW B</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645349023/11901896-2203-4eb2-ae22-fbfb78c376d3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645393545/6a418a9a-b3ac-49f6-83f9-b739648cd1f0.png" alt class="image--center mx-auto" /></p>
<p>Click: <strong>Create NAT Gateway</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645463310/147d2e8f-5bdd-421e-a860-11d34d0dc792.png" alt class="image--center mx-auto" /></p>
<p>Click: <strong>Create NAT Gateway</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645928492/5d8becb3-435e-4855-a61d-53522c9f2cc6.png" alt class="image--center mx-auto" /></p>
<p>If you go to VPC &gt; Elastic IPs, you can see that there are 2 new elastic IPs with association ID's.</p>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691645910922/c9242255-25f4-40d4-9c23-217daf25251f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-route-tables">Create Route Tables</h3>
<p>Go to VPC &gt; Route Tables &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646015348/b2960353-dccc-4314-91ce-93d3e1550a99.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646087245/0e3f2637-f330-4bd2-9833-7beb430c55fe.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646111671/8493e86e-ad33-4ffc-916b-52db871eec48.png" alt class="image--center mx-auto" /></p>
<p>Add a Route for 0.0.0.0/0 (All traffic except local VPC traffic) to the Internet Gateway we created earlier.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646193392/61428dae-90f3-43ea-8fbe-f5b1d3b16dc2.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646215844/5fd069ef-2ea4-4b0f-a0ae-98850e7fe393.png" alt class="image--center mx-auto" /></p>
<p>Edit Subnet Associations and add the 2 public web subnets.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646282423/7b7ff20c-8591-481e-ae0f-557793919af4.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646308299/a8100ca5-5edd-4f35-8f7c-2f22258f75ac.png" alt class="image--center mx-auto" /></p>
<p>Create 2 more Route Tables to route Internet traffic from the APP Subnets to the respective NAT Gateways in each Zone.</p>
<ul>
<li><code>private-app-rt-1a</code></li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646526905/a1da8a49-e9f6-4604-9541-636cec39ed35.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646639569/9aa733ab-da88-42cb-8590-f3612d8a8613.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646672844/aa4ab94b-96bd-49fb-a482-6acebfe58864.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646905287/67cb36b0-09f5-4511-bdac-08a634d86622.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646930388/eb89a910-103a-4cff-8da5-e3315b788426.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646960098/26380477-24a1-4a92-b797-c6127915eaf1.png" alt class="image--center mx-auto" /></p>
<ul>
<li>Similarly, route <code>private-app-rt-1b</code> to <code>NAT GW B</code></li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646572398/bc631b4e-47a9-4f55-af59-889f3bdad203.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646716720/4284a27a-cc25-40a9-a9a2-e76665ed5761.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646739057/fb2dc04d-f65f-4193-b553-f4d72c5d86b5.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646812646/5d8e7fe3-85e8-4ffa-ae85-c50dfc922827.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646844321/38e482d6-2a99-451a-80f2-e7c895c9e32a.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691646874109/c47b12d7-1f0b-420a-b059-596142b68eb0.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-security-groups-sg">Create Security Groups (SG)</h3>
<p>Go to VPC &gt; Security Groups &gt; Create</p>
<ul>
<li>(SG 1) Create an SG named <code>cloudops-w2-alb-sg</code> for the Internet-facing Application Load Balancer</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691647092815/792d4897-c51c-4c04-b97e-8d0406d44481.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691647158152/5b97a9fa-990e-4ab6-a85d-7c6e0d344c7b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691647264553/48ebb52f-d62f-4f8a-9473-65509a1c9304.png" alt class="image--center mx-auto" /></p>
<p>Click <strong>Create Security Group</strong></p>
<p>Copy the ID of the SG to use later</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691647388400/3014a80a-3079-442b-974a-293579ee8d26.png" alt class="image--center mx-auto" /></p>
<ul>
<li>(SG 2) Create a new SG named <code>cloudops-w2-web-sg</code> for the web tier ec2 instances. Add an inbound rule that allows HTTP traffic from your internet-facing load balancer security group you created in the previous step.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691647633507/a3884fcd-afc5-4bbf-807a-527cae0ff6a7.png" alt class="image--center mx-auto" /></p>
<p>Also add a rule that allows HTTP traffic from your IP.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691647736246/fc6aea9f-0888-4cad-a989-72154febf0f1.png" alt class="image--center mx-auto" /></p>
<ul>
<li>(SG 3) Create a new SG named <code>cloudops-w2-int-alb-sg</code> for the internal load balancer. Add an inbound rule that allows HTTP traffic from your public instance SG. This will allow traffic from Web tier instances to hit the internal load balancer.</li>
</ul>
<p>Copy the ID of <code>cloudops-w2-web-sg</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691648070947/9b961da8-813a-41f0-8da4-efc8109e206c.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>(SG 4) Create a new SG named <code>cloudops-w2-private-ec2-sg</code> for the private ec2 instances (backend).</p>
</li>
<li><p>Add an inbound rule that allows TCP traffic on port 4000 from the internal load balancer SG <code>cloudops-w2-int-alb-sg</code></p>
</li>
<li><p>Also add an inbound rule that allows TCP traffic on port 4000 from your IP for testing.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691648392567/9aecbd2d-fbbf-438e-8e4c-9c591e057904.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691648454683/948c1b3b-4516-4ac9-8b06-525c95359730.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>(SG 5) Create a new SG named <code>cloudops-w2-db-sg</code> to protect our private database instances.</p>
</li>
<li><p>Add an inbound rule that allows traffic from the private instance SG to the MySQL port 3306.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691648731133/aa5fdf97-944f-4279-a9e7-b46e5f5cb330.png" alt class="image--center mx-auto" /></p>
<p>Verify SG creation</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691648890163/029b957e-44b2-43c4-a44f-7c563b24a4b0.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-create-aurora-database">Create Aurora Database</h2>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<h3 id="heading-create-a-subnet-group">Create a Subnet Group</h3>
<p>Go to <strong>RDS</strong> service &gt; Subnet Groups &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691730915293/d4ed56f5-0016-4091-b7e1-656b48f2b90f.png" alt class="image--center mx-auto" /></p>
<p>Select the AZ's and your DB Subnets in each AZ.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691730971515/dbb798b0-e763-45c3-9028-67e792a8cf6a.png" alt class="image--center mx-auto" /></p>
<p>Click Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691730997929/6f6cf736-b892-4b51-a8fd-db77441cd226.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-an-aurora-database-instance">Create an Aurora Database instance</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731048502/b6fb10da-0d84-46c1-80b1-b253fae39940.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731093612/73a79ba9-eb85-448d-82d8-7b837296b20d.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731185079/d18e31bc-0d4c-45f0-915b-f60f1fb7a786.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731205577/f6a691e1-371d-4966-8711-bee2a042dd26.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731272249/ce7b71e9-8e8a-4f44-8d13-3e951ef4815b.png" alt class="image--center mx-auto" /></p>
<p>Connectivity section:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731324009/df41da6f-f103-4962-838a-2cb1c847804f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731368566/2bfbb75a-0919-4516-b1b9-d1a072173a65.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731386208/a3dfc981-59a2-4ec3-86e0-9856ceb8bf57.png" alt class="image--center mx-auto" /></p>
<p>Click <strong>Create Database</strong>.</p>
<p>Wait for 5 min for the Aurora Cluster creation...</p>
<p>Click: <strong>View Credentials</strong> and copy the DB Credentials.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691731577976/73bf4594-4fe9-434f-97a1-e38a5a1065a7.png" alt class="image--center mx-auto" /></p>
<p>When your database is provisioned, you should see a reader and writer instance in the database subnets of each availability zone. Note down the writer endpoint for your database for later use.</p>
<p>Select the database cluster &gt; Copy the endpoint of the Writer instance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691732724497/66d7d2c0-5d86-4c73-abf6-cc8c1b5bc790.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">cloudops-w2-db.cluster-cf6xjg8izaoi.ap-southeast-1.rds.amazonaws.com
</code></pre>
<h2 id="heading-app-tier-instances">App tier instances</h2>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p>Create an EC2 instance for our app layer and make all necessary software configurations so that the app can run. The app layer consists of a Node.js application that will run on port 4000. We will also configure our database with some data and tables.</p>
<h2 id="heading-app-instance">App instance</h2>
<p>Go to the EC2 service &gt; Instances &gt; Launch instance.</p>
<p>Give a Name tag: <code>cloudops-w2-app</code> and tag instances, volumes and network interfaces.</p>
<p>Choose the Amazon Linux 2 AMI at the top for 64-bit architecture.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733004568/3a923da2-5aba-4e1e-a811-f82263e988d7.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733087131/99b63661-2dbf-4b99-81a3-c4e6efc1cc62.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733128263/10b2b311-f936-4616-bc1c-c5d3039f00b9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733163022/aa983433-0acd-4d4c-8bed-ad92252829ca.png" alt class="image--center mx-auto" /></p>
<p>Save the PEM file securely.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733200835/44b767c1-00b8-4d72-9ee6-ebc301cb8fe5.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733334632/ade4897a-53f9-4c7b-a3fe-d260ac41a798.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733347541/dea8e67f-3246-488c-a6f5-9c632e910856.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733393066/75684918-50a2-4992-aa8a-49441056d40b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733414110/fa64f171-9a98-4261-b0f4-927e5ffb2c03.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733434254/89b33179-6f23-42a5-9b8a-c1e0b44c5339.png" alt class="image--right mx-auto mr-0" /></p>
<h3 id="heading-connect-to-the-instance-using-session-manager">Connect to the instance using Session Manager</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691733583325/7dbf61b8-f3a2-4244-85bb-760012517e5f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691738310066/20095128-e928-4ca3-8ad9-24790ed11780.png" alt class="image--center mx-auto" /></p>
<p>you will be logged in as ssm-user which is the default user. Switch to ec2-user</p>
<pre><code class="lang-bash">sudo su - ec2-user
</code></pre>
<p>I did not like using this terminal. I use it only for account recovery. Instead of typing commands here, I would deploy a bastion host as below. But it is optional and you may continue with Session manager.</p>
<h2 id="heading-optional-deploy-a-bastion-host-instance-in-a-public-subnet">(Optional) Deploy a Bastion Host instance in a Public Subnet</h2>
<p>Launch Instance &gt;</p>
<ul>
<li><p>Name: cloudops-w2-bastion</p>
</li>
<li><p>AMI: Amazon Linux 2023</p>
</li>
<li><p>Arch: 64 bit</p>
</li>
<li><p>Type: t2.micro</p>
</li>
<li><p>Key Pair: cloudops-w2</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691736222208/6cf5d251-7b42-4dc0-b9d7-3316577eabb3.png" alt class="image--center mx-auto" /></p>
<p>Inbound Rules &gt; Leave the default SSH rule as is.</p>
<p>Launch instance.</p>
<p>Log in to the bastion host:</p>
<p>(Using Git Bash on Windows 11)</p>
<pre><code class="lang-bash">ssh -i <span class="hljs-string">"G:\My Drive\vault\aws\cloudops-w2.pem"</span> ec2-user@13.212.4.194
</code></pre>
<p>Log in success. Now create an OpenSSH client config and save it to <code>~/.ssh/config</code></p>
<pre><code class="lang-bash">Host cloudops-w2-bastion
    HostName 13.212.4.194
    User ec2-user
    IdentityFile <span class="hljs-string">"G:\My Drive\vault\aws\cloudops-w2.pem"</span>
    ForwardAgent yes
    ServerAliveInterval 60
    ServerAliveCountMax 10
</code></pre>
<ul>
<li><p>Start the SSH Agent in Git Bash</p>
</li>
<li><p>add the private key (pem file) to the agent</p>
</li>
<li><p>connect to the bastion</p>
</li>
<li><p>connect to the app instance from the bastion using it's private IP</p>
</li>
</ul>
<pre><code class="lang-bash"><span class="hljs-built_in">eval</span> $(ssh-agent -s)
ssh-add <span class="hljs-string">"G:\My Drive\vault\aws\cloudops-w2.pem"</span>
ssh cloudops-w2-bastion
</code></pre>
<p>Modify the SG of the App instance to allow SSH traffic from the Private IP of the bastion instance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691737188439/8069539b-ff7f-4672-893a-5370df236eb9.png" alt class="image--center mx-auto" /></p>
<p>Save Rules.</p>
<p>Try to connect again:</p>
<pre><code class="lang-bash">$ ssh ec2-user@10.0.2.223
</code></pre>
<p>This time the connection is OK.</p>
<p>List running services to check if the AWS ssm-agent is running (optional)</p>
<pre><code class="lang-bash">$ sudo systemctl --<span class="hljs-built_in">type</span>=service --state=running
  UNIT                            LOAD   ACTIVE SUB     DESCRIPTION
  amazon-ssm-agent.service        loaded active running amazon-ssm-agent
</code></pre>
<h2 id="heading-app-tier-instance-configuration">App tier instance configuration</h2>
<p>Search for and Install the mariadb client [as the mysql client is no longer there]</p>
<pre><code class="lang-bash">sudo yum search mariadb
sudo yum install -y mariadb105
</code></pre>
<p>Launch the mariadb client and connect to the Aurora RDS DB:</p>
<pre><code class="lang-bash">[ec2-user@ip-10-0-2-223 ~]$ mysql -h cloudops-w2-db.cluster-cf6xjg8izaoi.ap-southeast-1.rds.amazonaws.com -u melvincv -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 701
Server version: 5.7.12 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type <span class="hljs-string">'help;'</span> or <span class="hljs-string">'\h'</span> <span class="hljs-keyword">for</span> <span class="hljs-built_in">help</span>. Type <span class="hljs-string">'\c'</span> to clear the current input statement.

MySQL [(none)]&gt;
</code></pre>
<p>Create a Database and a Table within it:</p>
<pre><code class="lang-bash">MySQL [(none)]&gt; CREATE DATABASE webappdb;
Query OK, 1 row affected (0.015 sec)

MySQL [(none)]&gt; SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| webappdb           |
+--------------------+
5 rows <span class="hljs-keyword">in</span> <span class="hljs-built_in">set</span> (0.002 sec)

MySQL [(none)]&gt; USE webappdb;
Database changed
MySQL [webappdb]&gt; CREATE TABLE IF NOT EXISTS transactions(id INT NOT NULL
    -&gt; AUTO_INCREMENT, amount DECIMAL(10,2), description
    -&gt; VARCHAR(100), PRIMARY KEY(id));
Query OK, 0 rows affected (0.049 sec)

MySQL [webappdb]&gt; SHOW TABLES;
+--------------------+
| Tables_in_webappdb |
+--------------------+
| transactions       |
+--------------------+
1 row <span class="hljs-keyword">in</span> <span class="hljs-built_in">set</span> (0.001 sec)

MySQL [webappdb]&gt; INSERT INTO transactions (amount,description) VALUES (<span class="hljs-string">'400'</span>,<span class="hljs-string">'groceries'</span>);
Query OK, 1 row affected (0.009 sec)

MySQL [webappdb]&gt; SELECT * FROM transactions;
+----+--------+-------------+
| id | amount | description |
+----+--------+-------------+
|  1 | 400.00 | groceries   |
+----+--------+-------------+
1 row <span class="hljs-keyword">in</span> <span class="hljs-built_in">set</span> (0.010 sec)

MySQL [webappdb]&gt;
</code></pre>
<p>Create a DB User and grant all permissions on the <code>transactions</code> DB to it:</p>
<pre><code class="lang-bash">MySQL [webappdb]&gt; CREATE USER <span class="hljs-string">'melvin'</span>@<span class="hljs-string">'%'</span> IDENTIFIED BY <span class="hljs-string">'RZe=urGbp4&lt;-"F4T'</span>;
Query OK, 0 rows affected (0.013 sec)

MySQL [webappdb]&gt; GRANT ALL ON transactions.* TO <span class="hljs-string">'melvin'</span>@<span class="hljs-string">'%'</span>;
Query OK, 0 rows affected (0.013 sec)

MySQL [webappdb]&gt; SELECT User,Host FROM mysql.user;
+-----------+-----------+
| User      | Host      |
+-----------+-----------+
| melvin    | %         |
| melvincv  | %         |
| mysql.sys | localhost |
| rdsadmin  | localhost |
+-----------+-----------+
4 rows <span class="hljs-keyword">in</span> <span class="hljs-built_in">set</span> (0.001 sec)

MySQL [webappdb]&gt; \q
Bye
</code></pre>
<h3 id="heading-git-repo-and-code">Git Repo and Code</h3>
<p>Edit the below file in the git repo using a code editor and fill in the Aurora DB details:</p>
<p><code>application-code/app-tier/DbConfig.js</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691821548310/86269bc4-6151-4eaf-9d43-8fdd931ed76d.png" alt class="image--center mx-auto" /></p>
<p>Copy the repo code to your S3 bucket.</p>
<p>From the repo root folder,</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> application-code
aws s3 cp . s3://melvincv2023-cloudops-w2 --recursive
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691820574533/907fae7a-2e8f-46a5-b0b9-6aa7663f0af7.png" alt class="image--center mx-auto" /></p>
<p>install NVM</p>
<pre><code class="lang-bash">curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
<span class="hljs-built_in">source</span> ~/.bashrc
</code></pre>
<p>Install a compatible version of nodejs and use it</p>
<pre><code class="lang-bash">nvm install 16
nvm use 16
</code></pre>
<p>PM2 is a daemon process manager that will keep our node.js app running when we exit the instance or if it is rebooted. Install that as well.</p>
<pre><code class="lang-bash">npm install -g pm2
</code></pre>
<p>Download our code from our s3 buckets onto our instance.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~
aws s3 cp s3://melvincv2023-cloudops-w2/app-tier/ app-tier --recursive
</code></pre>
<p>Install dependencies, and start the app with pm2.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~/app-tier
npm install
pm2 start index.js
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691820993037/e7f2f77f-e8d8-44ef-b7ba-31c0d22fb26a.png" alt class="image--center mx-auto" /></p>
<p>Make sure the app is running corectly:</p>
<pre><code class="lang-bash">pm2 list
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691821725369/35db86ce-ee30-4c43-9367-2bf8cf118ca8.png" alt class="image--center mx-auto" /></p>
<p>To start our app at boot even if the server crashes or reboots:</p>
<pre><code class="lang-bash">pm2 startup
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691821812443/60d2ff67-72af-477b-9d1b-2d9c03438aa3.png" alt class="image--center mx-auto" /></p>
<p>save the current list of node processes:</p>
<pre><code class="lang-bash">pm2 save
</code></pre>
<h3 id="heading-testing">Testing</h3>
<p>This is our simple health check endpoint that tells us if the app is simply running.</p>
<pre><code class="lang-bash">curl http://localhost:4000/health
</code></pre>
<p>The response should looks like the following:</p>
<pre><code class="lang-bash"><span class="hljs-string">"This is the health check"</span>
</code></pre>
<p>Next, test your database connection. You can do that by hitting the following endpoint locally:</p>
<pre><code class="lang-bash">curl http://localhost:4000/transaction
</code></pre>
<p>You should see a response containing the test data we added earlier:</p>
<pre><code class="lang-bash">{<span class="hljs-string">"result"</span>:[{<span class="hljs-string">"id"</span>:1,<span class="hljs-string">"amount"</span>:400,<span class="hljs-string">"description"</span>:<span class="hljs-string">"groceries"</span>}]}
</code></pre>
<p>If you see both of these responses, then your networking, security, database and app configurations are correct.</p>
<h2 id="heading-internal-load-balancing">Internal Load Balancing</h2>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p>An <strong>internal load balancer</strong> is a type of load balancer that distributes incoming network traffic to backend resources, such as Amazon EC2 instances, within a Virtual Private Cloud (VPC) network. Unlike external load balancers, which are accessible from the internet, internal load balancers are designed to handle traffic within the boundaries of a VPC and are not directly accessible from the public internet.</p>
<h3 id="heading-create-amazon-machine-image-ami">Create **Amazon Machine Image (**AMI)</h3>
<p>An <strong>Amazon Machine Image (AMI)</strong> is a pre-configured virtual machine image used as a template to create new instances (virtual servers) in Amazon Web Services (AWS). An AMI includes the operating system, application software, and any additional configurations necessary to launch instances with specific characteristics.</p>
<p>Create an AMI of the App tier instance to implement AutoScaling using an Internal App Load balancer.</p>
<p>EC2 &gt; Instances &gt; Rt.Click App instance</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823489505/7cbd3b14-b427-4807-b60c-ce179574016d.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823546492/850fd922-6525-47c5-9402-5b67df96f058.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823580246/8aac147b-49a9-45a3-abc7-64b9eb769a72.png" alt class="image--center mx-auto" /></p>
<p>Click: Create Image</p>
<h3 id="heading-create-a-target-group">Create a Target Group</h3>
<p>Create a target group for the internal load balancer.</p>
<p>A <strong>Target Group</strong> is a logical grouping of targets, which are typically instances or IP addresses that receive incoming traffic from the load balancer. The load balancer uses the target group to determine where to direct incoming requests. It plays a crucial role in routing traffic to healthy instances while also allowing you to manage the distribution of traffic based on different rules and conditions.</p>
<p>EC2 &gt; Target Groups &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823751446/5f34e362-ed69-41cc-b77f-6c05c4afd43d.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823837762/f9a5a946-4589-4b40-87ae-60d4b621f377.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823855402/068fb1f8-077c-4a62-aa17-e41d26d61ca7.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p>Do NOT register any targets for now.</p>
<p>Click: <strong>Create Target Group</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691823928997/81969da1-1be1-42bf-a178-0bebc35d31f4.png" alt class="image--center mx-auto" /></p>
<p>EC2 &gt; Load Balancers &gt; Create load balancer</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691824006259/4ce875b3-c0ea-4315-9df9-f5dba5b6719f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691824118257/c5ca6ad3-6915-41e3-929b-b64640ec358b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691824155777/10c72a9c-0696-4608-b68a-6e329cc0ce98.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691824172366/a45eba16-8a52-490b-98b1-7fb600fae61b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691824191747/adfabc72-ce87-4694-8881-4f713322d3df.png" alt class="image--center mx-auto" /></p>
<p>Click: Create Load Balancer</p>
<h3 id="heading-create-a-launch-template">Create a Launch Template</h3>
<p>Before we configure Auto Scaling, we need to create a Launch template with the AMI we created earlier.</p>
<p>A <strong>launch template</strong> is a resource that defines the configuration for launching instances (virtual servers). It provides a convenient way to specify the various settings needed to create and launch instances consistently, including the Amazon Machine Image (AMI), instance type, networking options, security groups, storage configurations, and more.</p>
<p>EC2 &gt; Launch Templates &gt; Create</p>
<ul>
<li><p>Name the Launch Template</p>
</li>
<li><p>Select the App Tier AMI</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691825306277/b5a11522-b040-43c1-92f3-5fa311b1f2b7.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691825341237/d9873827-c48a-461d-96ac-bce30500ecf7.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Instance Type: t2.micro</p>
</li>
<li><p>Key pair: Don't include</p>
</li>
<li><p>Network Settings: Don't include</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691825374831/49546a61-e0ff-42e6-a391-b6c987aa5cbc.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691825450754/b4bcd599-9b2c-4fab-9ebe-4b67b4c42a3f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691825502903/96fdca94-37f6-4577-a5de-9aaa69581dbd.png" alt class="image--center mx-auto" /></p>
<p>User Data &gt; Add the below script</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">cd</span> ~
aws s3 sync s3://melvincv2023-cloudops-w2/app-tier/ app-tier
</code></pre>
<p>Click: <strong>Create Launch Template</strong></p>
<h3 id="heading-create-auto-scaling-group">Create Auto Scaling Group</h3>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p>An <strong>Auto Scaling group</strong> is a key feature of Amazon Web Services (AWS) that enables you to automatically scale the number of instances in a group based on demand. It helps ensure that your application can handle varying workloads and maintains availability and performance by dynamically adjusting the number of instances up or down as needed.</p>
<p>EC2 service &gt; Auto Scaling groups &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826321290/d5bfe68c-75bd-4665-afbd-bfbe63d98f5e.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826371804/66a137c0-6cb3-40c9-a59b-752e0e4f6877.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826460505/d0c5e2b6-2afd-4574-96e5-5fe9e67404ad.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826482492/11db5ead-ed38-4653-9e87-0d04ae46c65b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826536818/516b978d-3f83-40cf-8e13-dcf7b8bf539d.png" alt class="image--center mx-auto" /></p>
<p>Optional: Add a 'Target Scaling Policy to scale up if a certain no. of requests hit the internal load balancer:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826683480/fe55b97b-0adf-48a6-95be-0876897b664d.png" alt class="image--center mx-auto" /></p>
<p><strong>How to set the right Target Value?</strong></p>
<ol>
<li><p><strong>Observability and Monitoring</strong>: Use AWS CloudWatch or other monitoring tools to track metrics related to the ALB and the instances. This data can provide insights into request patterns and help you set appropriate target values.</p>
</li>
<li><p><strong>Iterative Approach</strong>: Start with a conservative target value and monitor your application's performance. Gradually adjust the target value based on observed behavior and performance metrics.</p>
</li>
</ol>
<p>Add Notifications if needed &gt; Add Tags</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826899719/1dfa1e59-987d-4c2a-b70f-72d6113841e8.png" alt class="image--center mx-auto" /></p>
<p>Skip to Review &gt; Create ASG</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691826785713/338ff01f-f77d-4af2-b79e-3f6ec36dc00d.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-create-web-tier-instances">Create Web Tier instances</h2>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<h3 id="heading-edit-nginx-config">Edit nginx config</h3>
<p>From the Repo root, go to <code>app-code/nginx.conf</code> and edit line 58 to include the DNS name of the Internal load balancer we created earlier.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692076585740/8a1d663a-e914-460d-93dd-36625b0d2c66.png" alt class="image--center mx-auto" /></p>
<p>Commit and upload <code>nginx.conf</code> and <code>web-tier</code> folder to the S3 bucket.</p>
<h3 id="heading-create-an-ec2-instance-for-the-web-tier">Create an EC2 instance for the web tier</h3>
<p>EC2 &gt; Create instance &gt; Name: cloudops-w2-web &gt; Type: t2.micro &gt; Select Key Pair <code>cloudops-w2</code> &gt; Network Settings:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692076820739/bdc3b076-8dc9-4c29-a103-2b265ffb6cf9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692076891532/18923f2e-4287-4123-9f82-f7714290dd67.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692076905818/99bc1ae7-f7a2-43e1-be75-019e69d49b11.png" alt class="image--center mx-auto" /></p>
<p>Launch instance.</p>
<h3 id="heading-connect-to-the-instance">Connect to the instance</h3>
<p>Add this to <code>~/.ssh/config</code></p>
<pre><code class="lang-bash">Host cloudops-w2-web
    HostName 13.212.149.128
    User ec2-user
    IdentityFile <span class="hljs-string">"cloudops-w2.pem"</span>
    ForwardAgent no
    ServerAliveInterval 60
    ServerAliveCountMax 10
</code></pre>
<p>Add an Inbound Rule to the Security Group of the Web instance that allows SSH from your IP: <code>cloudops-w2-web-sg</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692077304488/8c2d3510-464e-45a4-b580-17e16f6cc2a8.png" alt class="image--center mx-auto" /></p>
<p>Connect using openssh</p>
<pre><code class="lang-bash">ssh cloudops-w2-web
</code></pre>
<h3 id="heading-set-up-the-web-instance">Set up the Web instance</h3>
<p>Install npm and node 16.</p>
<pre><code class="lang-bash">curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
<span class="hljs-built_in">source</span> ~/.bashrc
nvm install 16
nvm use 16
</code></pre>
<p>Copy the web tier code from our S3 bucket.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~/
aws s3 cp s3://melvincv2023-cloudops-w2/web-tier/ web-tier --recursive
</code></pre>
<p>Create the build folder for the react app by building it.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ~/web-tier
npm install 
npm run build
</code></pre>
<p>Install nginx...</p>
<pre><code class="lang-bash">sudo yum install -y nginx
</code></pre>
<p>Replace <code>nginx.conf</code> on the instance with our edited one from the S3 bucket.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> /etc/nginx
sudo rm nginx.conf
sudo aws s3 cp s3://melvincv2023-cloudops-w2/nginx.conf .
</code></pre>
<p>Restart NGINX, see that nginx has permissions to access our files and start it on boot.</p>
<pre><code class="lang-bash">sudo service nginx restart
chmod -R 755 /home/ec2-user
sudo chkconfig nginx on
</code></pre>
<p>The demo website would now be available when you enter the IP address of the Web instance:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692078454294/3e3eb80c-7beb-4211-b709-0816897c3320.png" alt class="image--center mx-auto" /></p>
<p>Create an AMI of the Web instance, similar to that of the App tier...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079048475/bae31608-0537-4dcb-a21f-f44ee26e9969.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079091038/a54b6a46-2dd9-455d-8824-38387f399f49.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079132445/d17e5377-4783-4554-bf67-771de9fb5dd9.png" alt class="image--center mx-auto" /></p>
<p>Create Image.</p>
<h3 id="heading-create-a-target-group-1">Create a Target Group</h3>
<p>For balancing the load across the public Web instances.</p>
<p>EC2 &gt; Target Groups &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079262120/b4f8ff7c-1dc2-4a71-9543-5849456fbb8d.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079318485/e1ffc7c4-0861-44b9-a58d-cdff1a20953c.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079343511/90fa6938-bd33-4c4e-bd3e-c4f351f51524.png" alt class="image--center mx-auto" /></p>
<p>Next &gt; Create Target Group.</p>
<h3 id="heading-create-a-public-load-balancer">Create a Public Load Balancer</h3>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p>EC2 &gt; Load Balancers &gt; Create</p>
<p>Select <code>Application Load Balancer</code> &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079484871/bf412180-9e98-42e9-bf3c-a55c3c133bd3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079519862/1fe96017-f86d-41e0-9b55-f17678dbf52e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079540164/47561e33-2def-4380-bce7-04db9c9fa51c.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079564171/f753aece-6981-4bc8-bbd5-e555c584b976.png" alt class="image--center mx-auto" /></p>
<p>Create Load Balancer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692079679797/4db322cc-aabb-4a3e-90fc-6cbbe81556f1.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-launch-template">Create Launch Template</h3>
<p>Create a launch template for use in Auto Scaling.</p>
<p>EC2 &gt; Launch Templates &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080141567/844d1930-5f56-42b1-904c-292c07e7e75a.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080161831/3c95f9df-34f3-4615-860c-7da22c984243.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080183763/11fa2948-b8b0-4d7c-928a-13987cc0e861.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080195240/43d1bcd6-13da-4d49-8110-0f6670358d93.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080245625/42ce00d9-77a4-4d25-bc05-cb3f2b8874de.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080262908/3ab46228-f87b-4e15-a383-1aa8e8426807.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080275252/904ccdc9-84c0-443d-b76c-fcec50c7351f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080411462/90590355-b094-46ff-8ff4-fbbe6eac7a15.png" alt class="image--center mx-auto" /></p>
<p>User Data &gt; Add the below script:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">cd</span> ~
aws s3 sync s3://melvincv2023-cloudops-w2/web-tier/ web-tier
sudo aws s3 cp s3://melvincv2023-cloudops-w2/nginx.conf /etc/nginx
sudo systemctl reload nginx
</code></pre>
<p>Create Launch Template.</p>
<h3 id="heading-create-auto-scaling-group-1">Create Auto Scaling Group</h3>
<p><mark>DELETE AFTER USE TO AVOID HIGH CHARGES</mark></p>
<p>EC2 &gt; Auto Scaling Groups &gt; Create</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080504228/38e68fa0-09d0-42ce-a73f-3cb3fe486ad8.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080520470/aaf6d65d-e60d-4e05-a710-e1d7e8b7c464.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080559403/eea29439-6f17-4c54-b02a-21b403581553.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080596699/fca3c0c1-60ed-4c9e-9dbe-bb1716efb224.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080617145/a53b09f5-aca8-4022-9ba8-a6851af7fcf8.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080659301/750813b9-8298-4508-960f-38f5a71a55eb.png" alt class="image--center mx-auto" /></p>
<p>(Next step is optional)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080704471/95317942-7f85-4fe3-b525-0e69e58eed10.png" alt class="image--center mx-auto" /></p>
<p>Next</p>
<p>Add notifications (optional) &gt; Skip to review</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080796597/6700e177-e092-4438-bb06-d14c619b8e65.png" alt class="image--center mx-auto" /></p>
<p>Create Auto Scaling Group.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692080875235/91e80a31-15f4-41f4-a98b-e9641be468f8.png" alt class="image--center mx-auto" /></p>
<p>Go to the App LB's Security group &gt; Inbound Rules &gt; Add a rule to allow HTTP traffic to all IPv4</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692081128105/b7685f3c-2158-493d-9ce6-2c42309b6e33.png" alt class="image--center mx-auto" /></p>
<p>Open the DNS name of the App LB in a browser. You should be able to see the web page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692081173377/aba61c76-2341-482e-a32d-981506cb85c3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692081216988/f4f58db9-9ea0-42fb-80bf-ca65df83fd20.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-route-53-dns-config">Route 53 DNS config</h2>
<p>Go to the Route 53 service &gt; Select your hosted zone &gt; Create Record</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692081627996/6908d47b-0534-4f3a-b702-9eaeb850e541.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692081668851/30d995d7-3af9-4c89-b2c7-9312e32cc363.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692081710335/51260ec0-0a62-4b62-b475-e2e8011720e7.png" alt class="image--center mx-auto" /></p>
<p>Create Records.</p>
<h1 id="heading-extras">Extras</h1>
<h2 id="heading-github-actions">GitHub Actions</h2>
<p>I also added a GitHub workflow to deploy the repo code to the S3 bucket, from which newly created instances in the app and web tier get their code. A commit and push to the main branch will trigger the workflow.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span> <span class="hljs-string">App</span> <span class="hljs-string">Code</span> <span class="hljs-string">to</span> <span class="hljs-string">S3</span>

<span class="hljs-attr">on:</span>
  <span class="hljs-attr">push:</span>
    <span class="hljs-attr">branches:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>

<span class="hljs-attr">jobs:</span>
  <span class="hljs-attr">deploy:</span>
    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>
    <span class="hljs-attr">steps:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Checkout</span> <span class="hljs-string">code</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v3</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Configure</span> <span class="hljs-string">AWS</span> <span class="hljs-string">credentials</span>
      <span class="hljs-attr">uses:</span> <span class="hljs-string">aws-actions/configure-aws-credentials@v2</span>
      <span class="hljs-attr">with:</span>
        <span class="hljs-attr">aws-access-key-id:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.AWS_ACCESS_KEY_ID</span> <span class="hljs-string">}}</span>
        <span class="hljs-attr">aws-secret-access-key:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.AWS_SECRET_ACCESS_KEY</span> <span class="hljs-string">}}</span>
        <span class="hljs-attr">aws-region:</span> <span class="hljs-string">ap-southeast-1</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Sync</span> <span class="hljs-string">files</span> <span class="hljs-string">to</span> <span class="hljs-string">S3</span>
      <span class="hljs-attr">run:</span> <span class="hljs-string">|</span>
        <span class="hljs-string">aws</span> <span class="hljs-string">s3</span> <span class="hljs-string">sync</span> <span class="hljs-string">app-code/</span> <span class="hljs-string">s3://melvincv2023-cloudops-w2</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Crafting a highly available 3-tier architecture for a Node.js app in AWS, with a blend of frontend public subnets, backend private subnets, and Aurora DB private subnets, yields a robust and efficient infrastructure.</p>
<p>The frontend layer engages users, the backend layer processes data, and the database layer stores critical information. This harmonious orchestration, combined with AWS's reliability and scalability, culminates in an architecture that can weather the demands of modern applications.</p>
<p>Connect with me on Linkedin and Twitter for more projects! Please find my social links at the top:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692179071969/5c1f7563-367b-482c-b33f-50efcd61aae4.png" alt class="image--center mx-auto" /></p>
<p>Also, consider subscribing to my blog 😊</p>
]]></content:encoded></item><item><title><![CDATA[#10weeksofCloudOps - Week 1]]></title><description><![CDATA[Host a static website on AWS or Azure or GCP and implement CI/CD]]></description><link>https://blog.melvincv.com/10weeksofcloudops-week-1</link><guid isPermaLink="true">https://blog.melvincv.com/10weeksofcloudops-week-1</guid><category><![CDATA[10weeksofcloudops]]></category><category><![CDATA[Static Website]]></category><category><![CDATA[AWS s3]]></category><category><![CDATA[cloudfront]]></category><category><![CDATA[route53]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Wed, 02 Aug 2023 05:40:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690955665056/4944d4c9-5859-4176-b4d3-8f7c51812b68.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1692866802729/726e7371-137c-4041-b5e8-1d120ba41728.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-introduction">Introduction</h2>
<p>In today's digital age, hosting a website has become an essential part of establishing an online presence. Amazon Web Services (AWS) offers a robust and scalable platform for hosting static websites, while implementing Continuous Integration and Continuous Deployment (CI/CD) practices can streamline the development and deployment process.</p>
<p>One popular CI/CD tool is GitHub Actions, which allows developers to automate various tasks. In this article, we will explore how to host a static website on AWS and implement CI/CD using GitHub Actions, enabling you to efficiently manage and deploy your website with ease.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p>Use S3, CloudFront, Route53</p>
</li>
<li><p><a target="_blank" href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html">https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html</a></p>
</li>
<li><p><a target="_blank" href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/website-hosting-cloudfront-walkthrough.html">https://docs.aws.amazon.com/AmazonS3/latest/userguide/website-hosting-cloudfront-walkthrough.html</a></p>
</li>
</ul>
<h2 id="heading-architecture">Architecture</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691039593412/c065e2b6-30ca-4fd0-930d-c5c0b2fa00f6.png" alt class="image--center mx-auto" /></p>
<p><mark>(Unavailable, as the infrastructure has been torn down)</mark></p>
<h2 id="heading-procedure">Procedure</h2>
<p>Download a <a target="_blank" href="https://html5up.net/">static site</a> and add it to a <a target="_blank" href="https://github.com/melvincv/10weeksofcloudops-w1">new Github repo</a>. (under the www folder)</p>
<h3 id="heading-create-an-s3-bucket">Create an S3 bucket</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690863578254/0571df61-9ace-464d-8e9c-c1b71d05b7e9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690863605010/c1eaffe3-5f4c-40e4-acdd-347983945650.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690863626487/9eb917e1-734c-4035-9254-594aefc1a9ff.png" alt class="image--center mx-auto" /></p>
<p>Click: Create Bucket</p>
<h3 id="heading-enable-static-website-hosting">Enable Static Website hosting</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690863792158/fd4ab2ca-91b2-4351-aa2a-322eeff32fb3.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690863813497/a8b1689b-f420-448a-b290-361a734f7294.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690863973743/df99223c-9783-41d9-a593-50576c6a44c0.png" alt class="image--center mx-auto" /></p>
<p>Click: Save Changes</p>
<p>Copy the Public URL from the bottom of the Properties page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690864044487/3d8351b9-8784-4197-b8b7-10d0b8bfbcb7.png" alt class="image--center mx-auto" /></p>
<p>Install and configure the AWS CLI for your OS.</p>
<p><a target="_blank" href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></p>
<p>Create an AWS Access Key and Secret Key.</p>
<p>Configure AWS CLI:</p>
<pre><code class="lang-bash">aws configure
</code></pre>
<p>Copy the static site to the s3 bucket:</p>
<pre><code class="lang-bash">aws s3 cp www s3://melvincv2023-cloudops-w1 --recursive
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690864508215/ec89c538-27e3-4de7-b941-4a17eb33096f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-add-an-s3-bucket-policy-to-allow-public-access">Add an S3 Bucket Policy to allow public access</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690865664108/3a0554bc-de70-4053-b064-bc11bfb45578.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690865716687/d10c6176-7f6a-4ece-9f6b-9c7f2d32f2cd.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">{
    <span class="hljs-string">"Version"</span>: <span class="hljs-string">"2012-10-17"</span>,
    <span class="hljs-string">"Statement"</span>: [
        {
            <span class="hljs-string">"Sid"</span>: <span class="hljs-string">"PublicReadGetObject"</span>,
            <span class="hljs-string">"Effect"</span>: <span class="hljs-string">"Allow"</span>,
            <span class="hljs-string">"Principal"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-string">"Action"</span>: [
                <span class="hljs-string">"s3:GetObject"</span>
            ],
            <span class="hljs-string">"Resource"</span>: [
                <span class="hljs-string">"arn:aws:s3:::melvincv2023-cloudops-w1/*"</span>
            ]
        }
    ]
}
</code></pre>
<p>Add the above policy and click Save Changes.</p>
<p>Now the Bucket URL should load the static site:</p>
<p><a target="_blank" href="http://melvincv2023-cloudops-w1.s3-website-ap-southeast-1.amazonaws.com/">http://melvincv2023-cloudops-w1.s3-website-ap-southeast-1.amazonaws.com/</a></p>
<h3 id="heading-cloudfront">CloudFront</h3>
<p>Go to the Cloudfront service, click "Create distribution".</p>
<p>Enter the Amazon S3 <strong>website endpoint</strong> for your bucket. Do not select the default bucket URI from the dropdown.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690866077175/82d55dad-fa4f-46ec-a66c-b8b96b73bc66.png" alt class="image--center mx-auto" /></p>
<p>For <strong>Default Cache Behavior Settings</strong>, keep the values set to the defaults.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690866877386/ceeec880-ffd2-4f9b-84b0-73488a04bb2e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690866958868/a878373a-d501-4498-9137-8f596f01158b.png" alt class="image--center mx-auto" /></p>
<p>Go to the <strong>Certificate Manager service &gt;</strong> Create an SSL certificate &gt; Verify the certificate by adding records to Route 53 (or your domain registrar's DNS settings)</p>
<p>Select the certificate in CloudFront. I have already created an wildcard SSL certificate in <strong>Certificate Manager.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690866460440/d37ac24e-f2d5-4b4b-9de0-0497a33d10fc.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690866518631/3f72a63a-7e85-4db4-8646-cafe5e7dca7c.png" alt class="image--center mx-auto" /></p>
<p>Click: Create distribution.</p>
<p>Create an S3 bucket in the Singapore region for configuring Cloudfront logging:</p>
<pre><code class="lang-bash">aws s3 mb s3://melvincv2023-cloudops-w1-logs --region ap-southeast-1
</code></pre>
<p>Configure CloudFront logging:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690867956298/8808c3cf-ad19-427c-ae3d-0c7582e7cc99.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690868055075/668e805e-6eee-4147-a42f-e2e43259acb4.png" alt class="image--center mx-auto" /></p>
<p>Click: Save changes.</p>
<p>Go to Route 53 &gt; select your zone</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690868194743/c5b3f01f-b1d3-42f6-80a8-4fbe24ee744e.png" alt class="image--center mx-auto" /></p>
<p>Add an Alias record pointing to your CloudFront distribution.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690868283661/39b335d7-d33a-40a1-8d85-3fae4e202e6c.png" alt class="image--center mx-auto" /></p>
<p>Click: Create records.</p>
<p>The site is now accessible at:</p>
<p><a target="_blank" href="https://site1.aws.melvincv.com/">Dimension by HTML5 UP (</a><a target="_blank" href="http://melvincv.com">melvincv.com</a><a target="_blank" href="https://site1.aws.melvincv.com/">)</a></p>
<h2 id="heading-github-actions-workflow">GitHub Actions Workflow</h2>
<p>GitHub Actions workflows are a powerful tool for automating various tasks in the software development lifecycle. Workflows are defined in YAML files and can be triggered by events such as code pushes, pull requests, or scheduled intervals.</p>
<p>Workflows consist of one or more jobs, which are executed on virtual machines or containers. Each job can have multiple steps, which are individual tasks that can be executed sequentially or in parallel. Workflows can also use actions, which are reusable units of code that can be shared and used across different workflows.</p>
<p>With GitHub Actions workflows, developers can automate tasks such as building, testing, and deploying their code, enabling them to focus on writing high-quality software.</p>
<h3 id="heading-add-repo-secrets">Add repo secrets</h3>
<p>Create an IAM user with programmatic access and download the <code>credentials.csv</code> file</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690871848494/d8828ce4-9383-4673-9582-7d8b9e27e0e1.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690871864632/77159fe6-da40-4517-b228-68a36a777d18.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690871897438/2915bb5b-ecf7-4b01-a97f-da9775d48e41.png" alt class="image--center mx-auto" /></p>
<p>Next &gt; Create Access Key &gt; Download CSV file</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690870045191/de551123-dc3d-4646-8ef9-87633366d5eb.png" alt class="image--center mx-auto" /></p>
<p>Create 2 secrets, add the access key and secret access key as their values:</p>
<pre><code class="lang-bash">AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690872183228/674e0e9a-d868-413b-a58d-c4eca3ed0460.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-github-workflow">Github Workflow</h3>
<p>Create a file in the repo in the path <code>.github/workflows/deploy.yml</code></p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span> <span class="hljs-string">Static</span> <span class="hljs-string">Site</span> <span class="hljs-string">to</span> <span class="hljs-string">S3</span>

<span class="hljs-attr">on:</span>
  <span class="hljs-attr">push:</span>
    <span class="hljs-attr">branches:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>

<span class="hljs-attr">jobs:</span>
  <span class="hljs-attr">deploy:</span>
    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>

    <span class="hljs-attr">steps:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Checkout</span> <span class="hljs-string">code</span>
        <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v3</span>

      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Set</span> <span class="hljs-string">up</span> <span class="hljs-string">AWS</span> <span class="hljs-string">credentials</span>
        <span class="hljs-attr">uses:</span> <span class="hljs-string">aws-actions/configure-aws-credentials@v2</span>
        <span class="hljs-attr">with:</span>
          <span class="hljs-attr">aws-access-key-id:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.AWS_ACCESS_KEY_ID</span> <span class="hljs-string">}}</span>
          <span class="hljs-attr">aws-secret-access-key:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.AWS_SECRET_ACCESS_KEY</span> <span class="hljs-string">}}</span>
          <span class="hljs-attr">aws-region:</span> <span class="hljs-string">ap-southeast-1</span>

      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span> <span class="hljs-string">to</span> <span class="hljs-string">S3</span>
        <span class="hljs-attr">run:</span> <span class="hljs-string">|
          aws s3 sync www s3://melvincv2023-cloudops-w1 --delete
</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Invalidate</span> <span class="hljs-string">CloudFront</span> <span class="hljs-string">cache</span>
        <span class="hljs-attr">run:</span> <span class="hljs-string">|</span>
          <span class="hljs-string">aws</span> <span class="hljs-string">cloudfront</span> <span class="hljs-string">create-invalidation</span> <span class="hljs-string">--distribution-id</span> <span class="hljs-string">E12J9I3XUIQBDB</span> <span class="hljs-string">--paths</span> <span class="hljs-string">"/*"</span>
</code></pre>
<h3 id="heading-create-an-origin-access">Create an Origin Access?</h3>
<p>No, it is not possible to use Origin Access Control (OAC) with an S3 website endpoint. When your origin is an Amazon S3 bucket configured as a website endpoint, you cannot use OAC or OAI (Origin Access Identity) [1].</p>
<p>However, you can still restrict access to a custom origin by setting up <strong>custom headers</strong> and configuring the origin to require them [1]. This means you can implement additional measures to control access to your S3 bucket content when using an S3 website endpoint with CloudFront.</p>
<p>It is important to note that using OAI is a best practice for securing access to your S3 bucket content through CloudFront[2][4]. While it may not apply to an S3 website endpoint, you can explore other options like <strong>custom headers</strong> to enhance the security of your static website hosted on S3.</p>
<p>Citations:</p>
<p>[1] <a target="_blank" href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html">https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html</a></p>
<p>[2] <a target="_blank" href="https://trendmicro.com/cloudoneconformity/knowledge-base/aws/CloudFront/s3-origin.html">https://trendmicro.com/cloudoneconformity/knowledge-base/aws/CloudFront/s3-origin.html</a></p>
<p>[3] <a target="_blank" href="https://repost.aws/knowledge-center/cloudfront-serve-static-website">https://repost.aws/knowledge-center/cloudfront-serve-static-website</a></p>
<p>[4] <a target="_blank" href="https://www.stormit.cloud/blog/cloudfront-origin-access-identity/">https://www.stormit.cloud/blog/cloudfront-origin-access-identity/</a></p>
<p>[5] <a target="_blank" href="https://crishantha.medium.com/securing-s3-with-origin-access-identity-oai-via-cloudfront-147467eae8aa">https://crishantha.medium.com/securing-s3-with-origin-access-identity-oai-via-cloudfront-147467eae8aa</a></p>
<p>[6] <a target="_blank" href="https://think-devops.com/posts/static-website-hosting/">https://think-devops.com/posts/static-website-hosting/</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Hosting a static website on AWS and implementing CI/CD using GitHub Actions can greatly enhance your web development workflow. By leveraging the power of AWS services like Amazon S3 and CloudFront, you can ensure high availability, scalability, and cost-effectiveness for your website.</p>
<p>Additionally, integrating CI/CD practices with GitHub Actions enables you to automate the deployment process, ensuring that your website is always up-to-date with the latest changes. This combination of AWS and GitHub Actions empowers developers to focus on building and improving their websites, while the infrastructure and deployment processes are taken care of seamlessly.</p>
<p>So, whether you are a seasoned developer or just starting your journey, hosting a static website on AWS and implementing CI/CD using GitHub Actions is a valuable skill set to have in your toolkit. Embrace the power of these technologies and take your web development projects to new heights.</p>
]]></content:encoded></item><item><title><![CDATA[gzip compression of static files in NGINX]]></title><description><![CDATA[As a DevOps or Ops Engineer, you are likely familiar with the importance of optimizing website performance. One way to improve website speed is by…]]></description><link>https://blog.melvincv.com/gzip-compression-of-static-files-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/gzip-compression-of-static-files-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[performance]]></category><category><![CDATA[static]]></category><category><![CDATA[compression]]></category><category><![CDATA[gzip]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Mon, 31 Jul 2023 05:29:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/plwud_FPvwU/upload/a84e064eace98d530d4462825bd62a70.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a DevOps or Ops Engineer, you are likely familiar with the importance of optimizing website performance. One way to improve website speed is by compressing responses using gzip in Nginx.</p>
<p>Gzip is a file compression format that reduces the size of files, including HTML, CSS, and JavaScript files, by compressing them into a smaller format. This compression reduces the amount of data that needs to be transferred between the server and the client, resulting in faster load times.</p>
<p>Nginx, a popular web server and reverse proxy server, supports gzip compression out of the box. Enabling gzip compression in Nginx is a simple process that can significantly improve website performance.</p>
<h3 id="heading-configuration">Configuration</h3>
<p>To enable gzip compression in Nginx, you need to modify the Nginx configuration file. The configuration file is typically located in the <code>/etc/nginx/</code> directory. Open the configuration file in a text editor and locate the <code>http</code> block. Within the <code>http</code> block, add the following lines of code:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">gzip</span> <span class="hljs-literal">on</span>;
<span class="hljs-attribute">gzip_comp_level</span> <span class="hljs-number">3</span>;
<span class="hljs-attribute">gzip_types</span> text/plain;
<span class="hljs-attribute">gzip_types</span> text/css;
<span class="hljs-attribute">gzip_types</span> application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
</code></pre>
<p>The first line, <code>gzip on</code>, enables gzip compression in Nginx. In the second line, the <code>gzip_comp_level</code> is set to 3.</p>
<p>The compression level can range from 1 to 9, with 1 being the fastest and least compressed, and 9 being the slowest and most compressed. A compression level of 3 to 4 is a good balance between compression efficiency and server performance.</p>
<p>The third line specifies the file types that should be compressed. In this example, text/plain, text/css, application/json, application/javascript, text/xml, application/xml, application/xml+rss, and text/javascript files will be compressed.</p>
<p>Save the configuration file and restart Nginx to apply the changes. You can do this by running the following command:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">sudo</span> service nginx restart
</code></pre>
<p>Once gzip compression is enabled in Nginx, you can test it by using a tool like Google PageSpeed Insights or GTmetrix. These tools will analyze your website and provide recommendations for improving website performance, including gzip compression.</p>
<p>In addition to improving website performance, gzip compression can also reduce bandwidth usage and lower hosting costs. By compressing files, less data is transferred between the server and the client, resulting in lower bandwidth usage and potentially lower hosting costs.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Enabling gzip compression in Nginx is a simple and effective way to improve website performance. By compressing files, less data is transferred between the server and the client, resulting in faster load times, lower bandwidth usage, and potentially lower hosting costs. As a DevOps / Ops Engineer, optimizing website performance should be a top priority, and gzip compression is a valuable tool in your optimization toolkit.</p>
]]></content:encoded></item><item><title><![CDATA[Cache Control Header in NGINX]]></title><description><![CDATA[The Cache-Control header is a powerful tool that can be used to control how a browser caches a resource. Here are some real-world examples of how to use…]]></description><link>https://blog.melvincv.com/cache-control-header-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/cache-control-header-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[caching]]></category><category><![CDATA[http-headers]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Fri, 28 Jul 2023 05:38:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690522678854/52b36502-9e4f-4a39-9bf5-6d16ba2c464b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <code>Cache-Control</code> header is a powerful tool that can be used to control how a browser caches a resource. Here are some real-world examples of how to use the <code>Cache-Control</code> header in a location block:</p>
<ul>
<li><p>To set a maximum age for a resource, you can use the <code>max-age</code> directive. This directive specifies the number of seconds for which the resource can be cached. For example, to set a maximum age of one year for all image files, you can use the following location block:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.(jpg|jpeg|png|gif)$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"max-age=31536000"</span>;
  }
</code></pre>
</li>
<li><p>To prevent a resource from being cached, you can use the <code>no-cache</code> directive. This directive tells the browser to revalidate the resource with the server before using a cached version. For example, to prevent caching of all HTML files, you can use the following location block:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.html$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"no-cache"</span>;
  }
</code></pre>
</li>
<li><p>To allow a resource to be cached by intermediate proxies, you can use the <code>public</code> directive. This directive tells the browser that the resource can be cached by any cache, even if it is not the end user's browser. For example, to allow caching of all CSS files by intermediate proxies, you can use the following location block:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.css$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"public"</span>;
  }
</code></pre>
</li>
<li><p>To prevent a resource from being modified, you can use the <code>immutable</code> directive. This directive tells the browser that the resource will never change, so it can be cached indefinitely. For example, to prevent modification of all JavaScript files, you can use the following location block:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.js$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"immutable"</span>;
  }
</code></pre>
</li>
</ul>
<p>Note that the <code>Cache-Control</code> header offers more control over caching behavior than the <code>Expires</code> header and takes precedence over the <code>Expires</code> header when both are present[6].</p>
<h2 id="heading-related-headers">Related Headers</h2>
<p>The <code>Cache-Control</code> header is a powerful tool that can be used to control how a browser caches a resource. However, there are other headers that can be used in conjunction with <code>Cache-Control</code> to provide more granular control over caching behavior. Here are some examples:</p>
<ul>
<li><p><code>ETag</code>: This header is used to provide a unique identifier for a resource. The browser can use this identifier to check if the resource has changed since it was last cached. You can use the <code>etag</code> directive in a location block to set the <code>ETag</code> header. For example:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"max-age=31536000"</span>;
      <span class="hljs-attribute">etag</span> <span class="hljs-literal">on</span>;
  }
</code></pre>
</li>
<li><p><code>Vary</code>: This header is used to specify which request headers should be taken into account when determining whether a cached resource can be used. You can use the <code>vary</code> directive in a location block to set the <code>Vary</code> header. For example:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"max-age=31536000"</span>;
      <span class="hljs-attribute">etag</span> <span class="hljs-literal">on</span>;
      <span class="hljs-attribute">vary</span> User-Agent;
  }
</code></pre>
<p>  This location block sets the <code>Vary</code> header to <code>User-Agent</code> for the same file types as the previous example.</p>
</li>
<li><p><code>Last-Modified</code>: This header is used to specify the date and time when a resource was last modified. The browser can use this information to check if the resource has changed since it was last cached. You can use the <code>last_modified</code> directive in a location block to set the <code>Last-Modified</code> header. For example:</p>
<pre><code class="lang-nginx">  <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$</span> {
      <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"max-age=31536000"</span>;
      <span class="hljs-attribute">etag</span> <span class="hljs-literal">on</span>;
      <span class="hljs-attribute">last_modified</span> <span class="hljs-literal">on</span>;
  }
</code></pre>
</li>
</ul>
<p>Note that the use of these headers depends on the specific requirements of your website and the behavior you want to achieve. In general, it is recommended to use the <code>Cache-Control</code> header as the primary caching control header and to avoid using the <code>Expires</code> header and the <code>Pragma</code> header[1].</p>
<h2 id="heading-another-location-block">Another location block</h2>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> <span class="hljs-regexp">~* \.(css|js|jpg|png)$</span> {
      <span class="hljs-attribute">access_log</span> <span class="hljs-literal">off</span>;
      <span class="hljs-attribute">add_header</span> Cache-Control public;
      <span class="hljs-attribute">add_header</span> Pragma public;
      <span class="hljs-attribute">add_header</span> Vary Accept-Encoding;
      <span class="hljs-attribute">expires</span> <span class="hljs-number">1M</span>;
    }
</code></pre>
<h3 id="heading-references">References</h3>
<p><a target="_blank" href="https://www.udemy.com/course/nginx-fundamentals/learn/lecture/10615216#overview">NGINX Fundamentals: High Performance Servers from Scratch | Udemy</a></p>
<p><a target="_blank" href="https://www.imperva.com/learn/performance/cache-control/">https://www.imperva.com/learn/performance/cache-control/</a></p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control">https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control</a></p>
<p><a target="_blank" href="https://www.keycdn.com/blog/cache-control-immutable">https://www.keycdn.com/blog/cache-control-immutable</a></p>
<p><a target="_blank" href="https://simonhearne.com/2022/caching-header-best-practices/">https://simonhearne.com/2022/caching-header-best-practices/</a></p>
<p><a target="_blank" href="https://paulcalvano.com/2018-03-14-http-heuristic-caching-missing-cache-control-and-expires-headers-explained/">https://paulcalvano.com/2018-03-14-http-heuristic-caching-missing-cache-control-and-expires-headers-explained/</a></p>
<p><a target="_blank" href="https://robotecture.com/http-topics/http-headers/http-header-expires/">https://robotecture.com/http-topics/http-headers/http-header-expires/</a></p>
<p><a target="_blank" href="https://simonhearne.com/2022/caching-header-best-practices/">https://simonhearne.com/2022/caching-header-best-practices/</a></p>
<p><a target="_blank" href="https://robotecture.com/http-topics/http-headers/http-header-expires/">https://robotecture.com/http-topics/http-headers/http-header-expires/</a></p>
<p><a target="_blank" href="https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers">https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers</a></p>
<p><a target="_blank" href="https://www.turing.com/blog/cache-control-headers-and-use-cases/">https://www.turing.com/blog/cache-control-headers-and-use-cases/</a></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/4480304/how-to-set-http-headers-for-cache-control">https://stackoverflow.com/questions/4480304/how-to-set-http-headers-for-cache-control</a></p>
<p><a target="_blank" href="https://serverfault.com/questions/88523/should-i-use-expires-headers-cache-control-headers-or-both">https://serverfault.com/questions/88523/should-i-use-expires-headers-cache-control-headers-or-both</a></p>
]]></content:encoded></item><item><title><![CDATA[Buffers and Timeouts in NGINX]]></title><description><![CDATA[In the world of web servers and content delivery, Nginx has emerged as one of the most popular and efficient solutions. One of the key features that make…]]></description><link>https://blog.melvincv.com/buffers-and-timeouts-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/buffers-and-timeouts-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[buffer]]></category><category><![CDATA[timeout]]></category><category><![CDATA[configuration]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Tue, 25 Jul 2023 08:55:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/nuc3NFB_6po/upload/46a9e09358c0d98c2ba2aa74acda8a57.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In the world of web servers and content delivery, Nginx has emerged as one of the most popular and efficient solutions. One of the key features that make Nginx stand out is its powerful buffering capabilities. In this article, we will explore the concept of buffering in Nginx and how it plays a crucial role in optimizing web performance and ensuring a seamless user experience.</p>
<h2 id="heading-what-is-buffering">What is buffering?</h2>
<p>Buffering is a mechanism used by web servers like Nginx to temporarily store and process data before serving it to the client's web browser. It involves loading certain portions of a web page or an entire web page into the server's memory before delivering it to the user. This preloading process helps in managing the flow of data and enables smoother content delivery.</p>
<h3 id="heading-types-of-buffers">Types of Buffers</h3>
<p>NGINX has 2 main types of buffers.</p>
<h3 id="heading-1-disk-buffers">1. Disk Buffers</h3>
<p>Disk buffering involves writing temporary files to the server's disk during the buffering process. This method is useful when dealing with large files or slow clients, as it prevents overwhelming the server's memory and allows for efficient handling of data.</p>
<h3 id="heading-2-memory-buffers">2. Memory Buffers</h3>
<p>Memory buffering, as the name suggests, stores the buffered data directly in the server's memory. This approach is more suitable for handling smaller files or when dealing with a large number of concurrent requests from clients.</p>
<h2 id="heading-configuration">Configuration</h2>
<p>If you do not know what you are doing, it is best to leave these values at their defaults.</p>
<pre><code class="lang-nginx"><span class="hljs-section">http</span> {

  <span class="hljs-attribute">include</span> mime.types;

  <span class="hljs-comment"># Buffer size for POST submissions</span>
  <span class="hljs-attribute">client_body_buffer_size</span> <span class="hljs-number">10K</span>;        (1)
  <span class="hljs-attribute">client_max_body_size</span> <span class="hljs-number">8m</span>;            (2)

  <span class="hljs-comment"># Buffer size for Headers</span>
  <span class="hljs-attribute">client_header_buffer_size</span> <span class="hljs-number">1k</span>;        (3)

  <span class="hljs-comment"># Max time to receive client headers/body</span>
  <span class="hljs-attribute">client_body_timeout</span> <span class="hljs-number">12</span>;        (4)
  <span class="hljs-attribute">client_header_timeout</span> <span class="hljs-number">12</span>;      (5)

  <span class="hljs-comment"># Max time to keep a connection open for</span>
  <span class="hljs-attribute">keepalive_timeout</span> <span class="hljs-number">15</span>;        (6)

  <span class="hljs-comment"># Max time for the client accept/receive a response</span>
  <span class="hljs-attribute">send_timeout</span> <span class="hljs-number">10</span>;        (7)

  <span class="hljs-comment"># Skip buffering for static files</span>
  <span class="hljs-attribute">sendfile</span> <span class="hljs-literal">on</span>;        (8)

  <span class="hljs-comment"># Optimise sendfile packets</span>
  <span class="hljs-attribute">tcp_nopush</span> <span class="hljs-literal">on</span>;        (9)
</code></pre>
<ol>
<li><p>Amount of memory to allocate for buffering the POST data from a client. (could be a form submission)</p>
</li>
<li><p>Do not accept POST requests larger than this value. If it is larger than this, the below error will occur:</p>
<ol>
<li>Error 413: Request Entity too large</li>
</ol>
</li>
<li><p>The amount of RAM to allocate for reading request headers.</p>
</li>
<li><p>Time taken to read the client request body to the buffer (12 ms)</p>
</li>
<li><p>Time taken to read the client request header to the buffer (12 ms)</p>
</li>
<li><p>Time that NGINX needs to keep a connection open for (more data on the way)</p>
</li>
<li><p>If the client does not receive any of the response data in this time limit, quit sending response data.</p>
</li>
<li><p>While sending a file from disk, do not use a buffer. Read the file directly and send to the client.</p>
</li>
<li><p>Allows NGINX to optimize the size of packets containing data from <code>sendfile</code></p>
</li>
</ol>
<h2 id="heading-best-practices-for-buffering-configuration"><strong>Best Practices for Buffering Configuration</strong></h2>
<h3 id="heading-1-analyzing-workload"><strong>1. Analyzing Workload</strong></h3>
<p>Understand the nature of your application's workload and tailor buffer and timeout settings accordingly.</p>
<h3 id="heading-2-periodic-review"><strong>2. Periodic Review</strong></h3>
<p>Regularly review server logs and performance metrics to fine-tune buffer and timeout configurations for optimal results.</p>
<h3 id="heading-3-stress-testing"><strong>3. Stress Testing</strong></h3>
<p>Conduct stress tests to simulate heavy traffic and assess how buffers and timeouts perform under pressure.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Buffers and timeouts are integral components of Nginx's performance optimization strategy. By efficiently managing data transmission and request processing, buffers and timeouts contribute to a responsive and reliable web server. Configuring these elements with care can significantly enhance the overall user experience and protect the server from potential security threats.</p>
]]></content:encoded></item><item><title><![CDATA[NGINX Worker Processes and Connections]]></title><description><![CDATA[When we start the NGINX service, we get a master process which we can view using systemctl. This master process then spawns worker processes that are used…]]></description><link>https://blog.melvincv.com/nginx-worker-processes-and-connections</link><guid isPermaLink="true">https://blog.melvincv.com/nginx-worker-processes-and-connections</guid><category><![CDATA[nginx]]></category><category><![CDATA[Nginx configuration guide]]></category><category><![CDATA[worker]]></category><category><![CDATA[connection]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Fri, 21 Jul 2023 05:45:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/MU8w72PzRow/upload/9034586122bba89bb247074d6e8f3c5a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-worker-processes">Worker processes</h2>
<p>When we start the NGINX service, we get a master process which we can view using systemctl. This master process then spawns worker processes that are used to serve requests. The default is one worker process.</p>
<p>We can change the no. of worker processes using the <code>worker_processes</code> directive. But more workers do not necessarily mean more performance. Each NGINX process will serve as many requests as the hardware can support.</p>
<p>There are instances where there are benefits in increasing the no. of worker processes. On a multicore CPU, for example. A single NGINX process can only work on one core of a CPU. So say, we have an 8-core CPU. The optimal no. of worker processes would be 8. Do not run more than one process on one core.</p>
<p>You may check the no. of CPU cores in a Linux server using:</p>
<pre><code class="lang-bash">nproc
lscpu
</code></pre>
<p>Setting the <code>worker_processes</code> directive to <code>auto</code> will auto-increase the no. of processes to match the no. of cores on your server.</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">worker_processes</span> auto;
</code></pre>
<h2 id="heading-no-of-connections-per-worker">No. of connections per worker</h2>
<pre><code class="lang-nginx"><span class="hljs-section">events</span> {
  <span class="hljs-attribute">worker_connections</span> <span class="hljs-number">1024</span>;
}
</code></pre>
<p>The <code>worker_connections</code> directive specifies the maximum number of connections that each worker process can handle. The default value is 512. However, you may want to increase the value of <code>worker_connections</code> if your server is handling a lot of traffic.</p>
<p>For example, if you have a server with 4 GB of RAM, you might want to set <code>worker_connections</code> to 1024. This will allow each worker process to handle up to 1024 connections, which can help to improve performance.</p>
<p>It is important to note that the total number of connections that NGINX can handle is limited by the number of open file descriptors that the system allows. You can check the maximum number of open file descriptors with the following command:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">ulimit</span> -n
<span class="hljs-number">1024</span>
</code></pre>
<p>If the number of open file descriptors is lower than the value of <code>worker_connections</code>, you will need to increase the value of <code>ulimit</code>.</p>
<h3 id="heading-request-capacity">Request Capacity</h3>
<p>Total no. of requests that can be served = worker processes * worker connections</p>
<p>This is very important for the performance optimization of NGINX.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By understanding the worker processes and number of connections settings in NGINX, you can optimize your server's performance and ensure that it can handle a large number of concurrent connections.</p>
]]></content:encoded></item><item><title><![CDATA[Server-side processing using php-fpm]]></title><description><![CDATA[PHP is a popular scripting language that is often used to create dynamic web pages. However, PHP can be resource-intensive, especially on high-traffic…]]></description><link>https://blog.melvincv.com/server-side-processing-using-php-fpm</link><guid isPermaLink="true">https://blog.melvincv.com/server-side-processing-using-php-fpm</guid><category><![CDATA[PHP]]></category><category><![CDATA[nginx]]></category><category><![CDATA[Server side rendering]]></category><category><![CDATA[troubleshooting]]></category><category><![CDATA[fastcgi]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Thu, 20 Jul 2023 06:31:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4wxWBy8Jo1I/upload/0c97613466a742928dd26cb0c9cb5577.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PHP is a popular scripting language that is often used to create dynamic web pages. However, PHP can be resource-intensive, especially on high-traffic websites. This is where NGINX and php-fpm come in.</p>
<p>NGINX is a high-performance web server that can handle a lot of traffic. php-fpm is a PHP FastCGI implementation that can offload the processing of PHP scripts from NGINX. This can improve performance and reduce the load on the web server.</p>
<p>To use NGINX and php-fpm to process PHP scripts, you need to configure both servers.</p>
<h2 id="heading-install-nginx-and-php-fpm">Install NGINX and php-fpm</h2>
<p>Here is the command to install both nginx and php-fpm on Ubuntu or Debian:</p>
<pre><code class="lang-bash">sudo apt install nginx php-fpm
</code></pre>
<h3 id="heading-check-if-php-fpm-is-running">Check if php-fpm is running</h3>
<pre><code class="lang-bash">sudo systemctl list-units | grep php
</code></pre>
<h3 id="heading-configuring-nginx">Configuring NGINX</h3>
<p>To configure NGINX to use php-fpm, you need to add the following lines to your nginx.conf file:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> / {
    <span class="hljs-attribute">fastcgi_pass</span> unix:/var/run/php-fpm.sock;
}
</code></pre>
<p>This tells NGINX to pass all requests for PHP scripts to the php-fpm socket at <code>/var/run/php-fpm.sock</code>.</p>
<h3 id="heading-configuring-php-fpm">Configuring php-fpm</h3>
<p>To configure php-fpm to listen on the Unix socket, you need to add the following lines to your php-fpm.conf file:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">listen</span> = /var/run/php-fpm.sock
</code></pre>
<p>This tells php-fpm to listen on the Unix socket at <code>/var/run/php-fpm.sock</code>.</p>
<p>Once you have configured NGINX and php-fpm, you need to restart both servers.</p>
<p>To restart NGINX, you can run the following command:</p>
<p><code>sudo service nginx restart</code></p>
<p>To restart php-fpm, you can run the following command:</p>
<p><code>sudo service php-fpm restart</code></p>
<p>Once both servers are restarted, you can test your configuration by creating a simple PHP script and accessing it through your web browser.</p>
<p>The following is a simple PHP script that you can use to test your configuration:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">echo</span> <span class="hljs-string">"Hello, world!"</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>Save this file as <code>index.php</code> in the root directory of your web server. Then, access it through your web browser by going to the following URL:</p>
<p>" <a target="_blank" href="http://localhost/index.php">http://localhost/index.php</a> "</p>
<p>If you see the message "Hello, world!", then your configuration is working correctly.</p>
<p>Using NGINX and php-fpm together can improve the performance of your PHP applications by offloading the processing of PHP scripts from the web server. This can be especially beneficial for high-traffic websites.</p>
<h3 id="heading-server-block-with-php-processing">Server Block with PHP processing</h3>
<p>Look for these config:</p>
<ul>
<li><p>index directive, index.php</p>
</li>
<li><p>location block</p>
<ul>
<li><p>fastcgi is a protocol for transferring binary data</p>
<ul>
<li>include <code>/etc/nginx/fastcgi.conf</code></li>
</ul>
</li>
<li><p>pass to a UNIX socket, a file that listens for binary data.</p>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {

    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    <span class="hljs-attribute">server_name</span> <span class="hljs-number">167.99.93.26</span>;

    <span class="hljs-attribute">root</span> /sites/demo;

    <span class="hljs-attribute">index</span> index.php index.html;

    <span class="hljs-attribute">location</span> / {
      <span class="hljs-attribute">try_files</span> <span class="hljs-variable">$uri</span> <span class="hljs-variable">$uri</span>/ =<span class="hljs-number">404</span>;
    }

    <span class="hljs-attribute">location</span> ~\.php$ {
      <span class="hljs-comment"># Pass php requests to the php-fpm service (fastcgi)</span>
      <span class="hljs-attribute">include</span> fastcgi.conf;
      <span class="hljs-attribute">fastcgi_pass</span> unix:/run/php/php7.1-fpm.sock;
    }

  }
</code></pre>
<h2 id="heading-testing-and-troubleshooting">Testing and Troubleshooting</h2>
<p>You may test the PHP processing by loading a PHP info file:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">echo</span> <span class="hljs-string">'&lt;?php phpinfo(); ?&gt;'</span> &gt; <span class="hljs-literal">info</span>.php
</code></pre>
<p>Open the file in the browser using http://URL/info.php</p>
<h3 id="heading-502-bad-gateway">502 Bad Gateway</h3>
<p>First, check the error logs:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">tail</span> -n <span class="hljs-number">1</span> /var/log/nginx/error.log
</code></pre>
<p>Error: Permission denied while connecting to php-fpm socket.</p>
<p>Check the user with which the NGINX process and the php-fpm process runs:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">ps</span> aux | grep nginx
ps aux | grep php
</code></pre>
<p>See that the nginx and php-fpm processes run as the same user.</p>
<p>Add the user directive to the NGINX config to match the user of the php-fpm process:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">user</span> www-data;
</code></pre>
<p>Reload NGINX and check again.</p>
<h2 id="heading-additional-resources">Additional resources</h2>
<ul>
<li><p>How to Configure PHP-FPM with NGINX: <a target="_blank" href="https://www.digitalocean.com/community/tutorials/php-fpm-nginx">https://www.digitalocean.com/community/tutorials/php-fpm-nginx</a></p>
</li>
<li><p>How to Setup PHP on Nginx with FastCGI (PHP-FPM) example: <a target="_blank" href="https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Nginx-PHP-FPM-config-example">https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Nginx-PHP-FPM-config-example</a>)</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Directive inheritance in NGINX]]></title><description><![CDATA[Directive inheritance in NGINX is a way of reusing configuration directives in different parts of the NGINX configuration file. Directives are inherited…]]></description><link>https://blog.melvincv.com/directive-inheritance-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/directive-inheritance-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[inheritance]]></category><category><![CDATA[configuration]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Wed, 19 Jul 2023 04:52:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/lFtttcsx5Vk/upload/c5e99913f5c8dc37c1845116b37e1da2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Directive inheritance in NGINX is a way of reusing configuration directives in different parts of the NGINX configuration file. Directives are inherited from the parent context to the child context. A context is a block of configuration directives. The main contexts in NGINX are:</p>
<ul>
<li><p><strong>Global context</strong>: This is the top-level context and applies to the entire NGINX configuration.</p>
</li>
<li><p><strong>HTTP context</strong>: This context applies to the HTTP protocol.</p>
</li>
<li><p><strong>Server context</strong>: This context applies to a specific server block.</p>
</li>
<li><p><strong>Location context</strong>: This context applies to a specific location within a server block.</p>
</li>
</ul>
<p>For example, the following configuration defines a global directive <code>worker_processes</code> and a server directive <code>listen</code>. The <code>worker_processes</code> directive is inherited by the <code>server</code> context and the <code>listen</code> directive is inherited by the <code>location</code> context.</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">worker_processes</span> <span class="hljs-number">2</span>;

<span class="hljs-section">http</span> {
  <span class="hljs-section">server</span> {
    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;

    <span class="hljs-attribute">location</span> / {
    }
  }
}
</code></pre>
<p>In this configuration, NGINX will create two worker processes and listen on port 80. The <code>location</code> context will inherit the <code>worker_processes</code> directive from the <code>http</code> context and the <code>listen</code> directive from the <code>server</code> context.</p>
<p>There are a few things to keep in mind about directive inheritance in NGINX:</p>
<ul>
<li><p>Directives can only be inherited from a parent context to a child context.</p>
</li>
<li><p>Directives cannot be inherited from a child context to a parent context.</p>
</li>
<li><p>Directives can be overridden in a child context.</p>
</li>
</ul>
<p>For example, the following configuration defines a server directive <code>listen</code> in the <code>http</code> context and a location directive <code>listen</code> in the <code>location</code> context. The <code>listen</code> directive in the <code>location</code> context will override the <code>listen</code> directive in the <code>http</code> context.</p>
<pre><code class="lang-nginx"><span class="hljs-section">http</span> {
  <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;

  <span class="hljs-section">server</span> {
    <span class="hljs-attribute">listen</span> <span class="hljs-number">8080</span>;

    <span class="hljs-attribute">location</span> / {
      <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    }
  }
}
</code></pre>
<p>Here is a breakdown of the configuration:</p>
<ul>
<li><p>The <code>http</code> context defines the global settings for the NGINX server. In this case, the <code>listen</code> directive tells NGINX to listen on port 80.</p>
</li>
<li><p>The <code>server</code> context defines a virtual host. In this case, the <code>listen</code> directive tells NGINX to listen on port 8080.</p>
</li>
<li><p>The <code>location</code> context defines a location within a virtual host. In this case, the <code>listen</code> directive tells NGINX to listen on port 80 for requests to the <code>/</code> location.</p>
</li>
</ul>
<p>Therefore, NGINX will listen on port 8080 for all requests, except for requests to the <code>/</code> location, which will be listened to on port 80.</p>
<p>I hope this explanation of directive inheritance in NGINX is helpful. Please let me know in the comments if you have any other questions.</p>
]]></content:encoded></item><item><title><![CDATA[Types of NGINX Directives]]></title><description><![CDATA[Here are the different types of NGINX directives: Here is an example of a complete NGINX configuration: This configuration will create a web server that…]]></description><link>https://blog.melvincv.com/types-of-nginx-directives</link><guid isPermaLink="true">https://blog.melvincv.com/types-of-nginx-directives</guid><category><![CDATA[nginx]]></category><category><![CDATA[directive]]></category><category><![CDATA[configuration]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Wed, 19 Jul 2023 04:42:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/EJSaEnVvZcg/upload/17fe555047b69b53fa4c1233c4be0bd7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here are the different types of NGINX directives:</p>
<ul>
<li><strong>Global directives</strong> are instructions that apply to the entire NGINX configuration. For example, the <code>worker_processes</code> directive specifies the number of worker processes that NGINX will create.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-attribute">worker_processes</span> <span class="hljs-number">2</span>;
</code></pre>
<ul>
<li><strong>HTTP directives</strong> are instructions that apply to the HTTP protocol. For example, the <code>gzip</code> directive enables gzip compression for HTTP responses.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-attribute">gzip</span> <span class="hljs-literal">on</span>;
</code></pre>
<ul>
<li><strong>Server directives</strong> are instructions that apply to a specific server block. A server block is a configuration that defines a virtual host. For example, the <code>listen</code> directive specifies the port that a server block will listen on.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {
  <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
}
</code></pre>
<ul>
<li><strong>Location directives</strong> are instructions that apply to a specific location within a server block. A location is a path that NGINX will match against the requested URI. For example, the <code>root</code> directive specifies the directory that NGINX will serve static files from.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {
  <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;

  <span class="hljs-attribute">location</span> / {
    <span class="hljs-attribute">root</span> /var/www/html;
  }
}
</code></pre>
<p>Here is an example of a complete NGINX configuration:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">worker_processes</span> <span class="hljs-number">2</span>;

<span class="hljs-section">http</span> {
  <span class="hljs-attribute">gzip</span> <span class="hljs-literal">on</span>;

  <span class="hljs-section">server</span> {
    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;

    <span class="hljs-attribute">location</span> / {
      <span class="hljs-attribute">root</span> /var/www/html;
    }
  }
}
</code></pre>
<p>This configuration will create a web server that listens on port 80 and serves static files from the <code>/var/www/html</code> directory.</p>
<p>Here are some additional examples of NGINX directives:</p>
<ul>
<li><p><strong>Error directives</strong> are instructions that control how NGINX handles errors. For example, the <code>error_log</code> directive specifies the file that NGINX will write error messages to.</p>
</li>
<li><p><strong>Logging directives</strong> are instructions that control how NGINX logs requests and responses. For example, the <code>access_log</code> directive specifies the file that NGINX will write access logs to.</p>
</li>
<li><p><strong>Timeout directives</strong> are instructions that specify how long NGINX will wait for a client to send a request or for a server to send a response. For example, the <code>client_max_body_size</code> directive specifies the maximum size of a client request body.</p>
</li>
</ul>
<h2 id="heading-array-action-and-normal-directives">Array, action, and normal directives</h2>
<ul>
<li><strong>Array directives</strong> are directives that can take multiple values. For example, the <code>access_log</code> directive can take multiple values, one for each log file that NGINX should write to.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-attribute">access_log</span> logs/access.log main;
<span class="hljs-attribute">access_log</span> logs/error.log <span class="hljs-literal">error</span>;
</code></pre>
<p>In this example, NGINX will write access logs to both the <code>logs/access.log</code> and <code>logs/error.log</code> files.</p>
<ul>
<li><strong>Action directives</strong> are directives that do not take any values. For example, the <code>rewrite</code> directive does not take any values. The <code>rewrite</code> directive tells NGINX to rewrite the requested URI before sending the request to the backend server.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^/old-url$</span> /new-url <span class="hljs-literal">permanent</span>;
</code></pre>
<p>In this example, NGINX will rewrite requests for the <code>/old-url</code> URI to the <code>/new-url</code> URI.</p>
<ul>
<li><strong>Normal directives</strong> are directives that take one value. For example, the <code>root</code> directive takes one value, which is the directory that NGINX should serve static files from.</li>
</ul>
<pre><code class="lang-nginx"><span class="hljs-attribute">root</span> /var/www/html;
</code></pre>
<p>In this example, NGINX will serve static files from the <code>/var/www/html</code> directory.</p>
<p>Here is a table that summarizes the different types of directives in NGINX:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td>Array directive</td><td>Can take multiple values</td><td><code>access_log logs/access.log main;</code></td></tr>
<tr>
<td>Action directive</td><td>Does not take any values</td><td><code>rewrite ^/old-url$ /new-url permanent;</code></td></tr>
<tr>
<td>Normal directive</td><td>Takes one value</td><td><code>root /var/www/html;</code></td></tr>
</tbody>
</table>
</div><p>For more information on NGINX directives, please refer to the NGINX documentation: <a target="_blank" href="http://nginx.org/en/docs/dirindex.html">http://nginx.org/en/docs/dirindex.html</a>.</p>
<p>I hope this explanation of the types of directives in NGINX is helpful. Please let me know in the comments if you have any questions.</p>
]]></content:encoded></item><item><title><![CDATA[Logging in NGINX]]></title><description><![CDATA[Logging is extremely important as it allows us to view errors, malicious users and bots. There are 2 types of logs - access logs and error logs. As the…]]></description><link>https://blog.melvincv.com/logging-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/logging-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[logging]]></category><category><![CDATA[error log]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Mon, 17 Jul 2023 06:01:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/TeeK3XdZd54/upload/d10b036166f7190729dd66838eaca3af.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Logging is extremely important as it allows us to view errors, malicious users and bots.</p>
<p>There are 2 types of logs - access logs and error logs. As the name suggests, error logs are used to log errors and warnings. Access logs log all requests to the server.</p>
<p>Logging is enabled by default. There is a default log format that you can use without changes. The main NGINX logs are present in <code>/var/log/nginx</code>.</p>
<p>Note that 404 errors are logged to the access log, not the error log.</p>
<h2 id="heading-configure-logging">Configure Logging</h2>
<h3 id="heading-logging-directives">Logging Directives</h3>
<p>There are 2 directives for logging: <code>access_log</code> and <code>error_log</code>.</p>
<h3 id="heading-disable-logging">Disable logging</h3>
<p>It is recommended to disable access logs wherever it is not required. This can save disk space and overhead.</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">access_log</span> <span class="hljs-literal">off</span>;
</code></pre>
<h3 id="heading-logging-example">Logging example</h3>
<p>Here is a server block with logging enabled in it's location block:</p>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {

    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    <span class="hljs-attribute">server_name</span> melvincv.com;

    <span class="hljs-attribute">root</span> /sites/mcv;

    <span class="hljs-attribute">location</span> /secure {
      <span class="hljs-comment"># Add context specific log</span>
      <span class="hljs-attribute">access_log</span> /var/log/nginx/access.mcv.log;
      <span class="hljs-attribute">error_log</span> /var/log/nginx/error.mcv.log;
      <span class="hljs-comment"># Disable logs for context</span>
      <span class="hljs-comment">#access_log off;</span>
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Welcome to secure area."</span>;
    }
  }
</code></pre>
<h3 id="heading-log-format-configuration">Log format configuration</h3>
<pre><code class="lang-nginx"><span class="hljs-attribute">log_format</span> combined <span class="hljs-string">'<span class="hljs-variable">$remote_addr</span> - <span class="hljs-variable">$remote_user</span> [<span class="hljs-variable">$time_local</span>] '</span> <span class="hljs-string">'"<span class="hljs-variable">$request</span>" <span class="hljs-variable">$status</span> <span class="hljs-variable">$body_bytes_sent</span> '</span> <span class="hljs-string">'"<span class="hljs-variable">$http_referer</span>" "<span class="hljs-variable">$http_user_agent</span>"'</span>; <span class="hljs-attribute">access_log</span> /var/log/nginx/access.log combined;
</code></pre>
<p>The <code>log_format</code> directive defines the format of the log messages. The <code>combined</code> format is a predefined format that logs the following information:</p>
<ul>
<li><p>The IP address of the client</p>
</li>
<li><p>The username of the client (if authenticated)</p>
</li>
<li><p>The time the request was received</p>
</li>
<li><p>The requested URL</p>
</li>
<li><p>The HTTP status code</p>
</li>
<li><p>The number of bytes sent to the client</p>
</li>
<li><p>The HTTP referer (the URL of the page that linked to the requested resource)</p>
</li>
<li><p>The HTTP user agent (the browser or other application that made the request)</p>
</li>
</ul>
<p>The <code>access_log</code> directive specifies the location of the access log and the format of the log messages. In this example, the access log is located at <code>/var/log/nginx/access.log</code> and the format is the <code>combined</code> format.</p>
<p>Once you have configured NGINX to log the appropriate information, you can start analyzing the access logs to gain insights into the traffic to your website.</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://nginx.org/en/docs/http/ngx_http_log_module.html">https://nginx.org/en/docs/http/ngx_http_log_module.html</a></p>
<p><a target="_blank" href="https://docs.nginx.com/nginx/admin-guide/monitoring/logging/">https://docs.nginx.com/nginx/admin-guide/monitoring/logging/</a></p>
<p><a target="_blank" href="https://nginx.org/en/docs/ngx_core_module.html#error_log">https://nginx.org/en/docs/ngx_core_module.html#error_log</a></p>
]]></content:encoded></item><item><title><![CDATA[Rewrites and Redirects]]></title><description><![CDATA[Rewrites and redirects are used to direct the user to a different URI path. Redirects change the path of the URL on the user's browser while rewrites do…]]></description><link>https://blog.melvincv.com/rewrites-and-redirects</link><guid isPermaLink="true">https://blog.melvincv.com/rewrites-and-redirects</guid><category><![CDATA[nginx]]></category><category><![CDATA[redirects]]></category><category><![CDATA[configuration]]></category><category><![CDATA[rewrites]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Fri, 14 Jul 2023 05:08:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zF_pTLx_Dkg/upload/34d52d44498337964420ae04a4c10a75.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Rewrites and redirects are used to direct the user to a different URI path. Redirects change the path of the URL on the user's browser while rewrites do not.</p>
<h2 id="heading-redirects">Redirects</h2>
<p>When using a redirect, the user is redirected to a new URI and the URI changes in the browser.</p>
<p>Note: When the first parameter is a 300 series status code, the return directive accepts a URI as the second parameter.</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> /logo {
    <span class="hljs-attribute">return</span> <span class="hljs-number">307</span> /thumb.png;
}
</code></pre>
<h2 id="heading-rewrites">Rewrites</h2>
<p>A rewrite sends the user to a new URI but changes the URI internally. The URI does not change for the user.</p>
<p>The rewrite directive is used for this. It accepts a regular expression as the 1st parameter and a URI as the 2nd parameter.</p>
<p>Rewrites are re-evaluated by NGINX as a completely new request, from the top down. This can consume little more system resources than a redirect.</p>
<p>A location block is needed for the new URI , like so:</p>
<pre><code class="lang-nginx">    <span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^/user/\w+</span> /meet;

    <span class="hljs-attribute">location</span> /meet {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Hello User"</span>;
    }
</code></pre>
<p>Here, <code>\w+</code> is used to capture a word after /user/</p>
<p>So, /user/melvin will get rewritten to /meet. This will match the location block after it and display "Hello User".</p>
<p>We may also use <strong>regex capture groups</strong> to get the first word and pass it to the rewritten URI, like so:</p>
<pre><code class="lang-nginx">    <span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^/user/(\w+)</span> /meet/<span class="hljs-variable">$1</span>;

    <span class="hljs-attribute">location</span> /meet {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Hello User"</span>;
    }

    <span class="hljs-attribute">location</span> = /meet/john {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Hello John"</span>;
    }
</code></pre>
<p>Here, the URI <code>/user/john</code> will get rewritten to <code>/meet/john</code> and will match the exact match location as it has higher priority than the prefix match above.</p>
<h3 id="heading-the-last-flag">the last flag</h3>
<p>It is added at the end of a rewrite directive to make sure that it does not get rewritten again, even if there are other rewrite statements matching the new URI.</p>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {

    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    <span class="hljs-attribute">server_name</span> <span class="hljs-number">167.99.93.26</span>;

    <span class="hljs-attribute">root</span> /sites/demo;

    <span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^/user/(\w+)</span> /meet/<span class="hljs-variable">$1</span> <span class="hljs-literal">last</span>;
    <span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^/meet/john</span> /thumb.png;

    <span class="hljs-attribute">location</span> /meet {

      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Hello User"</span>;
    }

    <span class="hljs-attribute">location</span> = /meet/john {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Hello John"</span>;
    }
  }
</code></pre>
<p>Here, <code>/user/john</code> gets rewritten to <code>/meet/john</code></p>
<p>There is a second rewrite directive that matches <code>/meet/john</code> and rewrites it to <code>/thumb.png</code>, but...</p>
<p>Since the <code>last</code> flag is added to the first rewrite, the second rewrite does not take effect. The user is served "Hello John".</p>
<h2 id="heading-tryfiles">try_files</h2>
<p>The try_files directive can be used in a server context or in a location context. It is often used with variables.</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> / {
    <span class="hljs-attribute">try_files</span> <span class="hljs-variable">$uri</span> <span class="hljs-variable">$uri</span>/ /index.html;
}
</code></pre>
<p>In this example, when a request is made to Nginx, it will try to find a file that matches the requested URI (<code>$uri</code>). If the file exists, Nginx will serve it. If the file doesn't exist, Nginx will try to find a directory that matches the requested URI (<code>$uri/</code>). If a directory is found, Nginx will look for an index file within that directory (e.g., <code>index.html</code>) and serve it.</p>
<p>The last argument is evaluated as a rewrite. So it should be something that does not give an error.</p>
<h3 id="heading-tryfiles-with-named-locations">try_files with named locations</h3>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {

    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    <span class="hljs-attribute">server_name</span> www.melvincv.com;

    <span class="hljs-attribute">root</span> /sites/mcv;

    <span class="hljs-attribute">try_files</span> <span class="hljs-variable">$uri</span> /mouse.png /meet <span class="hljs-variable">@friendly_404</span>;

    <span class="hljs-attribute">location</span> <span class="hljs-variable">@friendly_404</span> {
      <span class="hljs-attribute">return</span> <span class="hljs-number">404</span> <span class="hljs-string">"Sorry, that file could not be found."</span>;
    }

    <span class="hljs-attribute">location</span> /meet {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"Hello User"</span>;
    }

  }
</code></pre>
<p>In this example, the try_files directive will first try the URI, then <code>mouse.png</code>, then <code>/meet</code> and finally the named location <code>@friendly404</code></p>
<p>Note: <code>/meet</code> is defined in a location block, but NGINX will only check if there is a meet folder relative to the site root.</p>
]]></content:encoded></item><item><title><![CDATA[Variables in NGINX]]></title><description><![CDATA[In this post, we will see how to use nginx variables in a config file. NGINX variables are a powerful tool that can be used to dynamically generate…]]></description><link>https://blog.melvincv.com/variables-in-nginx</link><guid isPermaLink="true">https://blog.melvincv.com/variables-in-nginx</guid><category><![CDATA[nginx]]></category><category><![CDATA[variables]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Thu, 13 Jul 2023 07:31:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cvBBO4PzWPg/upload/9b6837ad46ddbaffdd362fc1bdda6833.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post, we will see how to use nginx variables in a config file.</p>
<p>NGINX variables are a powerful tool that can be used to dynamically generate content, control routing, and perform other tasks. Variables can be set in the NGINX configuration file, or they can be passed in from the environment.</p>
<p>There are many different types of NGINX variables, including:</p>
<ul>
<li><p><strong>Request variables:</strong> These variables contain information about the HTTP request, such as the client IP address, the requested URI, and the HTTP method.</p>
</li>
<li><p><strong>Server variables:</strong> These variables contain information about the server, such as the server name, the server port, and the server software version.</p>
</li>
<li><p><strong>Environment variables:</strong> These variables contain information that is passed in from the environment, such as the user's username or the current time.</p>
</li>
</ul>
<p>Variables can be used in a variety of ways in NGINX configuration files. For example, you can use variables to:</p>
<ul>
<li><p><strong>Generate dynamic content</strong>, such as personalized web pages or product recommendations.</p>
</li>
<li><p><strong>Control routing</strong>, such as redirecting requests to different servers based on the client's IP address.</p>
</li>
<li><p><strong>Perform logging and auditing</strong>, such as tracking the number of requests that are made to a particular URI.</p>
</li>
</ul>
<h2 id="heading-real-world-application-of-nginx-variables">Real-world application of NGINX variables</h2>
<p>A company wants to create a website that allows users to log in and view their account information. The company can use a variable to store the user's username in the NGINX configuration file. This variable can then be used to control routing, so that requests from the user are redirected to the appropriate page.</p>
<p>For example, the following configuration file would redirect requests from the user <code>johndoe</code> to the <code>/account/johndoe</code> page:</p>
<pre><code class="lang-nginx"><span class="hljs-attribute">location</span> /account {
    <span class="hljs-attribute">if</span> (<span class="hljs-variable">$http_user_agent</span> <span class="hljs-regexp">~ "^johndoe$")</span> {
        <span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^/account(.*)</span> /account/<span class="hljs-variable">$1</span>;
    }
}
</code></pre>
<p>This example uses a rewrite config, which we will discuss in the next article.</p>
<h2 id="heading-documentation">Documentation</h2>
<p><a target="_blank" href="https://nginx.org/en/docs/varindex.html">https://nginx.org/en/docs/varindex.html</a></p>
]]></content:encoded></item><item><title><![CDATA[Create an NGINX Virtual Host]]></title><description><![CDATA[This article explains how to create a simple virtual host configuration to host a website on NGINX. I used Ubuntu 22.04 LTS for this tutorial. To tell…]]></description><link>https://blog.melvincv.com/create-an-nginx-virtual-host</link><guid isPermaLink="true">https://blog.melvincv.com/create-an-nginx-virtual-host</guid><category><![CDATA[nginx]]></category><category><![CDATA[configuration]]></category><category><![CDATA[Virtual Host]]></category><dc:creator><![CDATA[Melvin C Varghese (melvincv)]]></dc:creator><pubDate>Wed, 12 Jul 2023 08:09:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/yXrl2lkGJ-k/upload/c6ab53ff8e758bc04212df4fa4ff27ef.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article explains how to create a simple virtual host configuration to host a website on NGINX. I used Ubuntu 22.04 LTS for this tutorial.</p>
<p>To tell NGINX how to host our website and where it is located, write a server {} context with directives in it:</p>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {

    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    <span class="hljs-attribute">server_name</span> <span class="hljs-number">167.99.93.26</span>;

    <span class="hljs-attribute">root</span> /sites/demo;
  }
</code></pre>
<p>server_name: it can contain IP, Domains, and wildcard domains like *.example.com</p>
<p>root: the website files root path</p>
<p>listen: the server listens on port 80</p>
<h3 id="heading-test-and-reload-nginx">Test and Reload NGINX</h3>
<pre><code class="lang-nginx"><span class="hljs-attribute">nginx</span> -t
sudo systemctl reload nginx
</code></pre>
<h2 id="heading-location-blocks">Location Blocks</h2>
<p>location {} blocks intercept a request that matches the URI specified and serves content that matches the rules specified within it.</p>
<p>location blocks have 5 ways of URL matching:</p>
<ol>
<li><p>Prefix match</p>
</li>
<li><p>Preferential prefix match</p>
</li>
<li><p>Exact match</p>
</li>
<li><p>REGEX match (case sensitive)</p>
</li>
<li><p>REGEX match (case insensitive)</p>
</li>
</ol>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {

    <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
    <span class="hljs-attribute">server_name</span> <span class="hljs-number">167.99.93.26</span>;

    <span class="hljs-attribute">root</span> /sites/demo;

    <span class="hljs-comment"># Preferential Prefix match</span>
    <span class="hljs-attribute">location</span><span class="hljs-regexp"> ^~</span> /Greet2 {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">'Hello from NGINX "/greet" location.'</span>;
    }

    <span class="hljs-comment"># Exact match</span>
    <span class="hljs-attribute">location</span> = /greet {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">'Hello from NGINX "/greet" location - EXACT MATCH.'</span>;
    }

    <span class="hljs-comment"># REGEX match - case sensitive</span>
    <span class="hljs-attribute">location</span> <span class="hljs-regexp">~ /greet[0-9]</span> {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">'Hello from NGINX "/greet" location - REGEX MATCH.'</span>;
    }

    <span class="hljs-comment"># REGEX match - case insensitive</span>
    <span class="hljs-attribute">location</span> <span class="hljs-regexp">~* /greet[0-9]</span> {
      <span class="hljs-attribute">return</span> <span class="hljs-number">200</span> <span class="hljs-string">'Hello from NGINX "/greet" location - REGEX MATCH INSENSITIVE.'</span>;
    }
  }
</code></pre>
<h3 id="heading-priority-of-url-matching">Priority of URL matching</h3>
<ol>
<li><p>Exact match</p>
</li>
<li><p>Preferential prefix match</p>
</li>
<li><p>REGEX match</p>
</li>
<li><p>Prefix match</p>
</li>
</ol>
<p>Preferential prefix match is the same as prefix match, except that it has more priority than regex matches</p>
<p>REGEX matches require the Perl PCRE library. They are used to match URL patterns.</p>
<p>The exact match matches only the specified path, but nothing after it.</p>
<p>The prefix match matches the path and everything after it.</p>
]]></content:encoded></item></channel></rss>