<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Fakhri Abdillah on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Fakhri Abdillah on Medium]]></description>
        <link>https://medium.com/@mfakhriabdillah?source=rss-9bef1fd6715a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IdaA5lqAXyAgGrv1ZRyr8w.png</url>
            <title>Stories by Muhammad Fakhri Abdillah on Medium</title>
            <link>https://medium.com/@mfakhriabdillah?source=rss-9bef1fd6715a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:55:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mfakhriabdillah/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Safely Host Production and Staging on the Same AWS EC2]]></title>
            <link>https://medium.com/@mfakhriabdillah/how-to-safely-host-production-and-staging-on-the-same-aws-ec2-8b4442479342?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b4442479342</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[aws-certificate-manager]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 08:09:33 GMT</pubDate>
            <atom:updated>2026-08-07T08:09:33.355Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes, to save money or resources, you might need to put your production (live) website and your staging (testing) website on the same AWS EC2 server.</p><p>Is this a bad idea? It can be. If your staging website has an error and uses too much CPU, your live website might crash too! However, if you really must do this, you can set it up safely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*SXwDYgW-ysqMOEowtxjrgw.png" /></figure><p>The secret is to use an <strong>AWS Application Load Balancer (ALB)</strong> to manage the traffic and security before it even reaches your server. Here is a step-by-step guide to doing it the right way.</p><h3>Step 1: Request a New SSL Certificate</h3><p>First, you need a secure HTTPS connection for your new staging domain (for example, staging.domain.com).</p><ul><li>Go to <strong>AWS Certificate Manager (ACM)</strong>.</li><li>Request a new public certificate for your staging domain.</li><li>Validate it using Route 53 (DNS validation).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xnyc9fCiw5a7xSVLLXn-cA.png" /></figure><p><strong>Will my live website go down?</strong> No! Requesting a new certificate happens in the background. There is <strong>zero downtime</strong> for your production website.</p><h3>Step 2: Add the Certificate to Your ALB (Using SNI)</h3><p>Did you know that one Load Balancer can hold many SSL certificates at the same time? This is possible because of a technology called <strong>SNI (Server Name Indication)</strong>.</p><ul><li>Go to the EC2 Dashboard and find your <strong>Load Balancer</strong>.</li><li>Click on your <strong>HTTPS:443 Listener</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvgB2HrraX0v19zx9eSeyA.png" /></figure><ul><li>Go to the <strong>Certificates</strong> tab and click <strong>Add certificate</strong>.</li><li>Choose your new staging certificate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuIjVA5DaRXIPv5H3qyMhw.png" /></figure><p>Now, your ALB can securely serve both your production and staging domains.</p><h3>Step 3: Keep Staging Private (IP Whitelisting)</h3><p>You do not want the public, search engines, or hackers to see your staging website. The best way to protect it is by blocking unknown IP addresses.</p><p>Because both websites share the same server, you cannot use an AWS Security Group (if you block an IP in the Security Group, they can’t see the live website either!). Instead, we will use <strong>ALB Listener Rules</strong>.</p><p>In your HTTPS Listener, create these two rules:</p><p><strong>Rule 1 (Allow your office):</strong></p><ul><li><strong>Condition:</strong> IF Host header is staging.domain.com AND Source IP is your office IP (e.g., 203.0.113.50/32).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZk9KvL3K4i7931P2rLBew.png" /></figure><ul><li><strong>Action:</strong> Forward to your EC2 Target Group.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZfaWqw92en33S9T-FP8aw.png" /></figure><ul><li><em>Set this as Priority 1.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoRN5VpDB3oUzlzFJhfdiw.png" /></figure><p><strong>Rule 2 (Block everyone else):</strong></p><ul><li><strong>Condition:</strong> IF Host header is staging.domain.com.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6XDQUeWFYOC7h5glOeFGg.png" /></figure><ul><li><strong>Action:</strong> Return fixed response (Response code: 403, Body: Access Denied).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sw5F-DX-ke34CbVyoF66A.png" /></figure><ul><li><em>Set this as Priority 2.</em></li></ul><p>With these rules, AWS will automatically block unauthorized people before they even touch your EC2 server.</p><h3>Step 4: Configure Nginx in Your EC2</h3><p>Finally, you need to tell your EC2 server how to handle the staging files.</p><p>Log into your EC2 server and create a new <strong>Virtual Host</strong> in Nginx for staging.domain.com. Make sure the document root points to your staging folder, not your production folder.</p><h3>Conclusion</h3><p>Hosting production and staging on the same server is not perfect, but with AWS ALB, you can make it very secure. By using ALB Listener Rules and SNI, you keep your SSL certificates organized and your staging environment completely hidden from the public!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4442479342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tales from a Battle-Tested Migration: Moving a Complex Oracle DB to PostgreSQL on GCP]]></title>
            <link>https://medium.com/@mfakhriabdillah/tales-from-a-battle-tested-migration-moving-a-complex-oracle-db-to-postgresql-on-gcp-9b4f5b1f1238?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b4f5b1f1238</guid>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[google-cloud-sql]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[oracle-database]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 16:23:58 GMT</pubDate>
            <atom:updated>2026-06-13T01:37:52.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction &amp; The Big Plan</h3><p>Database migrations always look easy in presentations. But in real life, with old and complex enterprise databases, it is very hard and full of surprises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBjQzpsCc1Gd7B5tDiYXXA.png" /></figure><p>In this article, I will share my experience moving a legacy Oracle database to Cloud SQL for PostgreSQL. We used a cloud-native Database Migration Service (DMS).</p><p><strong>How big was it?</strong></p><ul><li><strong>Size:</strong> About 680 tables.</li><li><strong>Business areas:</strong> financial, hr, payment, and analytics.</li><li><strong>Complexity:</strong> It had many partitioned tables and thousands of lines of old trigger code.</li></ul><p>This is not a simple “how-to” guide. This is a real story about the problems we faced and exactly how we fixed them.</p><blockquote><strong>A Quick Note Before We Start:</strong> &gt; Just a small spoiler! To protect company privacy, all the database, schema, and table names in this article have been changed. They are not the real names. However, the story, the errors, and the exact steps I took to fix them are 100% based on my real experience.</blockquote><h3>The Pre-Flight Battle — Fixing the Code Translation</h3><p>Before we even tried to copy the data, we faced a big problem. We needed to translate the old database structure (the schema) so PostgreSQL could understand it.</p><p><strong>The Struggle:</strong> We used an automatic tool called the Conversion Workspace to translate the code. Many people think these tools will magically convert everything to 100%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JGd-_BPVRRCa55c30GMVQ.png" /></figure><p>But in the real world, the automatic tool failed on many parts of our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqYZ0GZTU_DMu_H9qnk2Hw.png" /></figure><p><strong>The Core Issue:</strong> Oracle and PostgreSQL speak different languages for their logic. Oracle uses PL/SQL, and PostgreSQL uses PL/pgSQL. The automatic tool was good at simple tables, but it got confused easily. It could not automatically translate complex code, custom data types, or special rules (constraints) that only exist in Oracle.</p><p><strong>The Hard Work:</strong> We had to do the hard work by hand. Our team spent days checking the errors, and fixing the definitions in the Conversion Workspace.</p><p><strong>The lesson</strong> here is simple: <strong>automatic tools are great</strong> to make the job faster, but <strong>they are not perfect</strong>. You always need a human expert to review the code, find the translation errors, and rewrite the difficult parts so they work perfectly in PostgreSQL.</p><h3>Act 1 — The Invisible Block (Cloud System Error)</h3><p>We prepared everything for weeks. The connections were good, and the schemas were ready. We clicked “Start Migration.”</p><p>Immediately, it stopped. The console just said Internal Error. There were no logs to tell us why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGpJ2evIZ_7y6mgStDz2Xw.png" /></figure><p><strong>The Lesson:</strong> Do not always think your code or your network is the problem. Sometimes, the managed cloud service has a bug on their side.</p><p><strong>The Fix:</strong> We contacted the cloud provider’s enterprise support team (Shoutout to the GCP product and support team!). They checked their system and found a rare bug because our starting data was too big. Their team had to manually change a hidden setting on their backend so our migration could start.</p><h3>Act 2 — Stuck at 99% (The Timeout Problem)</h3><p>After the support team fixed the error, the data copy started. It went very fast up to 99%. Then, it stopped completely. The logs showed this error:</p><blockquote><em>DEADLINE_EXCEEDED </em><em>Operation timed out: context deadline exceeded</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqgWiOUvIEp8-f2tThTmew.png" /></figure><p><strong>The Cause:</strong> The problem was one very big table: hr.attendance_logs_archived. It had years of data (this database was created about 2006, btw). The migration tool tries to read data in pieces. But this table was so heavy that the tool took too long to read one piece, so it hit a time limit (timeout) and stopped.</p><p><strong>The Fix:</strong> The good thing about DMS is that it did not delete the 99% of data that was already copied! It just kept trying the failed table. We increase the timeout limit for the migration job configuration. After we gave it more time, the last 1% finished successfully. Fyuh~</p><h3>Act 3 — Partition Problems &amp; Name Errors</h3><p>In the middle of the project, we needed to update some tables. When we did this, the destination database gave a “missing primary key” error. We tried to add a normal Primary Key, but PostgreSQL gave this error:</p><blockquote><em>unique constraint on partitioned table must include all partitioning columns</em></blockquote><p><strong>The Reason:</strong> PostgreSQL has strict rules. If a table has partitions, the Primary Key <strong>must</strong> include the column used for the partition.</p><p><strong>The Fix:</strong> We had to change the SQL to include the partition column like this:</p><pre>ALTER TABLE analytics.dashboard_metrics <br>ADD CONSTRAINT pk_dashboard_metrics PRIMARY KEY (id_migrate, partition_dimension);</pre><p><strong>Watch out for names:</strong> In PostgreSQL, if you give the primary key the exact same name as the table, it will give an error. It is easier to let PostgreSQL make the name automatically:</p><pre>-- Do not give a name, let Postgres do it<br>ALTER TABLE financial.invoice_registry ADD PRIMARY KEY (invoice_id, period_id);</pre><p><em>Note: Also, if your migration tool needs helper columns like </em><em>rowid numeric(33,0), make sure to add them back if they get deleted during table updates.</em></p><h3>Act 4 — Triggers Make Trouble (The Superuser Rule)</h3><p>We reached the final step: copying live data. Suddenly, the migration stopped on many tables like payment.transaction_records and financial.ledger_entries.</p><p>The old database triggers were running by mistake on the new data. We saw many bad errors in the logs:</p><ul><li>invalid transaction termination ... line XX at COMMIT: Old triggers tried to use COMMIT, but PostgreSQL does not allow this inside trigger functions.</li><li>function error_unimplemented() does not exist: The automatic conversion tool put fake functions in the code because it did not understand the old Oracle code.</li><li>syntax error at or near &quot;:&quot;: The code still had old variable styles (:).</li><li>We also had to run CREATE EXTENSION IF NOT EXISTS pgcrypto; because the database could not make UUIDs.</li></ul><p><strong>The Superuser Problem:</strong> We tried to turn off all triggers easily by running ALTER TABLE ... DISABLE TRIGGER ALL;. But we got a permission error:</p><blockquote><em>permission denied: &quot;RI_ConstraintTrigger_...&quot; is a system trigger</em></blockquote><p>Cloud SQL does not let you act like a superuser to change system triggers (like foreign keys) because it wants to keep the database safe.</p><p><strong>The Fix:</strong> We had to use the USER command. This turns off only our custom triggers and leaves the system triggers alone:</p><pre>ALTER TABLE financial.ledger_entries DISABLE TRIGGER USER;</pre><h3>Conclusion &amp; What To Do Next</h3><p>In the end, the migration reached 100%. The data was correct, and the new PostgreSQL database worked perfectly.</p><p>But before you let real users use the new database, you must fix the messy code. We gave this checklist to our developers:</p><ul><li><strong>Turn Triggers On:</strong> Run ENABLE TRIGGER USER to turn the custom triggers back on.</li><li><strong>Fix Fake Functions:</strong> Developers must rewrite the error_unimplemented() placeholder functions into real PostgreSQL code.</li><li><strong>Remove Commits:</strong> Remove all COMMIT commands from the trigger code.</li><li><strong>Clean Variables:</strong> Find and remove the old : variables from the code strings.</li></ul><p>Moving big databases is hard. But if you know how PostgreSQL works, understand your cloud limits, and know how to handle old code, you can finish the migration successfully!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b4f5b1f1238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fearless Database Upgrades: A Practical Guide to AWS RDS Blue/Green Deployments]]></title>
            <link>https://medium.com/@mfakhriabdillah/fearless-database-upgrades-a-practical-guide-to-aws-rds-blue-green-deployments-25cd00117817?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25cd00117817</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rds]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 10:21:10 GMT</pubDate>
            <atom:updated>2025-09-25T10:21:10.326Z</atom:updated>
            <content:encoded><![CDATA[<p>Legacy tech stacks in a production environment are a ticking time bomb. While many teams delay essential database upgrades out of a classic fear of breaking changes, downtime, and complex code refactoring, the risk of inaction is far greater.</p><p>Sticking with outdated technology introduces two critical business risks:</p><ul><li><strong>Security Vulnerabilities:</strong> End-of-Life (EOL) software no longer receives security patches, leaving your systems exposed to exploits.</li><li><strong>Rising Costs:</strong> Cloud providers often charge premium fees for Extended Support on EOL database versions, ironically making it more expensive to <em>not</em> upgrade.</li></ul><p>Beyond mitigating risks, upgrading unlocks proactive benefits that drive a business forward, including significant performance gains, compatibility with the modern tech ecosystem, and the ability to innovate faster with new database features.</p><p>The question, then, isn’t <em>why</em> we should upgrade, but <strong>how can we do it safely? </strong>In a recent project, I successfully transformed a planned 14-minute downtime into an actual downtime of just one minute.</p><p>This is the challenge elegantly solved by <strong>AWS RDS Blue/Green Deployments</strong>.</p><h3>What is an AWS RDS Blue/Green Deployment?</h3><p>An RDS Blue/Green Deployment is a managed feature designed for safe, seamless database upgrades. Instead of performing a risky in-place upgrade on your live database, this method creates an identical, isolated, and synchronized staging environment.</p><p>Here’s how it works technically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*PyA8bjiUtI8Oe-S4qoSLYw.png" /></figure><ul><li><strong>The Blue Environment:</strong> This is your current, live production database.</li><li><strong>The Green Environment:</strong> AWS creates a topological copy of your Blue environment, including the primary instance and any read replicas. This Green environment stays continuously synchronized with Blue using logical replication.</li><li><strong>The Upgrade &amp; Testing Process:</strong> All changes — version upgrades, schema modifications, or parameter tuning — are applied exclusively to the isolated Green environment. This allows for thorough functional and performance testing without affecting production traffic.</li><li><strong>The Switchover:</strong> When you are ready, AWS initiates a switchover. This process briefly blocks writes to both environments, waits for the Green environment to be perfectly in sync, and then promotes Green to be the new production by redirecting your database’s DNS endpoint to it.</li></ul><h3>Key Advantages: Upgrading with Confidence</h3><p>This method provides several strategic benefits for technical teams.</p><p><strong>1. Near-Zero Downtime (Under 60 Seconds)</strong> The switchover process is engineered by AWS to be incredibly fast. The period of write unavailability typically lasts less than a minute. To give a real-world example, <strong>I used this method to reduce a planned 14-minute maintenance window to an actual downtime of just one minute.</strong> This is a game-changer for critical applications.</p><p><strong>2. Isolated, High-Fidelity Testing</strong> The Green environment is a precise replica of production, allowing QA and DevOps teams to conduct realistic load testing, verify query plans, and perform full functional validation against the new database version, eliminating surprises post-deployment.</p><p><strong>3. Safe and Predictable Rollbacks</strong> If a critical issue is discovered after the switchover, recovery is simple. The old Blue environment is never modified and remains on standby. This allows for a quick and controlled switch back, avoiding stressful and complex database restoration scenarios.</p><h3>Technical Considerations and Costs</h3><p>While powerful, there are a few factors to consider.</p><p><strong>1. Temporary Cost Implications</strong> Running two database environments in parallel incurs double the RDS instance costs for the duration of the process. This is a trade-off: you are investing in infrastructure costs to guarantee safety, predictability, and service availability.</p><p><strong>2. Prerequisites and Limitations</strong> The feature has specific prerequisites and configuration limitations. For complete details, it is essential to review the <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-considerations.html"><strong>official AWS documentation</strong></a>.</p><h3>Practical Guide: Creating a Blue/Green Deployment</h3><p>Let’s walk through the steps to create, test, and perform a switchover using the AWS RDS Console.</p><h4>Prerequisites</h4><p>Before we begin, ensure your environment meets these key requirements:</p><ul><li><strong>Supported Engines:</strong> RDS for MySQL, RDS for MariaDB, or RDS for PostgreSQL.</li><li><strong>Automated Backups:</strong> Must be enabled on the Blue (production) instance.</li><li><strong>Specific Parameters:</strong> Ensure log_bin (MySQL/MariaDB) or rds.logical_replication (PostgreSQL) is enabled.</li><li><strong>Standalone Topology:</strong> The Blue instance cannot be a read replica of another instance.</li></ul><h4>Step 1: Create the Green Environment</h4><ol><li>Navigate to the <strong>Amazon RDS Console</strong>, go to <strong>Databases</strong>, and select your production instance.</li><li>From the <strong>Actions</strong> menu, select <strong>Create Blue/Green Deployment</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DchqX62c_pCGyaShJV9-2g.png" /><figcaption><em>The “Create Blue/Green Deployment” option in the Actions menu.</em></figcaption></figure><p>On the configuration page, specify the following:</p><ul><li><strong>Blue/Green deployment identifier:</strong> Use a descriptive name, like db-prod-upgrade-to-mysql8.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbCCunGUPOk7smWO_nF6bQ.png" /></figure><ul><li><strong>Engine version:</strong> Select the target database version for the Green environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqmzNBg_x8vXEbReXgEBjg.png" /></figure><blockquote><strong>Pro-Tip:</strong> To optimize costs during the testing phase, you can select a less powerful instance class for the Green environment (e.g., t3.medium). You can then modify it to match the production spec right before the switchover.</blockquote><p>Once configured, click <strong>Create Blue/Green Deployment</strong>. This process can take from minutes to hours, depending on your database size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*pnB_UpIM74naMySG3oK39A.png" /><figcaption><em>The status screen after a Blue/Green Deployment has been created.</em></figcaption></figure><h4>Step 2: Verify and Test the Green Environment</h4><p>Once the deployment status shows as Ready for switchover, it is time for the most critical phase: testing.</p><ol><li><strong>Identify the Green Endpoint:</strong> Find the writer and reader endpoints for the Green instance in the deployment details.</li><li><strong>Connect Your Staging Application:</strong> Point your staging environment or testing tools to the Green endpoint.</li><li><strong>Conduct Thorough Testing:</strong> Run functional regression tests, performance load tests, and analyze slow query logs to ensure everything performs as expected.</li></ol><h4>Step 3: Execute the Switchover</h4><p>Once all tests have passed, you can proceed with the switchover.</p><ol><li>Navigate to the <strong>Blue/Green deployments</strong> page, select your deployment, and from the <strong>Actions</strong> menu, choose <strong>Switch over</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bH2mTd-tfcnLxpXsDWm_Dw.png" /></figure><p>Configure the <strong>Timeout</strong> setting. This is a safety net that automatically cancels the switchover if it takes too long. Confirm by typing Switch over and click the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrfH93vKM4OW2sSsXAmZXg.png" /></figure><p>The process will begin, briefly placing your database in a read-only state for less than a minute. When complete, your primary database endpoint will point to the newly upgraded instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*BCaCsWIb8VnHFZenq0Tqmg.png" /></figure><blockquote><strong><em>Important:</em></strong><em> Immediately after the switchover, perform a final validation on your production application to ensure everything is operating smoothly.</em></blockquote><h3>Conclusion</h3><p>Upgrading a production database no longer needs to be a high-stakes, stressful event. With AWS RDS Blue/Green Deployments, we can transform a high-risk procedure into a controlled, tested, and safe operation.</p><p>This method allows teams to embrace the benefits of modern database technology — from performance to security — without sacrificing the stability and availability of their services. While it requires a temporary cost investment, the peace of mind and confidence it provides during deployment are invaluable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25cd00117817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ID] Upgrade Database Minim Downtime dengan Blue/Gree Deploymet]]></title>
            <link>https://medium.com/@mfakhriabdillah/upgrade-database-minim-downtime-dengan-blue-gree-deploymet-c1bd983f4a51?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bd983f4a51</guid>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[database-migration]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 05:02:17 GMT</pubDate>
            <atom:updated>2025-09-23T05:19:22.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Dalam beberapa kasus yang pernah saya jumpai, arsitektur yang bisa dibilang ‘jadul’ ternyata masih umum diandalkan di lingkungan <em>production</em>. Sebut saja server yang digunakan masih menggunakan Ubuntu 16.04, PHP versi 5.x, hingga database MySQL 5.x.</p><p>Saat diskusi, alasan mereka untuk tidak melakukan <em>upgrade</em> biasanya klasik: kekhawatiran bahwa prosesnya akan memicu <em>breaking changes</em>. Ada ketakutan bahwa perlu ada penyesuaian besar dari sisi aplikasi, optimalisasi <em>query database</em>, hingga <em>refactoring code</em> yang kompleks dan memakan waktu. Sepintas, argumen ini terdengar masuk akal, terutama jika ada keterbatasan sumber daya atau tenaga ahli.</p><p>Namun, mempertahankan <em>status quo</em> ini justru menyimpan bom waktu yang bisa merugikan perusahaan dari dua sisi krusial:</p><ul><li><strong>Keamanan:</strong> <em>Stack</em> teknologi yang usang sering kali sudah melewati masa <em>support</em> resminya (End-of-Life). Artinya, tidak ada lagi pembaruan keamanan yang dirilis, menjadikannya sasaran empuk untuk celah eksploitasi baru.</li><li><strong>Biaya (Cost):</strong> Ironisnya, upaya menunda <em>upgrade</em> untuk berhemat justru bisa membengkakkan biaya. Banyak <em>cloud provider</em> mengenakan biaya premium untuk <em>Extended Support</em> agar database versi lama yang sudah <em>End-of-Support</em> (EOS) tetap bisa berjalan.</li></ul><p>Namun, alasan untuk upgrade tidak berhenti pada mitigasi risiko. Ada keuntungan proaktif yang bisa mendorong bisnis dan tim ke level berikutnya, seperti:</p><ul><li><strong>Performa dan efisiensi:</strong> Versi database yang lebih baru hampir selalu datang dengan peningkatan performa yang drastis.</li><li><strong>Kompatibilitas:</strong> Dunia teknologi bergerak cepat. <em>Library</em>, <em>framework</em>, dan <em>tools</em> baru seringkali menghentikan dukungan untuk versi database yang sudah ”jadul”.</li><li><strong>Mempercepat Inovasi:</strong> Teknologi lama membatasi kreativitas. Versi baru membuka pintu untuk fungsionalitas yang dulu mustahil.</li></ul><p>Dengan semua keuntungan ini — mulai dari performa yang lebih kencang, tim yang lebih produktif, hingga inovasi produk yang tak terbatas — keputusan untuk melakukan <em>upgrade</em> terasa seperti sebuah keharusan.</p><p>Namun, pertanyaan terbesarnya tetap sama: <strong>Bagaimana cara melakukannya dengan aman?</strong></p><p>Bagaimana kita bisa memigrasikan database produksi yang krusial dengan risiko <em>downtime</em> mendekati nol dan menyediakan jalur kembali (<em>rollback</em>) yang aman jika terjadi masalah? Inilah tantangan yang dijawab secara elegan oleh AWS melalui fitur <strong>RDS Blue/Green Deployments</strong>.</p><h3>Mengenal AWS RDS Blue/Green Deployment</h3><p>AWS RDS Blue/Green Deployment adalah sebuah fitur terkelola (<em>managed feature</em>) yang dirancang untuk membuat proses upgrade database mayor atau minor menjadi lebih aman dan minim disrupsi. Alih-alih melakukan <em>in-place upgrade</em> yang berisiko pada database produksi, metode ini bekerja dengan menciptakan lingkungan <em>staging</em> yang identik, terisolasi, namun tetap sinkron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*PyA8bjiUtI8Oe-S4qoSLYw.png" /></figure><p>Secara teknis, prosesnya berjalan sebagai berikut:</p><ul><li><strong>Lingkungan Blue:</strong> Ini adalah lingkungan database produksi kita yang sedang berjalan saat ini.</li><li><strong>Lingkungan Green:</strong> AWS akan membuat salinan topologi dari lingkungan Blue, termasuk <em>instance</em> utama, <em>read replicas</em>, dan konfigurasi lainnya. Lingkungan Green ini akan terus sinkron dengan Blue menggunakan replikasi logis (<em>logical replication</em>).</li><li><strong>Proses Upgrade &amp; Uji Coba:</strong> Semua perubahan dilakukan secara eksklusif di lingkungan Green. Karena terisolasi, kita bisa melakukan pengujian fungsional dan performa secara menyeluruh tanpa memengaruhi <em>traffic</em> produksi sama sekali.</li><li><strong><em>Switchover</em>:</strong> Ini adalah momen krusial. Ketika kita siap, AWS akan memulai proses <em>switchover</em>. Proses ini akan memblokir penulisan (<em>writes</em>), menunggu sinkronisasi akhir, lalu mempromosikan Green menjadi lingkungan produksi yang baru dengan mengalihkan <em>endpoint</em> DNS database kita.</li></ul><h3>Kelebihan Utama: Upgrade dengan Keyakinan Penuh</h3><p>Menggunakan metode ini memberikan beberapa keuntungan strategis yang krusial bagi tim teknis.</p><p><strong>1. Downtime Kurang dari Satu Menit</strong> Salah satu keunggulan terbesar adalah minimnya periode nonaktif. Proses <em>switchover</em> dirancang oleh AWS untuk secepat mungkin, dengan <em>downtime</em> (lebih tepatnya, <em>write unavailability</em>) yang biasanya berlangsung di bawah 60 detik. Ini sangat ideal untuk aplikasi kritikal.</p><p><strong>2. Uji Coba di Lingkungan Terisolasi</strong> Kita tidak lagi perlu menebak-nebak dampak dari sebuah <em>upgrade</em>. Lingkungan Green adalah replika presisi dari produksi, memungkinkan tim QA dan DevOps untuk melakukan <em>load testing</em>, verifikasi <em>query plan</em>, dan validasi fungsional aplikasi secara menyeluruh.</p><p><strong>3. Rollback yang Aman dan Terprediksi</strong> Jika setelah <em>switchover</em> terdeteksi adanya masalah, proses pemulihannya sangat aman. Lingkungan Blue (yang lama) tidak pernah dimodifikasi dan tetap siaga, memungkinkan proses <em>switch back</em> yang cepat jika diperlukan.</p><h3>Pertimbangan Teknis dan Biaya</h3><p>Meskipun sangat <em>powerful</em>, ada beberapa hal yang perlu dipertimbangkan sebelum mengadopsi metode ini.</p><p><strong>1. Implikasi Biaya Sementara</strong> Menjalankan dua lingkungan database secara paralel berarti ada biaya ganda untuk <em>instance</em> RDS selama durasi proses. Ini adalah sebuah <em>trade-off</em> untuk “membeli” jaminan keamanan dan ketersediaan layanan yang tinggi.</p><p><strong>2. Prasyarat dan Keterbatasan</strong> Fitur ini memiliki beberapa prasyarat terkait konfigurasi. Untuk detail lengkap mengenai batasan ini, sangat disarankan untuk membaca <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-considerations.html"><strong>dokumentasi resmi dari AWS</strong></a>.</p><h3>Praktik: Membuat Blue/Green Deployment di AWS RDS</h3><p>Teori sudah kita pahami, sekarang saatnya mempraktikkannya. Bagian ini akan memandu kita melalui langkah-langkah untuk membuat, menguji, dan melakukan <em>switchover</em> menggunakan fitur Blue/Green Deployment di AWS RDS Console.</p><h4>Sebelum Memulai: Prasyarat Penting</h4><p>Pastikan lingkungan kita memenuhi beberapa syarat utama sebelum memulai:</p><ul><li><strong>Database yang Didukung:</strong> Fitur ini saat ini tersedia untuk RDS for MySQL, RDS for MariaDB, dan RDS for PostgreSQL.</li><li><strong>Backup Otomatis:</strong> <em>Automated backups</em> harus diaktifkan pada <em>instance</em> database Blue.</li><li><strong>Parameter Tertentu:</strong> Pastikan parameter log_bin (MySQL/MariaDB) atau rds.logical_replication (PostgreSQL) aktif.</li><li><strong>Bukan Bagian dari Topologi Lain:</strong> <em>Instance</em> Blue tidak boleh menjadi <em>read replica</em> dari <em>instance</em> lain.</li></ul><h4>Langkah 1: Membuat Lingkungan Green</h4><ol><li>Buka <strong>Amazon RDS Console</strong>, navigasi ke <strong>Databases</strong>, dan pilih <em>instance</em> produksi yang ingin di-upgrade.</li><li>Klik menu <strong>Actions</strong> di pojok kanan atas, lalu pilih <strong>Create Blue/Green Deployment</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJZKxl-uC11UbaZhFZGSrg.png" /><figcaption>Tampilan opsi “Create Blue/Green Deployment” di menu Actions.</figcaption></figure><p>Di halaman konfigurasi, isi beberapa field berikut:</p><ul><li><strong>Blue/Green deployment identifier:</strong> Beri nama yang deskriptif, misalnya db-prod-upgrade-to-mysql8.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rd2nTzApiNxBbGA3FTJNKA.png" /></figure><ul><li><strong>Engine version:</strong> Pilih versi target database untuk lingkungan Green.</li><li><strong>TIPS:</strong> Untuk menghemat biaya, kita bisa menurunkan spesifikasi <em>instance</em> pada lingkungan Green saat tahap pembuatan dan pengujian (misalnya dari m7.2xlarge ke t3.medium). Spesifikasi bisa dinaikkan kembali sesaat sebelum <em>switchover</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BD_BqIRZQwj1bDMd6N1_aQ.png" /></figure><p>Sebagian besar pengaturan lain akan disalin dari lingkungan Blue. Jika sudah sesuai, klik <strong>Create Blue/Green Deployment</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uH_qhv5ESe6o8oi2D57a7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_dc-6QnYFqpJYY8F3SHpQ.png" /><figcaption><em>Tampilan status setelah Blue/Green Deployment berhasil dibuat.</em></figcaption></figure><h4>Langkah 2: Verifikasi dan Uji Coba Lingkungan Green</h4><p>Setelah status berubah menjadi Ready for switchover, jangan terburu-buru. Ini adalah kesempatan emas untuk melakukan pengujian.</p><ol><li><strong>Identifikasi Endpoint Green:</strong> Temukan <em>endpoint</em> untuk <em>writer</em> dan <em>reader</em> dari <em>instance</em> Green di halaman detail.</li><li><strong>Hubungkan Aplikasi (Staging):</strong> Arahkan koneksi dari aplikasi versi <em>staging</em> ke <em>endpoint</em> Green.</li><li><strong>Lakukan Pengujian Menyeluruh:</strong> Jalankan tes fungsional, tes performa, dan analisis <em>query</em> untuk memastikan semuanya berjalan baik.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKWVUi7i3xH8Vp4tQFaQWQ.png" /><figcaption>Endpoint lingkungan green</figcaption></figure><h4>Langkah 3: Eksekusi Switchover</h4><p>Jika semua pengujian sudah lolos, saatnya melakukan proses peralihan.</p><ul><li>Kembali ke halaman <strong>Blue/Green deployments</strong>, pilih deployment Anda, lalu dari menu <strong>Actions</strong> pilih <strong>Switch over</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBeT3qrqRatjHSwKSY9YDQ.png" /></figure><ul><li>Atur durasi <strong>Timeout</strong> (standarnya 30 menit) sebagai pengaman.</li><li>Ketik Switch over untuk mengonfirmasi dan klik tombolnya.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*BCaCsWIb8VnHFZenq0Tqmg.png" /></figure><p>Proses <em>switchover</em> akan dimulai. Selama momen singkat ini (biasanya kurang dari 1 menit), database akan berada dalam mode <em>read-only</em>. Setelah selesai, <em>endpoint</em> utama Anda akan mengarah ke <em>instance</em> baru.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6XbKEDyZ-HhX7C_T0GVjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7cJYVHk5dqrcmtcEX7DmQ.png" /></figure><blockquote><strong><em>Penting:</em></strong><em> Segera lakukan validasi akhir pada aplikasi produksi untuk memastikan semuanya berjalan lancar.</em></blockquote><h3>Kesimpulan</h3><p>Upgrade database di lingkungan produksi tidak lagi harus menjadi momen yang menakutkan. Dengan AWS RDS Blue/Green Deployment, kita bisa mengubah proses yang berisiko tinggi menjadi sebuah prosedur yang terkontrol, teruji, dan aman.</p><p>Metode ini memungkinkan kita untuk mendapatkan semua keuntungan dari teknologi database terbaru — mulai dari performa, keamanan, hingga fitur-fitur inovatif — tanpa harus mengorbankan stabilitas dan ketersediaan layanan. Meskipun memerlukan biaya tambahan sementara, ini adalah investasi yang sangat sepadan untuk sebuah ketenangan pikiran dan keyakinan penuh saat melakukan deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bd983f4a51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically Scale Your AWS RDS MySQL for Weekend Traffic Spikes]]></title>
            <link>https://medium.com/@mfakhriabdillah/automatically-scale-your-aws-rds-mysql-for-weekend-traffic-spikes-d9a3e390f5d6?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a3e390f5d6</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rds-mysql]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Mon, 05 May 2025 03:17:57 GMT</pubDate>
            <atom:updated>2025-05-05T03:17:57.456Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A Step-by-Step Guide Using AWS Lambda &amp; EventBridge</strong></p><p>If your application experiences higher traffic on weekends, manually scaling your RDS database can be tedious. Instead, you can automate this process using <strong>AWS Lambda</strong> and <strong>EventBridge (CloudWatch Events)</strong> to scale up your instance before the weekend and scale it back down afterward — with minimal downtime during off-peak hours.</p><p>In this guide, I’ll walk you through setting up a <strong>scheduled scaling solution</strong> for AWS RDS MySQL.</p><h3>Why Automate RDS Scaling?</h3><ol><li>Handle traffic spikes efficiently without over-provisioning 24/7</li><li>Reduce costs by downsizing when demand is low</li><li>Zero manual intervention — fully automated scaling</li></ol><h3><strong>How It Works</strong></h3><ol><li>AWS Lambda modifies the RDS instance class (CPU &amp; RAM).</li><li>EventBridge (CloudWatch Events) triggers the Lambda functions on a schedule.</li><li>Scale up before weekends, scale down after weekends.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoAB4sOzPXnkaVLTycM5XA.png" /><figcaption>System Flow Diagram: The RDS Scaling Rules</figcaption></figure><h3>Implementation</h3><h3>Step 1: Create the Lambda functions</h3><p><strong>Scale-Up Lambda (Weekend Configuration)</strong><br>This function upgrades your RDS instance to a larger size (e.g., db.m5.2xlarge).</p><pre>import boto3<br><br>def lambda_handler(event, context):<br>    client = boto3.client(&#39;rds&#39;)<br>    <br>    response = client.modify_db_instance(<br>        DBInstanceIdentifier=&#39;your-db-instance-name&#39;,  # Replace with your RDS name<br>        DBInstanceClass=&#39;db.m5.2xlarge&#39;,  # 8 vCPU, 32GB RAM<br>        ApplyImmediately=True  # Apply changes immediately (not during next maintenance window)<br>    )<br>    <br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: &#39;RDS instance scaled up successfully!&#39;<br>    }</pre><p><strong>Scale-Down Lambda (Weekday Configuration)</strong><br>This function downgrades your RDS instance to a smaller size (e.g., db.m5.xlarge).</p><pre>import boto3<br><br>def lambda_handler(event, context):<br>    client = boto3.client(&#39;rds&#39;)<br>    <br>    response = client.modify_db_instance(<br>        DBInstanceIdentifier=&#39;your-db-instance-name&#39;,  # Replace with your RDS name<br>        DBInstanceClass=&#39;db.m5.xlarge&#39;,  # 4 vCPU, 16GB RAM<br>        ApplyImmediately=True<br>    )<br>    <br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: &#39;RDS instance scaled down successfully!&#39;<br>    }</pre><p><strong>Deploying the Lambda Functions</strong></p><ol><li>Go to AWS Lambda → Create Function (Python 3.x runtime).</li><li>Paste the respective code.</li><li>Set an IAM role with permissions:<br><em>rds:ModifyDBInstance<br>rds:DescribeDBInstances (optional, for logging)</em></li></ol><p>IAM Permissions Required:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;rds:ModifyDBInstance&quot;,<br>        &quot;rds:DescribeDBInstances&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    }<br>  ]<br>}</pre><h3>Step 2: Schedule Scaling with EventBridge (CloudWatch Events)</h3><p>Now, we’ll trigger the Lambda functions automatically:</p><p><strong>Scale-Up on Friday Night (Before Weekend Traffic)</strong></p><ul><li><strong>When?</strong> Every Friday at 11 PM UTC.</li><li><strong>What?</strong> Triggers the scale_up_rds Lambda.</li></ul><h4>How to Set Up:</h4><ol><li>Go to <strong>Amazon EventBridge</strong> → <strong>Rules</strong> → <strong>Create Rule</strong>.</li><li><strong>Schedule</strong>: cron(0 23 ? * FRI *) (11 PM every Friday).</li><li><strong>Target</strong>: Select the scale_up_rds Lambda.</li></ol><h3>2. Scale-Down on Sunday Night (After Weekend Traffic)</h3><ul><li><strong>When?</strong> Every Sunday at 11 PM UTC.</li><li><strong>What?</strong> Triggers the scale_down_rds Lambda.</li></ul><h4>How to Set Up:</h4><ol><li><strong>Schedule</strong>: cron(0 23 ? * SUN *) (11 PM every Sunday).</li><li><strong>Target</strong>: Select the scale_down_rds Lambda.</li></ol><h3>Step 3: Testing &amp; Monitoring</h3><h3>Manual Test (Before Going Live)</h3><ul><li>Run the Lambda functions manually to verify scaling works.</li><li>Check <strong>RDS → Modifications</strong> to confirm changes.</li></ul><h3>Monitoring</h3><ul><li>Use <strong>CloudWatch Logs</strong> to track Lambda executions.</li><li>Set up <strong>RDS Performance Insights</strong> to verify scaling impact.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbqiwGfArcE97tXSlk6fMw.png" /><figcaption>Scaling Process in Graph</figcaption></figure><h3>Important Considerations</h3><p>✅ <strong>Downtime</strong>: Scaling requires a brief restart (~4–7 min). Schedule it during low-traffic periods.<br>✅ <strong>Backups</strong>: Ensure scaling doesn’t conflict with backup windows.<br>✅ <strong>Permissions</strong>: Lambda must have rds:ModifyDBInstance permissions.</p><h3>Alternative Approach: Aurora Serverless</h3><p>If downtime is a concern, consider <strong>Amazon Aurora Serverless v2</strong>, which auto-scales without manual intervention.</p><h3>Final Thoughts</h3><p>By automating RDS scaling, you optimize costs while handling traffic spikes efficiently. This setup is ideal for predictable workload changes (like weekend traffic).</p><h3>Enjoyed this guide?</h3><p>👉 Follow me on <a href="https://medium.com/@mfakhriabdillah">Medium</a> for more cloud &amp; DevOps tips!<br>🔗 Share this post if you found it helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a3e390f5d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce Your Docker Image Size using Multi-Stage Build]]></title>
            <link>https://medium.com/@mfakhriabdillah/reduce-your-docker-image-size-using-multi-stage-build-4260396d068a?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4260396d068a</guid>
            <category><![CDATA[multi-stage-builds]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 10:45:03 GMT</pubDate>
            <atom:updated>2024-08-03T10:45:03.874Z</atom:updated>
            <content:encoded><![CDATA[<p>On <a href="https://medium.com/@mfakhriabdillah/streamlining-golang-development-implementing-ci-cd-with-gitlab-ci-b89d384574d8">previous post</a>, we automate a Golang development using Giltab CI. And I just realized that the built image is sooo huge (for a simple apps like that, btw).<br>So I figured out how to make this image size more efficient. And i found that we can using a multi-stage build process on our Dockerfile.</p><h3>What is Multi-Stage Build?</h3><p>Multi-stage build is a technique that we can use multiple FROM statements in our Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. <br>So, how it’s works in our Dockerfile? Let’s we try!<br>In our previous post, we using this Dockerfile</p><pre>FROM golang:alpine3.16 <br>WORKDIR /app <br>COPY . . <br>RUN go mod download <br>RUN go build -o goapp <br>EXPOSE 8080 <br>ENTRYPOINT [&quot;./app/goapp&quot;]</pre><p>After we built the Docker image using <em>docker build</em> command, we can see that the size are quite big (600MB).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*xxNF0gUJx2aGwXKx3U1e3w.png" /></figure><p>Let’s implement the multi-stage build.<br>In the first build stage, we import the dependency of our golang source code, and package it into a binary file.</p><pre>FROM golang:alpine3.16 <br>WORKDIR /app <br>COPY . . <br>RUN go mod download <br>RUN go build -o goapp</pre><p>From this stage, we will get a binary file, called <em>goapp</em>. In next stage, we can use a tiny image like <em>Alpine Linux</em> image to run this binary. <br>But first, i want to identify the first stage using `AS` keyword on Dockerfile. In this part, we give the stage name as <strong><em>build</em></strong><em>.</em></p><pre>FROM golang:alpine3.16 <strong>AS build</strong><br>WORKDIR /app <br>COPY . . <br>RUN go mod download <br>RUN go build -o goapp</pre><p>After that, we can create next build. We will using `alpine:latest` image with expectations the image size will not be too large.</p><pre>FROM alpine:latest<br>WORKDIR /</pre><p>After defining the base image, copy the `goapp` binary from the first build using `COPY` syntax.</p><pre>COPY - from=build /app/goapp ./goapp</pre><p>Next, we can expose the port, and run the binary like usual.</p><pre>EXPOSE 80<br>ENTRYPOINT [&quot;./goapp&quot;]</pre><p>Complete Dockerfile:</p><pre>FROM golang:alpine3.16 AS build<br>WORKDIR /app<br>COPY . .<br>RUN go mod download<br>RUN go build -o goapp<br>FROM alpine:latest<br>WORKDIR /<br>COPY - from=build /app/goapp ./goapp<br>EXPOSE 80<br>ENTRYPOINT [&quot;./goapp&quot;]</pre><p>Let’s try to build the Docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*QT2vy6W_-mu2vStWje6biw.png" /></figure><p>As we can see, the new version of our docker image reduced to <strong>19 MB only</strong>. It means, we reduce up to 96% of the image size!<br>Hope this simple tutorial can improve your workflow!</p><h3>Reference</h3><p><a href="https://docs.docker.com/build/building/multi-stage/">https://docs.docker.com/build/building/multi-stage/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4260396d068a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Golang Development: Implementing CI/CD with GitLab CI]]></title>
            <link>https://medium.com/@mfakhriabdillah/streamlining-golang-development-implementing-ci-cd-with-gitlab-ci-b89d384574d8?source=rss-9bef1fd6715a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89d384574d8</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhammad Fakhri Abdillah]]></dc:creator>
            <pubDate>Thu, 09 May 2024 10:19:56 GMT</pubDate>
            <atom:updated>2024-05-09T10:19:56.058Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s fast-paced software development environment, continuous integration and continuous deployment (CI/CD) have become indispensable practices for ensuring code quality, accelerating delivery, and increasing team productivity. For Golang projects, implementing CI/CD can significantly streamline the development lifecycle, allowing developers to focus more on writing code and less on manual processes. In this article, we’ll explore how to leverage GitLab CI, a powerful CI/CD tool integrated into the GitLab platform, to automate and optimize the Golang development process.</p><h3>Understanding the Golang Development Lifecycle</h3><p>Before diving into CI/CD, it’s crucial to grasp the typical stages in the Golang development lifecycle. From writing code to testing, building, and deploying, each stage plays a vital role in delivering high-quality software efficiently. For instance, let’s consider a scenario where a team is developing a web application in Golang.</p><p>The development lifecycle might involve writing code and unit testing locally, pushing code/changes to a shared repository, running integration tests, building Docker images, and deploying the application to a cloud server.</p><h3>Introduction to GitLab CI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*Mcg4D27L37UfZlWI.png" /></figure><p>GitLab CI is a robust CI/CD tool integrated into the GitLab platform. It allows developers to define and automate pipelines for building, testing, and deploying applications with ease. Compared to other CI/CD tools, GitLab CI offers a seamless experience, especially for teams already using Gitlab for version control.</p><h3>Setting Up Golang Projects</h3><p>The first step to implementing CI/CD using GitLab CI is setting up a GitLab CI pipeline. But, before we set up the pipeline, we will create a GitLab repository first. Go to <a href="https://gitlab.com,/">https://gitlab.com</a>, and login to your account (or sign up if you using GitLab for the first time). Click <strong>New project</strong> to create a new repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltX_EjSOR38t_i6ASyraTA.png" /></figure><p>Choose <strong>Create blank project</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7JfVY_qH2pL0A3S8xFtFQ.png" /></figure><p>Fill the repository information like project name, project slug, etc. You can also set the visibility of the repository. In this case, I will make this repository be accessed publicly. Click <strong>Create Project</strong> to apply this configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKp9bo1Du9cejFrLHM1H7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nK_ebUcbjKuBB4SLquwFRg.png" /><figcaption>The repositories first-look</figcaption></figure><p>Clone the project repository into your local computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*hw722ZCUTbw5aJ-n8EEB7g.png" /></figure><p>After that, let’s prepare a simple Golang application that we’ll deploy using GitLab CI. For this example, I create a basic HTTP server using several standard packages.</p><pre>// main.go<br>package main<br><br>import (<br> &quot;net/http&quot;<br> &quot;os&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br> r := gin.Default()<br> r.GET(&quot;/&quot;, func(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{<br>   &quot;message&quot;:         &quot;ok&quot;,<br>   &quot;app_version&quot;:     &quot;2.0&quot;,<br>   &quot;app_description&quot;: &quot;deploy app version 2.0 build 2&quot;,<br>  })<br> })<br> r.GET(&quot;/env&quot;, func(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{<br>   &quot;code&quot;:     200,<br>   &quot;data_env&quot;: os.Environ(),<br>  })<br> })<br> r.Run() // listen and serve on 0.0.0.0:8080 (for windows &quot;localhost:8080&quot;)<br>}</pre><pre>// go.mod<br>module simple-app<br><br>go 1.20<br><br>require (<br> github.com/bytedance/sonic v1.10.0-rc3 // indirect<br> github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect<br> github.com/chenzhuoyu/iasm v0.9.0 // indirect<br> github.com/gabriel-vasile/mimetype v1.4.2 // indirect<br> github.com/gin-contrib/sse v0.1.0 // indirect<br> github.com/gin-gonic/gin v1.9.1 // indirect<br> github.com/go-playground/locales v0.14.1 // indirect<br> github.com/go-playground/universal-translator v0.18.1 // indirect<br> github.com/go-playground/validator/v10 v10.15.0 // indirect<br> github.com/goccy/go-json v0.10.2 // indirect<br> github.com/json-iterator/go v1.1.12 // indirect<br> github.com/klauspost/cpuid/v2 v2.2.5 // indirect<br> github.com/leodido/go-urn v1.2.4 // indirect<br> github.com/mattn/go-isatty v0.0.19 // indirect<br> github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect<br> github.com/modern-go/reflect2 v1.0.2 // indirect<br> github.com/pelletier/go-toml/v2 v2.0.9 // indirect<br> github.com/twitchyliquid64/golang-asm v0.15.1 // indirect<br> github.com/ugorji/go/codec v1.2.11 // indirect<br> golang.org/x/arch v0.4.0 // indirect<br> golang.org/x/crypto v0.12.0 // indirect<br> golang.org/x/net v0.14.0 // indirect<br> golang.org/x/sys v0.11.0 // indirect<br> golang.org/x/text v0.12.0 // indirect<br> google.golang.org/protobuf v1.31.0 // indirect<br> gopkg.in/yaml.v3 v3.0.1 // indirect<br>)</pre><pre>// go.sum<br>github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=<br>github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=<br>github.com/bytedance/sonic v1.10.0-rc3 h1:uNSnscRapXTwUgTyOF0GVljYD08p9X/Lbr9MweSV3V0=<br>github.com/bytedance/sonic v1.10.0-rc3/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=<br>github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=<br>github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=<br>github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=<br>github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=<br>github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo=<br>github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=<br>github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=<br>github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=<br>github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=<br>github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=<br>github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=<br>github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=<br>github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=<br>github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=<br>github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=<br>github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=<br>github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=<br>github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=<br>github.com/go-playground/validator/v10 v10.15.0 h1:nDU5XeOKtB3GEa+uB7GNYwhVKsgjAR7VgKoNB6ryXfw=<br>github.com/go-playground/validator/v10 v10.15.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=<br>github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=<br>github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=<br>github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=<br>github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=<br>github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=<br>github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=<br>github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=<br>github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=<br>github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=<br>github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=<br>github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=<br>github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=<br>github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=<br>github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=<br>github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=<br>github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=<br>github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=<br>github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=<br>github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=<br>github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=<br>github.com/pelletier/go-toml/v2 v2.0.9 h1:uH2qQXheeefCCkuBBSLi7jCiSmj3VRh2+Goq2N7Xxu0=<br>github.com/pelletier/go-toml/v2 v2.0.9/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=<br>github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=<br>github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=<br>github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=<br>github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=<br>github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=<br>github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=<br>github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=<br>github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=<br>github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=<br>github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=<br>github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=<br>github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=<br>github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=<br>github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=<br>github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=<br>golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=<br>golang.org/x/arch v0.4.0 h1:A8WCeEWhLwPBKNbFi5Wv5UTCBx5zzubnXDlMOFAzFMc=<br>golang.org/x/arch v0.4.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=<br>golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk=<br>golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=<br>golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14=<br>golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=<br>golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=<br>golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=<br>golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=<br>golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=<br>golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc=<br>golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=<br>golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=<br>google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=<br>google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=<br>google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=<br>gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=<br>gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=<br>gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=<br>gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=<br>nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=<br>rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=</pre><p>Now, let’s create a Dockerfile to containerize our Golang application.</p><pre>FROM golang:alpine3.16<br>WORKDIR /app<br>COPY . .<br>RUN go mod download<br>RUN go build -o goapp<br>EXPOSE 8080<br>ENTRYPOINT [&quot;/app/goapp&quot;]</pre><p>This Dockerfile sets up a Docker image based on the Golang image, copies our Golang application code into the container, installs dependencies, builds the application, and sets the command to run the application.</p><p>Push the application to GitLab repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*i5oYXZ9EVycZo68Ll1-BOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*5PIkv7nM-vv1XeRiDy78Pg.png" /></figure><h3>Setting Up Gitlab CI for Golang Project</h3><p>After we prepare the Golang application, we’ll create a .gitlab-ci.yaml file in the root directory of our project repository to define the stages and jobs required for our CI/CD process.</p><p>First, we can define the stages. In this pipeline, we will run a test, build the Docker image and push it to Docker Hub, and deploy it to the server.</p><pre>stages:<br>  - test<br>  - build-push-docker-images<br>  - deploy</pre><p>In the first stage, we’ll run a test from the pipelines. Here we define the base image to run our instructions. Because we will run some Golang commands, we can use golang:latest images.</p><pre>test:<br>  image: golang:latest<br>  stage: test<br>  script:<br>    - go test ./...</pre><p>After the test stage is successful, GitLab CI will build the code into a docker image and push it to the Docker Hub. We use a docker:latest image with docker:dind services to run this stage.</p><pre>build-push-docker-images:<br>  image: docker:latest<br>  services:<br>    - docker:dind<br>  stage: build-push-docker-images<br>  script:<br>   - docker build -t fakhriabdillah/mygolang:latest .</pre><p>The docker image is ready to push into <a href="http://hub.docker.com/">Docker Hub</a>. I assume you have a Docker Hub account. First, we must create a docker repository to store the docker images. Open Docker Hub, and create a new repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFOYAJb0xDEKfjrnr8oSNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3I2XmMVnfz0f40vorhjGA.png" /></figure><p>Let’s go back to GitLab. In this stage, we need docker hub credentials to push docker images to our repository. We can store the username and <a href="https://docs.docker.com/security/for-developers/access-tokens/">personal access token (PAT)</a> in the <a href="https://docs.gitlab.com/ee/ci/variables/">Gitlab CI variables</a>. In your Gitlab repository, go to <strong>Settings &gt; CI/CD</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*jogFAqVSqMX1VmMsYkzEcA.png" /></figure><p>Expand the <strong>Variables</strong> section, and click <strong>Add variable.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HM7b5w9_oQ8MrWGvf_ju9w.png" /></figure><p>Add your DockerHub username and personal access token to the variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3085ES0VpTAIt-OlJCQSA.png" /></figure><p>After that, we can call it in the pipeline like this to log in to the Docker Hub and push the images.</p><pre>build-push-docker-images:<br>  image: docker:latest<br>  services:<br>    - docker:dind<br>  stage: build-push-docker-images<br>  script:<br>   - docker build -t fakhriabdillah/mygolang:latest .<br>   - docker login --username=$DOCKER_USERNAME --password=$DOCKER_TOKEN<br>   - docker push fakhriabdillah/mygolang:latest</pre><p>After we push the image to Docker Hub, we’ll deploy it to the server. In this case, we use a Ubuntu 20.04 server (docker installed), and we will use ssh command to run a deployment command on the server. We can define the server address in the Variables as the stage before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*X23PHRUUtevHgZd15H6Kiw.png" /><figcaption>Defining SSH server address</figcaption></figure><p>In this case, we need an <a href="https://www.sectigo.com/resource-library/what-is-an-ssh-key">SSH privatekey</a> to authenticate into the server. As shown in the picture below, we can store the SSH key in the GitLab variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*EDQKwNs5UTSzHw2CyueH9g.png" /><figcaption>Adding SSH private key to Gitlab Variable</figcaption></figure><p>After that, we can use the SSH private key in the pipeline with the following script.</p><pre>deploy:<br>  stage: deploy<br>  before_script:<br>    - mkdir -p ~/.ssh<br>    - echo -e &quot;$SSH_IDRSA&quot; &gt; ~/.ssh/id_rsa<br>    - chmod 600 ~/.ssh/id_rsa<br>    - &#39;[[ -f /.dockerenv ]] &amp;&amp; echo -e &quot;Host *\n\tStrictHostKeyChecking no\n\n&quot; &gt; ~/.ssh/config&#39;<br>  script:<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker login --username=$DOCKER_USER --password=$DOCKER_TOKEN&quot;<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker pull fakhriabdillah/mygolang:latest&quot;<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker rm -f mygolang-container&quot;<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker run --name mygolang-container -d-p 80:8080 mygolang:latest&quot;</pre><p>So, the .gitlab-ci.yaml full configuration will be like this</p><pre>stages:<br>  - test<br>  - build-push-docker-images<br>  - deploy<br><br>test:<br>  image: golang:latest<br>  stage: test<br>  script:<br>    - go test ./...<br><br>build-push-docker-images:<br>  image: docker:latest<br>  services:<br>    - docker:dind<br>  stage: build-push-docker-images<br>  script:<br>   - docker build -t fakhriabdillah/mygolang:latest .<br>   - docker login --username=$DOCKER_USERNAME --password=$DOCKER_TOKEN<br>   - docker push fakhriabdillah/mygolang:latest<br><br>deploy:<br>  stage: deploy<br>  before_script:<br>    - mkdir -p ~/.ssh<br>    - echo -e &quot;$SSH_IDRSA&quot; &gt; ~/.ssh/id_rsa<br>    - chmod 600 ~/.ssh/id_rsa<br>    - &#39;[[ -f /.dockerenv ]] &amp;&amp; echo -e &quot;Host *\n\tStrictHostKeyChecking no\n\n&quot; &gt; ~/.ssh/config&#39;<br>  script:<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker login --username=$DOCKER_USER --password=$DOCKER_TOKEN&quot;<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker pull fakhriabdillah/mygolang:latest&quot;<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker rm -f mygolang-container&quot;<br>    - ssh -i ~/.ssh/id_rsa -p22 $SSH_SERVER_ADDRESS &quot;docker run --name mygolang-container -d-p 80:8080 mygolang:latest&quot;</pre><p>Let’s push the code into GitLab repository, and see what happens!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*zquKjlNfcUiHKzI7_goTgQ.png" /></figure><p>On the sidebar, you can go to <strong>Build &gt; Pipelines</strong>, and see that GitLab creates a new pipeline job to run our CI/CD pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7-e82MT6NoksUpHvkjnfg.png" /></figure><p>And… It’s passed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4_eKdbz071gSMbOS27dZQ.png" /></figure><p>We can check the deployment was successful from the logs on the pipeline jobs. And we can try to access the server from the web browser now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7nfFqZXZSYxJWSHh1qrNQ.png" /></figure><h3>Conclusion</h3><p>Implementing CI/CD with GitLab CI for Golang development offers numerous benefits, including faster feedback loops, improved code quality, and increased team collaboration. By following the steps outlined in this article and embracing CI/CD best practices, you can streamline your Golang development process and deliver software more efficiently than ever before. With GitLab CI, the possibilities are endless, empowering you to automate and optimize every aspect of your development lifecycle.</p><h3>Resources</h3><ul><li><a href="https://docs.gitlab.com/ee/ci/">GitLab CI Documentation</a></li><li><a href="https://www.gitlab.com/ci-cd/best-practices">Best Practices for CI/CD Pipelines</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89d384574d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>