<?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 Jaeyoon Lee on Medium]]></title>
        <description><![CDATA[Stories by Jaeyoon Lee on Medium]]></description>
        <link>https://medium.com/@jae.yoon7373?source=rss-5629894f74a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SrAaDl1ToY2Z9B9WmT0z2Q.jpeg</url>
            <title>Stories by Jaeyoon Lee on Medium</title>
            <link>https://medium.com/@jae.yoon7373?source=rss-5629894f74a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:05:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jae.yoon7373/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[Automating Environment Variable Setup with AWS Secrets Manager in Microservice Architecture]]></title>
            <link>https://blog.devops.dev/automating-environment-variable-setup-with-aws-secrets-manager-in-microservice-architecture-dec0a19881f2?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dec0a19881f2</guid>
            <category><![CDATA[aws-secrets-manager]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-iam-role]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 11:39:53 GMT</pubDate>
            <atom:updated>2025-12-01T11:37:57.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>A secure, scalable approach to managing secrets across multiple microservices without copy-paste nightmare.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VWTi574kf0pUnZs7N4K4g.png" /><figcaption>Automating the retrieval of environment variables from AWS Secrets Manager into multiple microservices using IAM authentication &amp; Bash scripts.</figcaption></figure><p>Managing .env variables in a microservice architecture is challenging. Sharing secrets via Slack or Notion is insecure, and keeping local environment files in sync across a team of developers is a constant headache. Not to mention the confusion with test vs. production keys and environment switching.</p><p>In this guide, we will implement a solution using <strong>AWS Secrets Manager</strong> to store our variables and a set of <strong>Bash scripts</strong> to load them dynamically into an NPM project.</p><h3>1. Prerequisites</h3><p>Before starting this guide, you will need to:</p><ul><li>Have AWS CLI installed and configured (aws configure)</li><li>jq package installed to parse .json responses (sudo apt install jq)</li></ul><h3>2. Project Structure &amp; Architecture</h3><p>This will be the project directory structure for this guide. We assume a monorepo setup where multiple services live side-by-side:</p><pre>aws-secret-env/<br>├── subfolder/<br>│   └── microservice-3/<br>│       ├── .env<br>│       └── package.json<br>├── microservice-1/<br>│   ├── .env<br>│   └── package.json<br>├── microservice-2/<br>│   ├── .env<br>│   └── package.json<br>├── scripts/<br>│   ├── load-env.sh<br>│   └── setup-all.sh<br>└── package.json</pre><p>As you can see, multiple microservice directories are present in one repository for ease of maintenance. A subfolder was included to demonstrate how our scripts handle nested directories for future scaling.</p><h3>3. AWS Configuration</h3><h4>3.1 Designing the Secret Hierarchy</h4><p>In the AWS Console, navigate to Secrets Manager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRrsmasmJZZ0eGBp8D7jZA.png" /></figure><p>Create a new secret (select “Other type of secret”), and add your key-value pairs (e.g., ENVIRONMENT, API_KEY):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzE2HD8c2ANGYcSoXKjIfg.png" /></figure><p>We will use MICROSERVICE_NAME and API_KEY dummy values to check if the correct env values are retrieved during testing.</p><p>After clicking Next, to define a secret name, use a hierarchy that reflects your project structure. This enables our scripts to predict the secret name based on the folder name.</p><p>In this case, we will use: aws-load-env/microservice-1/dev.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHRzSOiT6Uqf_Crxcj328Q.png" /></figure><p>After clicking next, we will not use secret rotation for this demo, so you can skip the token rotation configuration page and finalize the secret creation.</p><h4>3.2 Storing Secrets</h4><p>Repeat the above steps to create secrets for all your services and environments. You should end up with a list like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZPW_UtRQxHNRtU2l4fV6A.png" /></figure><p>Note that production and development environments are separated within the same microservice. I’ve used the naming convention:</p><pre>&lt;top-level-service-name&gt;/&lt;microservice-name&gt;/&lt;environment&gt;</pre><h4><strong>3.3 IAM User &amp; Role Setup</strong></h4><p>For security, we don’t want to embed long-term access keys into our scripts. Instead, we use <strong>AWS STS (Security Token Service)</strong>.</p><ol><li><strong>Create an IAM Role</strong> (secret-env-role) with the AWSSecretsManagerClientReadOnlyAccess policy.</li><li><strong>Create an IAM User</strong> (env-load-user).</li><li><strong>Establish a Trust Relationship between your IAM User and IAM Role.</strong></li></ol><p>You can create a Trust Policy for the role by adding the below configuration:</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;Principal&quot;: {<br>    &quot;AWS&quot;: &quot;arn:aws:iam::YOUR_ACCOUNT_ID:user/env-load-user&quot; &lt;--- IAM USER ARN<br>   },<br>   &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>  }<br> ]<br>}</pre><p>This allows you to authenticate once with your user credentials, and then temporarily “become” the role to fetch secrets. This is a best practice by AWS for limiting the “blast radius” of compromised credentials .</p><h3>4. Scripts</h3><p>We will create two scripts in the scripts/ folder: load-env.sh and setup-all.sh.</p><h4>4.1 load-env.sh</h4><p>This is the main script. It authenticates (if needed) and assumes the required role, fetches the secrets from AWS Secrets Manager as JSON, and parses them into a .env file:</p><pre>#!/usr/bin/env bash<br><br>REPO_ROOT=&quot;${1:-${basename &quot;$PWD&quot;}}&quot;<br>MICROSERVICE_ROOT=&quot;${2:-$(basename &quot;$PWD&quot;)}&quot;<br>ENVIRONMENT=&quot;${3:-dev}&quot;<br>OUT_FILE=&quot;${4:-.env}&quot;<br><br>if [ -z &quot;$AWS_SESSION_TOKEN&quot; ]; then<br>  echo &quot;✔ No active session found. Assuming role through AWS sts.&quot;<br>  eval $(aws sts assume-role \<br>    --role-arn arn:aws:iam::************:role/secret-env-role \<br>    --role-session-name temp-session \<br>    --query &#39;Credentials.[AccessKeyId,SecretAccessKey,SessionToken]&#39; \<br>    --output text | \<br>    awk &#39;{printf &quot;export AWS_ACCESS_KEY_ID=%s\nexport AWS_SECRET_ACCESS_KEY=%s\nexport AWS_SESSION_TOKEN=%s\n&quot;, $1, $2, $3}&#39;)<br>else<br>  echo &quot;✔ Using existing AWS session.&quot;<br>fi<br><br>SECRET_STR=$(aws secretsmanager get-secret-value \<br>  --secret-id ${REPO_ROOT}/${MICROSERVICE_ROOT}/${ENVIRONMENT} \<br>  --query SecretString --output text --region ap-northeast-2 2&gt;/dev/null || true)<br><br>if [ -z &quot;$SECRET_STR&quot; ]; then<br>  echo &quot;Failed to fetch secret or secret is empty&quot;<br>  exit 1<br>fi<br><br>echo &quot;$SECRET_STR&quot; | jq -r &#39;to_entries | .[] | &quot;\(.key)=\(.value)&quot;&#39; &gt; &quot;$OUT_FILE&quot;<br><br>echo &quot;✔ Loaded secret into $OUT_FILE&quot;</pre><p><strong>Please make sure to replace the following line with your actual AWS Role ARN:</strong></p><pre>--role-arn arn:aws:iam::************:role/secret-env-role \</pre><h4>4.2 setup-all.sh</h4><p>This script is used for onboarding new developers. It authenticates once and then loops through all directories to set up the entire repo in seconds:</p><pre>#!/bin/bash<br>SERVICE_ROOT_NAME=&quot;${1:-}&quot;<br>ENVIRONMENT=&quot;${2:-dev}&quot;<br><br>TARGET_DIRS=(<br>  &quot;microservice-1&quot;<br>  &quot;microservice-2&quot;<br>  &quot;subfolder/microservice-3&quot;<br>)<br><br>SCRIPT_DIR=&quot;$(cd &quot;$(dirname &quot;${BASH_SOURCE[0]}&quot;)&quot; &amp;&amp; pwd)&quot;<br><br>eval $(aws sts assume-role \<br>  --role-arn arn:aws:iam::************:role/secret-env-role \<br>  --role-session-name temp-session \<br>  --query &#39;Credentials.[AccessKeyId,SecretAccessKey,SessionToken]&#39; \<br>  --output text | \<br>  awk &#39;{printf &quot;export AWS_ACCESS_KEY_ID=%s\nexport AWS_SECRET_ACCESS_KEY=%s\nexport AWS_SESSION_TOKEN=%s\n&quot;, $1, $2, $3}&#39;)<br><br>for dir in &quot;${TARGET_DIRS[@]}&quot;; do<br>  echo &quot;----------------------------------------&quot;<br>  echo &quot;Checking: $dir&quot;<br><br>  if [ -d &quot;$dir&quot; ]; then<br>    SERVICE_NAME=$(basename &quot;$dir&quot;)<br><br>    pushd &quot;$dir&quot; &gt; /dev/null<br><br>    bash $SCRIPT_DIR/load-env.sh &quot;${SERVICE_ROOT_NAME}&quot; &quot;${SERVICE_NAME}&quot; &quot;${ENVIRONMENT}&quot;<br><br>    popd &gt; /dev/null<br>  else<br>    echo &quot;❌ Error: Directory &#39;$dir&#39; is required but not found!&quot;<br>  fi<br>done</pre><p>The scripts depends on the TARGET_DIRS directory. Make sure to update this part of the script when adding new microservices as the project increases.</p><h3>5. Integration (package.json)</h3><p>One thing to note is that we don’t want developers calculating relative paths (../../scripts/load-env.sh) manually for each nested microservice in the respective package.json.</p><p>We use git rev-parse --show-toplevel to dynamically find the root of the repo. This allows you to use the exact same package.json script into any microservice, regardless of how deep it is nested.</p><p><strong>Add this to every microservice’s </strong><strong>package.json:</strong></p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;load-env-dev&quot;: &quot;bash $(git rev-parse --show-toplevel)/scripts/load-env.sh aws-load-env \&quot;\&quot; dev&quot;,<br>    &quot;load-env-prod&quot;: &quot;bash $(git rev-parse --show-toplevel)/scripts/load-env.sh aws-load-env \&quot;\&quot; prod&quot;<br>  }<br>}</pre><p><em>Note: We pass </em><em>&quot;&quot; as the second argument so the script defaults to using the current folder name.</em></p><h3>6. Testing &amp; Verification</h3><h4><strong>Test 1: Single Service</strong></h4><p>Navigate to microservice-1 and run:</p><pre>cd microservice-1<br>npm run load-env-dev</pre><p>You should see env created with:</p><pre>MICROSERVICE_NAME=Microservice 1<br>API_KEY=Test 1</pre><h4><strong>Test 2: Full Setup</strong></h4><p>From the root directory, run:</p><pre>bash ./scripts/setup-all.sh</pre><p>You should see it authenticate once, then rapidly configure all services (including the nested microservice-3).</p><p>Check your .env files, and you should see your variables populated securely from AWS!</p><h3>Conclusion</h3><p>By shifting from local .env files to <strong>AWS Secrets Manager</strong> and automating the retrieval process, we have transformed a manual, error-prone chore into a robust workflow.</p><h4>Benefits:</h4><ul><li><strong>Security:</strong> We eliminated “secret sprawl.” No more API keys hidden in Git history, Slack DMs, or sticky notes.</li><li><strong>Consistency:</strong> Every developer and production server pulls from the exact same “Single Source of Truth.”</li><li><strong>Automation:</strong> A single command (setup-all.sh) onboards a new developer or provisions a build server in seconds.</li></ul><h4>Trade-offs &amp; Considerations</h4><p>While this architecture is robust, there are two factors to keep in mind:</p><ol><li><strong>Cost:</strong> AWS charges <strong>$0.40 per secret/month</strong> and <strong>$0.05 per 10,000 API calls</strong> (may vary depending on the region). While cheap for small projects, costs can scale.</li><li><strong>The “Bootstrap” Security:</strong> While we removed the application secrets from the code, developers still need <strong>initial AWS IAM User</strong> credentials to run these scripts. Ensure these credentials are never committed to Git and are rotated regularly.</li></ol><p>And there you have it! An easier, more robust way to load .env variables that is ready for both local development and CI/CD pipelines.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dec0a19881f2" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/automating-environment-variable-setup-with-aws-secrets-manager-in-microservice-architecture-dec0a19881f2">Automating Environment Variable Setup with AWS Secrets Manager in Microservice Architecture</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Let’s Encrypt’s HTTP-01 Validation Flow (with Nginx & Certbot --webroot on Linux)]]></title>
            <link>https://blog.devops.dev/configure-https-with-ssl-certificates-using-nginx-certbot-using-webroot-on-linux-c378b94c90bc?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c378b94c90bc</guid>
            <category><![CDATA[lets-encrypt]]></category>
            <category><![CDATA[acme]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[certbot]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 03:48:45 GMT</pubDate>
            <atom:updated>2025-09-15T14:40:17.833Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Step-by-step guide to validation and implementation in a Dockerized Nginx setup</em></h4><p>Hello everyone!</p><p>I run my Nginx server in a Docker container with Let’s Encrypt SSL certificates, but automatic renewals aren’t supported for Nginx containers in Docker.</p><p>To work around this, I used the --webroot path when configuring HTTPS so renewals occur without stopping my container.</p><p>Here is a brief guide with an overview of the certificate issuance process and the implementation using Nginx &amp; Certbot.</p><h3>Overview</h3><p>Here is a brief overview of the certificate validation flow that Let’s Encrypt uses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWC_-j8zEsbjQ7ZKYYiuxQ.png" /><figcaption>HTTP-01 Validation Flow for Let’s Encrypt Certificates.</figcaption></figure><p><strong>1. Certbot places the token<br></strong>Certbot writes a special file inside .well-known/acme-challenge/&lt;token&gt; in the linux container’s webroot.</p><p><strong>2. Nginx serves the token<br></strong>Your Nginx server serves this file at the public URL path.</p><p><strong>3. ACME Server(Let’s Encrypt) requests the URL<br></strong>The ACME (<em>Automatic Certificate Management Environment</em>) server managed by Let’s Encrypt sends an HTTP request to:</p><pre>http://your-domain/.well-known/acme-challenge/&lt;token&gt;</pre><p><strong>4. ACME Server compares the tokens<br></strong>If the content matches the expected token, domain ownership is confirmed and the SSL/TLS certificate is issued.</p><h3>Implementation</h3><h4>1. Install Certbot</h4><p>Before you install certbot in your linux machine, make sure that you remove preinstalled certbot packages that might conflict with your new installation:</p><pre>sudo apt remove certbot</pre><p>Then, install certbot using snap:</p><pre>sudo snap install --classic certbot</pre><blockquote>If you do not have snap installed in your linux machine, you can follow instructions on <a href="https://snapcraft.io/docs/installing-snapd">snapcraft’s official docs</a>.</blockquote><p>Run the following command to ensure that the certbot command can be run:</p><pre>sudo ln -s /snap/bin/certbot /usr/bin/certbot</pre><blockquote>This part of the guide is based on certbot’s official documentation. If you want to read more, click <a href="https://certbot.eff.org/instructions?ws=nginx&amp;os=snap">here</a>.</blockquote><h4>2. Run Barebones Nginx Container</h4><p>Create a nginx and nginx/letsencrupt-webroot directory:</p><pre>mkdir nginx<br>cd nginx<br>mkdir letsencrypt-webroot</pre><p>Create a nginx Docker network:</p><pre>sudo docker network create nginx</pre><p>Now create a barebones nginx.conf that listens on port 80 (http):</p><pre>server {<br>    listen 80;<br>    server_name test.jaeyoon.dev;<br><br>    location /.well-known/acme-challenge/ {<br>        root /var/www/certbot;<br>    }<br>}</pre><blockquote>/.well-known/acme-challenge/ is the standard ACME validation path. Certbot will store a temporary token here, and Let’s Encrypt will request http://test.domain.com/.well-known/acme-challenge/&lt;token&gt; to verify domain ownership.</blockquote><p>Create a nginx-compose.yml:</p><pre>services:<br>  nginx:<br>    image: nginx:latest<br>    container_name: nginx-reverse-proxy<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/conf.d/default.conf<br>      - /etc/letsencrypt:/etc/letsencrypt:ro<br>      - ./letsencrypt-webroot:/var/www/certbot:ro<br>    networks:<br>      - nginx<br><br>networks:<br>  nginx:<br>    external: true</pre><p>Now run your nginx container:</p><pre>sudo docker compose -f ./nginx-compose.yml up -d</pre><h4>3. Configure DNS Settings</h4><p>In your DNS portal (GoDaddy, Squarespace, etc.), make sure that you point your domain to your linux container that is running your nginx server:</p><pre>Host      Type      TTL      Data<br>test      A         4hrs     &lt;container ip address&gt;</pre><ul><li>Host: the subdomain name — test would translate to test.domain.com.</li><li>Type: A record, which points the domain to a specific IP4 Address.</li><li>TTL: Time To Live — how quickly your domains settings are updated. You can use your DNS default settings.</li><li>Data: the IP Address of your Host.</li></ul><blockquote>If you don’t have your DNS settings pointing to your nginx server, the next step will fail. Please configure your DNS settings before moving on.</blockquote><h4>4. Create Certbot certificates using --webroot flag</h4><p>Now, create a certbot certificate:</p><pre>sudo certbot certonly --webroot \<br>  -w /home/jae/Desktop/nginx/letsencrypt-webroot \<br>  -d test.jaeyoon.dev</pre><ul><li>-w: the webroot path that certbot will use to create validation tokens when issuing &amp; renewing certificates.</li><li>-d: the domain you want to create certificates for.</li></ul><p>You should see something like this:</p><pre>Saving debug log to /var/log/letsencrypt/letsencrypt.log<br>Requesting a certificate for test.jaeyoon.dev<br><br>Successfully received certificate.<br>Certificate is saved at: /etc/letsencrypt/live/test.jaeyoon.dev/fullchain.pem<br>Key is saved at:         /etc/letsencrypt/live/test.jaeyoon.dev/privkey.pem<br>This certificate expires on 2025-12-11.<br>These files will be updated when the certificate renews.<br>Certbot has set up a scheduled task to automatically renew this certificate in the background.<br><br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -<br>If you like Certbot, please consider supporting our work by:<br> * Donating to ISRG / Let&#39;s Encrypt:   https://letsencrypt.org/donate<br> * Donating to EFF:                    https://eff.org/donate-le<br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -</pre><p>Notice that certificates have been saved at:</p><pre>Certificate is saved at: /etc/letsencrypt/live/test.jaeyoon.dev/fullchain.pem<br>Key is saved at:         /etc/letsencrypt/live/test.jaeyoon.dev/privkey.pem</pre><p>This will later be used when updating your nginx.conf to listen for https requests.</p><h4>5. Create Dummy Server</h4><p>Create a dummy server that displays “Hello World” then requested:</p><pre>docker run -d \<br>  --name hello-world \<br>  --network nginx \<br>  -p 8080:5678 \<br>  hashicorp/http-echo -text=&quot;Hello World&quot;</pre><p>This ensures Nginx has an upstream service to proxy HTTPS traffic to.</p><h4>6. Update nginx.conf</h4><p>Stop your nginx Docker container:</p><pre>sudo docker compose -f ./nginx-compose.yml down</pre><p>Edit your nginx.conf to enable https:</p><pre># Redirect HTTP to HTTPS<br>server {<br>    listen 80;<br>    server_name test.jaeyoon.dev;<br><br>    location / {<br>        return 301 https://$host$request_uri;<br>    }<br><br>    location /.well-known/acme-challenge/ {<br>        root /var/www/certbot;<br>    }<br>}<br><br>server {<br>    listen 443 ssl;<br>    server_name test.jaeyoon.dev;<br><br>    ssl_certificate /etc/letsencrypt/live/test.jaeyoon.dev/fullchain.pem;<br>    ssl_certificate_key /etc/letsencrypt/live/test.jaeyoon.dev/privkey.pem;<br><br>    ssl_protocols TLSv1.2 TLSv1.3;<br>    ssl_prefer_server_ciphers on;<br>    ssl_ciphers HIGH:!aNULL:!MD5;<br><br>    location / {<br>        proxy_pass http://hello-world:5678;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>        proxy_set_header X-Forwarded-Host $host;<br>    }<br>}</pre><ul><li>server_name: listens for your domain when forwarding request.</li><li>proxy_pass: forwards request to http://hello-world:5678 docker container. The host name is used since hello-world container and nginx container are in the <strong>same docker network</strong>.</li><li>ssl_certificate: the path where Let’s Encrypt created the fullchain.pem file.</li><li>ssl_certificate_key: the path where Let’s Encrypt created the privkey.pem file.</li></ul><p>Now restart your nginx container:</p><pre>sudo docker compose -f ./nginx-compose.yml up -d</pre><h4>7. Test</h4><p>Run a curl command to your domain:</p><pre>curl https://test.jaeyoon.dev</pre><p>You should get:</p><pre>Hello World</pre><p>You can also use your browser to check if it is serving over HTTPS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkgToEzi1mSAtDcIMRev-g.png" /></figure><h4>8. Test Renewal</h4><p>Run a --dry-run to simulate a certificate renewal:</p><pre>sudo certbot renew --dry-run</pre><p>You should see something like this:</p><pre><br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -<br>Processing /etc/letsencrypt/renewal/test.jaeyoon.dev.conf<br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -<br>Account registered.<br>Simulating renewal of an existing certificate for test.jaeyoon.dev<br><br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -<br>Congratulations, all simulated renewals succeeded:<br>  /etc/letsencrypt/live/test.jaeyoon.dev/fullchain.pem (success)<br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -</pre><p>Now you are all set! Certbot will automatically renew your certificates without having the need to stop and restart your nginx container.</p><h3>Conclusion</h3><p>By using Certbot with the --webroot method, you can issue and renew SSL/TLS certificates in a Dockerized Nginx environment without downtime.</p><p>This setup keeps your containers running, serves HTTPS traffic securely, and ensures renewals happen automatically in the background.</p><p>Once configured, your certificates will stay valid with little maintenance, leaving you free to focus on running your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c378b94c90bc" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/configure-https-with-ssl-certificates-using-nginx-certbot-using-webroot-on-linux-c378b94c90bc">Understanding Let’s Encrypt’s HTTP-01 Validation Flow (with Nginx &amp; Certbot --webroot on Linux)</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Slack Commands to Trigger MongoDB Backups with API Gateway and AWS Lambda]]></title>
            <link>https://blog.devops.dev/use-slack-commands-to-trigger-mongodb-backups-with-api-gateway-and-aws-lambda-7ef3f475ea09?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ef3f475ea09</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[slack-commands]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 13:51:18 GMT</pubDate>
            <atom:updated>2025-08-25T11:42:23.471Z</atom:updated>
            <content:encoded><![CDATA[<h4>Send a Slack slash command to trigger your AWS Lambda function via API Gateway</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPQezB_41g5YpmUtiHeTvg.png" /><figcaption><em>Trigger MongoDB backups via a Slack Command routed through API Gateway and AWS Lambda, which connects to your MongoDB instance and stores the dump in S3.</em></figcaption></figure><p>Hello everyone! To add on to the previous <a href="https://blog.devops.dev/backing-mongodb-data-every-week-with-eventbridge-aws-lambda-5beb24748db2">MongoDB Backup Microservice guide</a>, here’s a way to <strong>manually trigger a MongoDB backup</strong> using a <strong>Slack Command</strong> connected to <strong>API Gateway and AWS Lambda</strong>.</p><p>This is useful for development teams or small projects that want to manutally trigger database backups right before running sensitive tasks.</p><blockquote>If you are new here, I recommend checking out the previous article first, as this guide builds directly on top of it:</blockquote><p><a href="https://blog.devops.dev/backing-mongodb-data-every-week-with-eventbridge-aws-lambda-5beb24748db2">Back Up MongoDB Data Every Week with EventBridge &amp; AWS Lambda</a></p><p>Anyways, let’s get started!</p><h3>Overview</h3><h4>1. Create API Gateway Route</h4><p>First, create an API Gateway route. In your AWS Console, navigate to <strong>API Gateway &gt; APIs &gt; Create API</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5IjpfHxpBEV2ccNiQUflQ.png" /></figure><p>Choose <strong>HTTP API</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsAwkPAGPT6xK-g1QB2yWg.png" /></figure><p>Enter the <strong>API name</strong>, and under <strong>Integration</strong>, select your existing Lambda function that you created before. If it doesn’t show up, make sure you’re in the correct <strong>AWS Region</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2iNlp7QftfET9OPfJz4Dg.png" /></figure><p>Create a POST route with the resource path of /mongodb-backup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsCeLorHObbQ80i4B8Khiw.png" /></figure><blockquote>This is crucial for integrating with Slack Commands later in this guide. Make sure you choose POST as the HTTP method.</blockquote><p>Then, define the default stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UG6DYXbP3nTGTTuWjK6cKg.png" /></figure><p>Check the information below, and click <strong>Create</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODFBI1KzrxqJZ7uWOp8dQw.png" /></figure><p>After creating the API route, click the <strong>API: mongodb-backup</strong> tab on the side and confirm the <strong>Invoke URL</strong> for your route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrXR7Dc9AQimcz0SgkOgaw.png" /></figure><p>Now you are done! Take note of your <strong>Invoke URL</strong> for your API Gateway and the <strong>Route</strong> that you created when integrating with Lambda:</p><pre>Invoke URL: https://s9zlq4m2da.execute-api.ap-northeast-2.amazonaws.com<br>Route: POST /mongodb-backup</pre><p>Therefore, your full URL to trigger your mongodb-backup Lambda function will be:</p><pre>https://s9zlq4m2da.execute-api.ap-northeast-2.amazonaws.com/mongodb-backup</pre><blockquote>Note: This endpoint is used for demo purposes only and will be disabled after publishing.</blockquote><h4>2. Test API Gateway Route</h4><p>Now it’s time to test your API Gateway trigger!</p><p>From your terminal, run a HTTP POST request to your API Gateway trigger URL:</p><pre>curl -X POST https://jwz7iq2wi9.execute-api.ap-northeast-2.amazonaws.com/mongodb-backup</pre><p>If everything works, your Lambda function should be invoked. You may see output like this:</p><pre>null</pre><p>But check your S3 bucket — you should see a new backup dump file uploaded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpGk9N-6NTOS_NkTuJX6vg.png" /></figure><p>In the Lambda dashboard, scroll down to the <strong>Triggers</strong> section and confirm that API Gateway is listed as a trigger to your Lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDszHiKT77aMSdRu3no8UQ.png" /></figure><p>Perfect! Now you have successfully integrated API Gateway with your Lambda function as a trigger.</p><h4>3. Create Slack Command</h4><p>In <a href="https://api.slack.com/apps">https://api.slack.com/apps</a>, create a new Slack App:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfpNx7NAxabJubuH-j9kCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pznOt9xQgMSuNnCYmPAU5A.png" /></figure><p>After creating your app, install the app in your Slack workspace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DznDfRKDEC8KyOCy1jKjFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-d2G41WSVK2I4NC7Lez2A.png" /></figure><p>Then, create a new Slash Command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rmbThXsPj7REtB1nJIgzg.png" /></figure><p>Enter the following fields. Set the <strong>Request URL</strong> to your tested API endpoint:</p><pre>https://jwz7iq2wi9.execute-api.ap-northeast-2.amazonaws.com/mongodb-backup</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEQDl80X-8sFVhtp6CFQDw.png" /></figure><p>Now you’re ready to run the command from Slack!</p><h4>4. Test Slack Command</h4><p>In any Slack channel in your workspace, type the command /backup-mongodb-data and you will see a popup appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OixaQx5FtYGhUt_6G2wY7g.png" /></figure><p>Click enter, and you should see an operation_timeout error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jd8ZyNCUocy2__RCt7qAig.png" /></figure><p><strong>This is normal behavior.</strong> Slack slash commands expect a response within 3 seconds after executing, but our Lambda function is taking more time than that and hence the error. <strong>We will fix this later.</strong></p><p>Despite the error, the backup should still succeed. Check your S3 bucket again — you’ll see the new dump file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NlmwmETyYPbK0dhDeQ1AQ.png" /></figure><h4>5. Editing the Lambda function</h4><p>To prevent the operation_timeout error, we need to change the Lambda function just a little bit:</p><p>Here’s the original handler function:</p><pre>export const handler = async () =&gt; {<br>  await dumpMongoToS3()<br>}</pre><p>Modify it to return a response immediately, but run the dumpMongoToS3() in the background with setTimeout:</p><pre>export const handler = async () =&gt; {<br> setTimeout(() =&gt; {<br>  dumpMongoToS3()<br> }, 0)<br><br> return {<br>  statusCode: 200,<br>  body: &quot;Running backup in background.&quot;<br> }<br>}</pre><p>Run your /mongodb-backup command in your Slack channel, and you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ho_FuIgSpXPngrxN6V4Mbg.png" /></figure><h3><strong>Conclusion</strong></h3><p>Now you’ve built a custom system that lets you back up <strong>MongoDB</strong> directly from a <strong>Slack Command</strong>— using <strong>API Gateway</strong> and a <strong>Lambda</strong> function.</p><p>This setup is a solid starting point for both automation and manual control. From here, you could expand it with Slack notifications, backup status logs, or even direct links to your S3 backup bucket for easier access. The possibilities are endless :)</p><p>Cheers, and see you in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ef3f475ea09" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/use-slack-commands-to-trigger-mongodb-backups-with-api-gateway-and-aws-lambda-7ef3f475ea09">Use Slack Commands to Trigger MongoDB Backups with API Gateway and AWS Lambda</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Back Up MongoDB Data Every Week with EventBridge & AWS Lambda]]></title>
            <link>https://blog.devops.dev/backing-mongodb-data-every-week-with-eventbridge-aws-lambda-5beb24748db2?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5beb24748db2</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 05:30:12 GMT</pubDate>
            <atom:updated>2025-07-23T03:54:16.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stream MongoDB dumps to S3 in real time using a serverless workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJ84HrtOfE3-r1ktGLLrAA.png" /><figcaption>EventBridge triggers the mongodb-backup Lambda function on a scheduled interval.</figcaption></figure><p>Hello everyone! Recently, I created a MongoDB microservice using AWS Lambda &amp; EventBridge to back up data every week.</p><p>I built this because I needed a scheduled backup service without relying on MongoDB Atlas’ paid service.</p><p>Here we go!</p><h3>Overview</h3><h4>1. Creating an npm project</h4><p>First, initialize a mongodb-backup project and create an index.js and .env file:</p><pre>mkdir mongodb-backup<br>cd mongodb-backup<br>npm init -y<br>touch index.js .env</pre><p>Install the required dependencies:</p><pre>npm i moment-timezone dotenv @aws-sdk/client-s3 @aws-sdk/lib-storage</pre><p>Edit your package.json:</p><pre>{<br>  &quot;name&quot;: &quot;mongodb-backup&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  },<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@aws-sdk/client-s3&quot;: &quot;^3.848.0&quot;,<br>    &quot;@aws-sdk/lib-storage&quot;: &quot;^3.848.0&quot;,<br>    &quot;dotenv&quot;: &quot;^17.2.0&quot;,<br>    &quot;moment-timezone&quot;: &quot;^0.6.0&quot;<br>  }<br>}</pre><p>Edit your index.js:</p><pre>import &quot;dotenv/config&quot;<br>import { S3Client } from &quot;@aws-sdk/client-s3&quot;<br>import { Upload } from &quot;@aws-sdk/lib-storage&quot;<br>import moment from &quot;moment-timezone&quot;<br>import { spawn } from &quot;child_process&quot;<br>import { PassThrough } from &quot;stream&quot;<br><br>const s3 = new S3Client({<br> region: process.env.S3_REGION,<br> credentials: {<br>  accessKeyId: process.env.S3_ACCESS_KEY,<br>  secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,<br> },<br>})<br><br>const dumpMongoToS3 = async () =&gt; {<br> const date = moment().tz(&quot;Asia/Seoul&quot;).format(&quot;YYYY-MM-DD_HH:mm:ss&quot;)<br> const key = `data-backup/${date}_dump`<br><br> const passthrough = new PassThrough()<br><br> const dump = spawn(&quot;mongodump&quot;, [<br>  &quot;--uri&quot;,<br>  process.env.MONGO_URL,<br>  &quot;--archive&quot;,<br>  &quot;--gzip&quot;,<br> ])<br><br> dump.stderr.on(&quot;data&quot;, (data) =&gt; {<br>  console.error(`stderr: ${data}`)<br> })<br><br> const upload = new Upload({<br>  client: s3,<br>  params: {<br>   Bucket: process.env.S3_BUCKET_NAME,<br>   Key: key,<br>   Body: passthrough,<br>  },<br> })<br><br> dump.stdout.pipe(passthrough)<br><br> // Wait for both upload and dump process to finish<br> await Promise.all([<br>  upload.done(),<br>  new Promise((resolve, reject) =&gt; {<br>   dump.on(&quot;close&quot;, (code) =&gt; {<br>    if (code === 0) resolve(null)<br>    else reject(new Error(`mongodump exited with code ${code}`))<br>   })<br>  }),<br> ])<br><br> console.log(&quot;Upload to S3 complete:&quot;, key)<br>}<br><br>await dumpMongoToS3()</pre><p>Here is a quick summary:</p><ul><li>mongodump executable generates a MongoDB backup and writes it to stdout.</li><li>A PassThrough stream pipes this output directly into the AWS S3 upload, acting as a bridge between the mongodump process and the S3 Upload stream — without buffering to disk or memory, which makes it scalable.</li></ul><p>Edit your .env file and input credentials:</p><pre>MONGO_URL=AAAA<br>S3_REGION=BBBB<br>S3_ACCESS_KEY=CCCC<br>S3_SECRET_ACCESS_KEY=DDDD<br>S3_BUCKET_NAME=EEEE</pre><p>You can find your MONGO_URL by going to the MongoDB Atlas dashboard, clicking Connect &gt; Drivers under your cluster settings.</p><p>Make sure to replace &lt;db_password&gt; in the connection string with your actual database user’s password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9UuruWdZO6S10-PgPn45A.png" /><figcaption>Your MongoDB connection URL. Make sure to replace &lt;db_password&gt; with the password for the database user.</figcaption></figure><p>Now, add the mongodump executable to your project. You can download it here:</p><p><a href="https://www.mongodb.com/try/download/database-tools">Download MongoDB Command Line Database Tools</a></p><p>Make sure to select the right platform for your OS before downloading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHVugQBFtMWUvI0Mb1jifw.png" /><figcaption>Downloading MongoDB Command Line Database Tools.</figcaption></figure><p>The mongodump executable will be inside the bin directory of the downloaded package.</p><p>Once done, your directory should look like this:</p><pre>mongo-backup/<br>├── .env<br>├── index.js<br>├── mongodump<br>├── package-lock.json<br>└── package.json</pre><h4><strong>2. Testing your npm project</strong></h4><p>Once you’re done, run your npm project:</p><pre>npm start</pre><p>You should see something like this in your terminal:</p><pre>stderr: 2025-07-21T00:58:12.018+0900    [###############.........]  sample_mflix.embedded_movies  2223/3483  (63.8%)<br><br>stderr: 2025-07-21T00:58:15.018+0900    [######################..]  sample_mflix.embedded_movies  3292/3483  (94.5%)<br><br>stderr: 2025-07-21T00:58:18.018+0900    [######################..]  sample_mflix.embedded_movies  3292/3483  (94.5%)<br><br>stderr: 2025-07-21T00:58:19.562+0900    [########################]  sample_mflix.embedded_movies  3483/3483  (100.0%)<br><br>stderr: 2025-07-21T00:58:19.691+0900    done dumping sample_mflix.embedded_movies (3483 documents)<br><br>Upload to S3 complete: data-backup/2025-07-21_00:57:29_dump</pre><p>Now check your S3 bucket to make sure that the dump file has been successfully uploaded to the data-backup/ directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlkX19D0n9dWl-M1UuPIGQ.png" /><figcaption>You should see a dump file in the data-backup/ directory in your S3 bucket.</figcaption></figure><h4>3. Creating a Lambda Function</h4><p>Now, let’s prepare your npm project for AWS Lambda.</p><p>First, create a Lambda function in the AWS Console. Choose Node.js v22.x runtime and x86_64 architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*407c6t0jdPkExPP1nL64ug.png" /><figcaption>Creating a Lambda function with Node v22.x &amp; x86_64 architecture.</figcaption></figure><p>Lambda functions already have the AWS SDK built-in and support environment variables out of the box. Therefore, you can uninstall unused packages to reduce the size of node_modules:</p><pre>npm uninstall dotenv @aws-sdk/client-s3 @aws-sdk/lib-storage</pre><p><strong>Also, when using executables in Lambda, add this line at the top of your code. This is crucial in using custom executables in Lambda:</strong></p><pre>process.env[&quot;PATH&quot;] = process.env[&quot;PATH&quot;] + &quot;:&quot; + process.env[&quot;LAMBDA_TASK_ROOT&quot;]</pre><p>You can read more here:</p><p><a href="https://aws.amazon.com/blogs/compute/running-executables-in-aws-lambda/">Running Arbitrary Executables in AWS Lambda | Amazon Web Services</a></p><p>Your final index.js function should look something like this:</p><pre>import { S3Client } from &quot;@aws-sdk/client-s3&quot;<br>import { Upload } from &quot;@aws-sdk/lib-storage&quot;<br>import moment from &quot;moment-timezone&quot;<br>import { spawn } from &quot;child_process&quot;<br>import { PassThrough } from &quot;stream&quot;<br><br>const s3 = new S3Client({<br> region: process.env.S3_REGION,<br> credentials: {<br>  accessKeyId: process.env.S3_ACCESS_KEY,<br>  secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,<br> },<br>})<br><br>// for executables in lambda<br>process.env[&quot;PATH&quot;] = process.env[&quot;PATH&quot;] + &quot;:&quot; + process.env[&quot;LAMBDA_TASK_ROOT&quot;]<br><br>const dumpMongoToS3 = async () =&gt; {<br> const date = moment().tz(&quot;Asia/Seoul&quot;).format(&quot;YYYY-MM-DD_HH:mm:ss&quot;)<br> const key = `data-backup/${date}_dump`<br><br> const passthrough = new PassThrough()<br><br> const dump = spawn(&quot;mongodump&quot;, [<br>  &quot;--uri&quot;,<br>  process.env.MONGO_URL,<br>  &quot;--archive&quot;,<br>  &quot;--gzip&quot;,<br> ])<br><br> dump.stderr.on(&quot;data&quot;, (data) =&gt; {<br>  console.error(`stderr: ${data}`)<br> })<br><br> const upload = new Upload({<br>  client: s3,<br>  params: {<br>   Bucket: process.env.S3_BUCKET_NAME,<br>   Key: key,<br>   Body: passthrough,<br>  },<br> })<br><br> dump.stdout.pipe(passthrough)<br><br> // Wait for both upload and dump process to finish<br> await Promise.all([<br>  upload.done(),<br>  new Promise((resolve, reject) =&gt; {<br>   dump.on(&quot;close&quot;, (code) =&gt; {<br>    if (code === 0) resolve(null)<br>    else reject(new Error(`mongodump exited with code ${code}`))<br>   })<br>  }),<br> ])<br><br> console.log(&quot;Upload to S3 complete:&quot;, key)<br>}<br><br>export const handler = async () =&gt; {<br> await dumpMongoToS3()<br>}</pre><p>Changes made:</p><ul><li>Removed import dotenv/config</li><li>Removed the direct dumpMongoToS3() call</li><li>Append :LAMBDA_TASK_ROOT to PATH to support executables in Lambda</li><li>Exported a proper handler function</li></ul><p><strong>Finally, you need to replace your </strong><strong>mongodump executable with the executable from the </strong><strong>Amazon Linux 2 x86_64 </strong><strong>Command Line Database Tools package to match the AWS Lambda environment:</strong></p><p><a href="https://www.mongodb.com/try/download/database-tools">Download MongoDB Command Line Database Tools</a></p><p>Then, zip your project for Lambda deployment (excluding .env):</p><pre>zip -r lambda_upload.zip . -x &quot;.env&quot;</pre><p>Upload the .zip file in the AWS Lambda console under Upload from &gt; .zip file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h9HVtkIOqbGcI1S-Ltw69A.png" /><figcaption>Upload your project with .zip file in AWS Lambda.</figcaption></figure><h4>4. Editing Lambda Configuration</h4><p>In Configuration &gt; General configuration, set:</p><ul><li>Memory: 1024 MB</li><li>Timeout: 5 minutes</li></ul><p>This setup should work well for small-to-medium MongoDB datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llAxiTMNzgM9HT4iVUIlBA.png" /><figcaption>Click the “Edit” button in “General configuration” tab.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoHeUW4D-43Tv6xZNQfxRw.png" /><figcaption>Change memory to 1024 MB and timeout to 5 minutes.</figcaption></figure><p>Confirm your changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40mM24KLNDvglbh73w9p9Q.png" /></figure><blockquote>This setup should work well for small-to-medium MongoDB datasets. If you’re backing up a large database, increase memory and timeout accordingly. Lambda will terminate the process if it exceeds either limit.</blockquote><p>In Configuration &gt; Environment variables, add all the .env values manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFjcvVHWtAqLB60rl7Mxow.png" /><figcaption>Click the “Edit” button in the “Environment variables” tab.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEBWs6IsnF2pgdkJ6foaiQ.png" /><figcaption>Input the same environment variables as in your .env file.</figcaption></figure><h4>5. Testing your Lambda Function</h4><p>Once done, go to the Test tab, Create new event, and click on Test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKtrwv95qMy5eY2aUvdHXA.png" /><figcaption>Test your Lambda function.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODO053DbCynnnwLG5H7vUA.png" /><figcaption><em>You should see a pending notification while the Lambda is executing.</em></figcaption></figure><p>After executing, you should see a successful notification popup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po_Bh7BmmXex0WI7sVOA0g.png" /><figcaption><em>You should see a success notification once testing completes.</em></figcaption></figure><p>Now check your S3 bucket to make sure that a dump file has successfully been created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeNSG9VDjihr1jQKPwtsKQ.png" /><figcaption>Check your S3 bucket for your dump file.</figcaption></figure><h4>6. Triggering your Lambda function with EventBridge</h4><p>On the main Lambda page, click Add Trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-oJ8d5CkM-XNvReG6I79Q.png" /><figcaption>Add trigger for your Lambda function.</figcaption></figure><p>Select EventBridge (CloudWatch Events):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5cCoiLn9fzdzusNfz9pRw.png" /><figcaption>Select EventBridge as your trigger.</figcaption></figure><p>Create a new rule, with a schedule expression of cron(0 17 ? * MON *) which will trigger your lambda function every Monday 17:00 UTC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gjt8FOtbzGmyd0NLPkpAFA.png" /><figcaption>Create a new rule — schedule the trigger using a cron expression.</figcaption></figure><p>You can learn more about cron expressions here:</p><p><a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-scheduled-rule-pattern.html">Using cron and rate expressions to schedule rules in Amazon EventBridge</a></p><p>After clicking the “Add” button, you should see a trigger created in your Lambda dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGr1NgP7jsQGJTGFGtHFHA.png" /><figcaption>Notification after setting up your EventBridge trigger.</figcaption></figure><h3>Conclusion</h3><p>Now you are all set!</p><p>Your mongodb-backup Lambda function will automatically run every Monday at 17:00, ensuring that your data is safely backed up.</p><p>I’ll be posting a guide on how to manually trigger Lambda functions using API Gateway and Slack commands — so stay tuned!</p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5beb24748db2" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/backing-mongodb-data-every-week-with-eventbridge-aws-lambda-5beb24748db2">Back Up MongoDB Data Every Week with EventBridge &amp; AWS Lambda</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Strategy Pattern for Cloud Storage File Uploads (S3 & R2) in Django]]></title>
            <link>https://blog.devops.dev/using-the-strategy-pattern-for-cloud-storage-file-uploads-s3-r2-in-django-20e7f2a1dde1?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/20e7f2a1dde1</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloudflare-r2]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Sat, 31 May 2025 13:36:05 GMT</pubDate>
            <atom:updated>2025-06-03T15:38:46.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PY3IRAWeKiys90hUlBJfFw.png" /><figcaption>Using the strategy pattern to support multiple cloud file upload strategies (AWS S3 and Cloudflare R2).</figcaption></figure><p>Hello everyone! Recently, while working on a team project, I had to implement logic to upload files to cloud storage.</p><p>Because I wanted the file upload process to be agnostic and decoupled from a specific cloud provider’s code, I decided to use the Strategy Pattern. This was so that when project requirements change in the future, our team could easily switch cloud providers without changing the implementation in our Django server.</p><p>I’ll take you through the process I took to implement this design pattern.</p><h3>Overview</h3><h4>Strategy Pattern</h4><p>The Strategy Pattern is a design pattern that essentially means:</p><blockquote>Choose a behavior, plug a strategy, and swap it out when needed.</blockquote><p>First, you define a common <strong>interface — a general rule of how things should behave. </strong>Then, you create specific implementation— strategies. When you need the behavior to change, you simply swap out the underlying strategy, allowing you to <strong>change the implementation</strong> without changing your main code.</p><h4>An Electric Fan Running on Power or Battery</h4><p>Imagine an electric fan that can run either from an outlet or battery. The behavior is the same — the fan turning to cool the air — but the way it receives power can differ.</p><p>Rather than building two separate fans — one getting power from an outlet and one from a battery — you can design a fan that accepts both. This enables you to switch the power source from an outlet to a battery when needed — let’s say in the case of an outage — without building the other type of fan from scratch.</p><h4>Applying the Pattern to Cloud Storage</h4><p>There are many cloud storage providers to choose from. Depending on factors like reliability, cost, ease of use, or scalability, a team may decide to switch providers.</p><p>If a team decides to move from AWS S3 Storage to CloudFlare R2 Storage, rather than changing every function call from uploadFileToS3() to uploadFileToR2(), why not make a generic function uploadFileToCloudStorage() that allows you to swap out the underlying logic?</p><p>Then, you only have to adjust one place in your code — the strategy selection for uploading files. This approach makes migration to a different provider straightforward, scalable, and maintainable, regardless of project size.</p><h3>Implementation in Django</h3><h4>Step 1: Creating the Interface (UploadFileStrategy)</h4><p>First, define the UploadFileStrategy interface—using an abstract base class—which specifies the common behavior uploadFile:</p><pre>from abc import ABC, abstractmethod<br><br>class UploadFileStrategy(ABC):<br>    @abstractmethod<br>    def uploadFile(self, file, folderName) -&gt; str:<br>        pass<br></pre><p>This is like defining the behavior of a fan to have the turnOn() function. For the UploadFileStrategy, every implementation of this blueprint will have an uploadFile() function.</p><p>Then, add the util function generate_file_key which can be used by classes that implement this interface (abstract class):</p><pre>class UploadFileStrategy(ABC):<br>    @abstractmethod<br>    def uploadFile(self, file, folderName) -&gt; str:<br>        pass<br><br>    def generate_file_key(self, filename, folder):<br>        current_datetime = datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;)<br><br>        if &quot;.&quot; in filename:<br>            file_name, file_extension = filename.rsplit(&quot;.&quot;, 1)<br>            updated_file_name = f&quot;{file_name}_{current_datetime}.{file_extension}&quot;<br>        else:<br>            updated_file_name = f&quot;{filename}_{current_datetime}&quot;<br><br>        file_key = folder + &quot;/&quot; + updated_file_name<br><br>        return file_key</pre><h4>Step 2: Implementing S3 (AWS) Upload Strategy</h4><p>Next, implement the S3UploadStrategy class based on the interface (blueprint) defined above:</p><pre>from .strategy import UploadFileStrategy<br><br>class S3UploadStrategy(UploadFileStrategy):<br>    def __init__(self):<br>        # Initialization goes here<br>    <br>    def uploadFile(self, file, folder):<br>        # implementation goes here</pre><p>The rest is just implementing the logic to connect to the AWS client using the AWS keys and uploading the file to S3:</p><pre>from .strategy import UploadFileStrategy<br>import boto3<br>from botocore.exceptions import NoCredentialsError<br>from django.conf import settings<br><br><br>class S3UploadStrategy(UploadFileStrategy):<br>    def __init__(self):<br>        self.client = boto3.client(<br>            &quot;s3&quot;,<br>            aws_access_key_id=settings.AWS_ACCESS_KEY_ID,<br>            aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,<br>        )<br><br>    def uploadFile(self, file, folder):<br>        file_key = self.generate_file_key(file.name, folder)<br><br>        try:<br>            # Upload file to S3<br>            self.client.upload_fileobj(<br>                file,<br>                settings.AWS_STORAGE_BUCKET_NAME,<br>                file_key,<br>                ExtraArgs={&quot;ContentType&quot;: file.content_type},<br>            )<br><br>            # Return public URL<br>            file_url = f&quot;https://{settings.AWS_STORAGE_BUCKET_NAME}.s3.{settings.AWS_S3_REGION_NAME}.amazonaws.com/{file_key}&quot;<br>            return file_url<br>        except NoCredentialsError:<br>            return &quot;AWS credentials are missing.&quot;<br>        except Exception as e:<br>            return str(e)</pre><p>Notice the use of self.generate_file_key. Because S3UploadStrategy inherits from UploadFileStrategy, it can access methods defined in the blueprint.</p><h4>Step 3: Implementing R2 (CloudFlare) Upload Strategy</h4><p>With the same process, define the R2UploadStrategy. Like before, you need to define the implementation of the uploadFile() method.</p><pre>from .strategy import UploadFileStrategy<br>import boto3<br>from botocore.exceptions import NoCredentialsError<br>from django.conf import settings<br><br><br>class R2UploadStrategy(UploadFileStrategy):<br>    def __init__(self):<br>        # R2 is compatible with boto3 s3 logic<br>        self.client = boto3.client(<br>            &quot;s3&quot;,<br>            aws_access_key_id=settings.R2_ACCESS_KEY,<br>            aws_secret_access_key=settings.R2_SECRET_ACCESS_KEY,<br>            endpoint_url=settings.R2_ENDPOINT_URL,<br>            region_name=&quot;auto&quot;,<br>        )<br><br>    def uploadFile(self, file, folder):<br>        file_key = self.generate_file_key(file.name, folder)<br><br>        try:<br>            # Upload file to R2<br>            self.client.upload_fileobj(<br>                file,<br>                settings.R2_STORAGE_BUCKET_NAME,<br>                file_key,<br>                ExtraArgs={&quot;ContentType&quot;: file.content_type},<br>            )<br><br>            # Return public URL<br>            file_url = f&quot;{settings.R2_PUBLIC_URL}/{file_key}&quot;<br>            return file_url<br>        except NoCredentialsError:<br>            return &quot;AWS credentials are missing.&quot;<br>        except Exception as e:<br>            return str(e)</pre><h4>Step 4: Creating the UploadClient</h4><p>After implementing the two strategies, define an UploadClient that accepts either strategy:</p><pre>from abc import ABC, abstractmethod<br><br>class UploadFileStrategy(ABC):<br>    @abstractmethod<br>    def uploadFile(self, file, folderName) -&gt; str:<br>        pass<br><br># Create the UploadClient class<br>class UploadClient:<br>    def __init__(self, strategy: UploadFileStrategy):<br>        self.strategy = strategy<br><br>    def uploadFile(self, file, folder) -&gt; str:<br>        return self.strategy.uploadFile(file, folder)</pre><h4>Step 5: Using it in Practice</h4><p>Now, use the UploadClient in your Django views:</p><pre>from .strategy import UploadClient<br>from .s3_strategy import S3UploadStrategy<br><br>upload_client = UploadClient(S3UploadStrategy())<br><br>upload_client.uploadFile(file, &quot;folder&quot;)</pre><p>When switching cloud providers, simply change the strategy:</p><pre>from .strategy import UploadClient<br>from .r2_strategy import R2UploadStrategy<br><br>upload_client = UploadClient(R2UploadStrategy())<br><br>upload_client.uploadFile(file, &quot;folder&quot;)</pre><p>In my Django view, it might look something like this:</p><pre>...<br><br>upload_client = UploadClient(S3UploadStrategy())<br><br>@csrf_exempt<br>def index(request):<br>    if request.method == &quot;POST&quot;:<br>        if &quot;file&quot; not in request.FILES:<br>            return HttpResponseBadRequest(&quot;Missing file&quot;)<br><br>        uploaded_file = request.FILES[&quot;file&quot;]<br><br>        try:<br>            file_url = upload_client.uploadFile(uploaded_file, folder=&quot;file&quot;)<br><br>            raw_bytes = requests.get(file_url).content<br><br>            output = pypandoc.convert_text(raw_bytes, &quot;latex&quot;, format=&quot;docx&quot;)<br><br>            result = convert_latex_to_braille(output)<br><br>            response = HttpResponse(result, content_type=&quot;text/plain&quot;)<br>            response[&quot;Content-Disposition&quot;] = (<br>                &#39;attachment; filename=&quot;converted_file.txt&quot;&#39;<br>            )<br><br>            return response<br>        except Exception as e:<br>            print(e)<br>            return JsonResponse({&quot;error&quot;: str(e)}, status=500)<br>    else:<br>        return JsonResponse({&quot;error&quot;: &quot;Invalid request method&quot;}, status=405)</pre><p>And there you have it — a scalable, maintainable solution to uploading files using the Strategy Pattern in Django!</p><h3>Conclusion</h3><p>By leveraging the Strategy Pattern, you can create a flexible and maintainable file upload system in Django. This method lets you easily switch between cloud providers like AWS S3 and Cloudflare R2 without changing the core application logic. It simplifies future development, keeping the codebase clean, scalable, and easy to adapt to new requirements.</p><p>Hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20e7f2a1dde1" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/using-the-strategy-pattern-for-cloud-storage-file-uploads-s3-r2-in-django-20e7f2a1dde1">Using the Strategy Pattern for Cloud Storage File Uploads (S3 &amp; R2) in Django</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Access Your Router’s Web Interface Remotely Using SSH Tunneling]]></title>
            <link>https://blog.devops.dev/how-to-access-your-routers-web-interface-remotely-using-ssh-tunneling-537e6fbd2af5?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/537e6fbd2af5</guid>
            <category><![CDATA[port-forwarding]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[ssh-tunnel]]></category>
            <category><![CDATA[remote-access]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Thu, 22 May 2025 15:08:00 GMT</pubDate>
            <atom:updated>2025-05-26T15:48:45.263Z</atom:updated>
            <content:encoded><![CDATA[<h4>Securely connect to your home router from a remote machine using an SSH tunnel — ideal for port forwarding, remote network access, and router configuration.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwordGR3QTrIG5C72dEsQA.png" /><figcaption>SSH tunneling flow to access a router’s web interface. The SSH tunnel from localhost:8888 connects through the Raspberry Pi to reach the router’s admin page at 192.168.219.1:80, all within the private network. This allows secure, remote web access to the router.</figcaption></figure><p>Hello everyone, I recently had to access my router’s web interface to add some port forwarding rules for my Raspberry Pi. The challenge? My Raspberry Pi and router sits in my house — far from where I currently live. Here’s what I had:</p><ul><li>SSH access to my Raspberry Pi</li><li>The Raspberry Pi was connected to the router whose port forwarding rules I needed to change</li><li>I knew my home router’s administrative password</li></ul><h3>The Solution</h3><p>The solution was simple — create an <strong>SSH web tunnel</strong> to access the router’s web interface using the Raspberry Pi from my MacBook!</p><pre>ssh -i ~/.ssh/id_rsa \<br>    -p 22 \<br>    -L 8888:192.168.219.1:80 \<br>    pi@xxx.xxx.xxx.xx</pre><p>Quick breakdown:</p><ul><li>-i: Identity file — <strong>private key</strong> used to SSH into my Raspberry Pi</li><li>-p: Port — port number to connect SSH (defaults to 22)</li><li>-L: Local-port Forwarding<em> — </em>creates a SSH tunnel to a specified address</li><li>pi@xxx.xxx.xxx.xx: IP address of my Raspberry PI to connect via SSH</li></ul><blockquote>This command connects your terminal to the host like a regular SSH session. However, a <strong>SSH web tunnel will also be active in the background</strong> as long as you don’t exit the session.</blockquote><p>Now, opening localhost:8888 provides me access to the router web interface directly from my MacBook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8djFQUjG1LmoAwfUaTB6cw.png" /><figcaption>Accessing localhost:8888 connects to my Pi’s router web interface (at 192.168.219.1) via SSH Tunneling.</figcaption></figure><h3>Syntax</h3><p>Let’s take a close look at this part:</p><pre>-L 8888:192.168.219.1:80</pre><ul><li>8888: Local port that opens on <strong>my MacBook</strong></li><li>192.168.219.1: Internal IP of the router, as <strong>seen from the Raspberry Pi</strong></li><li>80: The HTTP port the router’s web interface uses</li></ul><h3>Traffic Flow (What Actually Happens)</h3><p>How does traffic actually flow? Here are the steps that occurs after the command is run:</p><ol><li>I open http://localhost:8888.</li></ol><p>2. The SSH Daemon on my MacBook accepts that TCP connection because of -L 8888:.</p><p>3. The data is encrypted and sent through the SSH tunnel to my Raspberry Pi (pi@xxx.xxx.xxx.xx).</p><p>4. My Raspberry Pi decrypts it and initiates a <strong>new connection</strong> to 192.168.219.1:80 from its own network.</p><p>5. Data travel back and forth between my MacBook(localhost:8888) and (192.168.219.1:80) giving me access to my router web interface!</p><h3>Taking A Closer Look</h3><p>Here’s the fully explicit version of the forwarding flag:</p><pre>-L 127.0.0.1:8888:192.168.219.1:80</pre><p>I think this is easier to understand at first glance, since 127.0.0.1(localhost):8888 on my host machine is being tunneled into 192.168.219.1:80 on my remote machine.</p><p>However, you can omit the 127.0.0.1 since it will default to it if no other address is specified to create the flag:</p><pre>-L 8888:192.168.219.1:80</pre><h4>Shortest One-Liner (Using SSH Config)</h4><p>If you’ve set up your SSH config file with a host alias like this:</p><pre># ~/.ssh/config<br><br>Host pi-1<br>  HostName xxx.xxx.xxx.xx<br>  User pi<br>  IdentityFile ~/.ssh/id_rsa</pre><p>You can simplify the tunnel command to:</p><pre>ssh -L 8888:192.168.219.1:80 pi-1</pre><p>If you want to learn more, you can read here:</p><p><a href="https://awstip.com/how-to-simplify-the-ssh-process-for-your-ec2-instance-two-easy-methods-1f5fcdb4a55b">How to Simplify the SSH Process for Your EC2 Instance: Two Easy Methods</a></p><h3>Conclusion</h3><p>To summarize, whenever you need to access an internal IP or web interface from a remote machine, SSH tunneling is a simple and secure option — especially when dealing with graphical interfaces like router dashboards.</p><p>Hope this helps! Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=537e6fbd2af5" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/how-to-access-your-routers-web-interface-remotely-using-ssh-tunneling-537e6fbd2af5">How to Access Your Router’s Web Interface Remotely Using SSH Tunneling</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding IP Addresses and CIDR Notation]]></title>
            <link>https://blog.devops.dev/understanding-ip-addresses-and-cidr-notation-bb1699fe65c6?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb1699fe65c6</guid>
            <category><![CDATA[cidr]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[ip-address]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 14:37:07 GMT</pubDate>
            <atom:updated>2025-05-21T15:42:18.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, while working on a manual Kubernetes cluster, I’ve recently embarked on a journey to understand CIDR notation and what it actually means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9t169DyH_O78MD7puwrgCw.png" /><figcaption>Brief overview of CIDR notation.</figcaption></figure><h3>Classless Inter-Domain Routing (CIDR)</h3><p>CIDR is a method for allocating IP addresses and routing IP packets. You probably have seen CIDR notation which looks like this:</p><pre>192.168.0.0/24</pre><p>This means:</p><ul><li>The first 24 bits are the network portion</li><li>The remaining 8 bits (32 – 24) are used for hosts</li></ul><blockquote>But what does this actually mean?</blockquote><p>Well, let’s first take a look at an IP Address without the /24:</p><pre>192.168.0.0<br>[8bits].[8bits].[8bits].[8bits]</pre><p>An IP Address is composed of 4 numbers separated by a dot (an octet), and each octet is 8 bits. Since one bit represents 2, there are a total of 2⁸ = 256 (0 ~ 255) different numbers you can represent in each octet.</p><pre>0.0.0.0 ~ 255.255.255.255</pre><p>Because there are 4 octets in an IP Address, an IP Address is 32 bits. When you are configuring a private network like that in a Kubernetes cluster, you want to assign these network IPs to your nodes.</p><h3>Assigning IPs</h3><p>Okay so assigning IPs to nodes, hosts, whatever in a private network. Got it. Why not something like this?</p><pre>1.1.1.1 (host 1)<br>2.2.2.2 (host 2)<br>3.3.3.3 (host 3)<br>4.4.4.4 (host 4)</pre><p>Well, the problem is that 1.1.1.1, 2.2.2.2, 3.3.3.3, and 4.4.4.4 are all public reserved IPs. You have complete freedom to designate these IPs in your private network, but using these IPs will prevent the network from being able to reach the public IPs of 1.1.1.1 (Cloudflare DNS), 2.2.2.2, etc. Sure, if you will never access those IPs publicly, you can go ahead and use them in your private network, but it does not follow the best practices.</p><h4>What is the best practice for assigning IPs in private network?</h4><p>To avoid conflicts with public IPs, certain ranges are commonly reserved exclusively for private/internal use:</p><ul><li>192.168.0.0 ~ 192.168.255.255 (small networks)</li><li>172.16.0.0 ~ 172.31.255.255 (medium networks)</li><li>10.0.0.0 ~ 10.255.255.255 (large networks)</li></ul><p>These IPs will never be used publicly, so you can rest assured that use them in your private network. You are probably familiar with the 192.168.xxx.xxx IP address, which is almost always used for home networks in your router.</p><p>Now writing 192.168.0.0 ~ 192.168.255.255 all the time is quite lengthy. What we want is a way to shorten this range into a notation. Hence, the 192.168.0.0/16 is born.</p><h4>192.168.0.0/16</h4><p>So what does the /16 mean? Well in the range 192.168.0.0 ~ 192.168.255.255, notice how the first 192.168 is fixed, and the last two octets change:</p><pre>192.168.255.255<br>[192].[168].[0 ~ 255].[0 ~ 255]</pre><p><strong>The first two octets are fixed.</strong></p><p><strong>The first two 8 bits are fixed.</strong></p><p><strong>The first 16 bits are fixed.</strong></p><p><strong>The remaining (32–16 = 16) bits change.</strong></p><p><strong>The first 16 bits are fixed, the remaining 16 bits change.</strong></p><p>Because the <strong>first 16 bits are fixed</strong>, we used the notation 192.168.0.0/16. This automatically indicates that the remaining 16 bits (32 — 16) change, which means this CIDR supports up to 2¹⁶- 2 = 65,534 usable IP addresses (more on this later).</p><h4>172.16.0.0/12</h4><p>Let’s take a look at 172.16.0.0/12 :</p><pre>[172].[16 ~ 31].[0 ~ 255].[0 ~ 255]</pre><p>From our conclusion earlier, /12 would also mean that <strong>12 bits are fixed</strong>, the remaining <strong>20 bits change</strong>.</p><h4><strong>Why the 16~31?</strong></h4><p>Why does the second octet range from 16 ~ 31?</p><pre>[172].[16 ~ 31].[0 ~ 255].[0 ~ 255]<br>        ↑ Here</pre><p>We have to look at 172.16.0.0 in binary:</p><pre>172 = 10101100  <br>16  = 00010000<br>0 = 00000000<br><br>172.16.0.0 = <br>10101100.00010000.00000000.00000000</pre><p>/12 means that the<strong> first 12 bits</strong> are fixed, so:</p><pre>-&gt; 172.16.0.0 =<br>-&gt; 10101100.0001xxxx.xxxxxxxx.xxxxxxxx<br>                ↑ The last 20 bits change</pre><p>Take a look at the second octet. Because the first 4 bits are fixed as 0001, all the possible combinations or 0s and 1s are in the range:</p><pre># binary range<br>00010000 ~ 00011111<br><br># convert to base 10 number<br>16 ~ 31</pre><p>Therefore,172.16.0.0/12 means that first <strong>12 bits are fixed</strong>, and the last<strong> 20 bits change</strong> to create the range:</p><pre>[172].[16 ~ 31].[0 ~ 255].[0 ~ 255]</pre><p>which supports up to 2²⁰ = about 1 million usable IP addresses (technically 2²⁰- 2= 1,048,574).</p><h4><strong>10.0.0.0/8</strong></h4><p>Finally, let’s find the range for 10.0.0.0/8.</p><ul><li>First 8 bits are fixed</li><li>Last 24 bits change (last three octets change)</li></ul><pre>[10].[0 ~ 255].[0 ~ 255].[0 ~ 255]</pre><p>Which can support up to 2²⁴ = 16,777,216 IP Addresses (16,777,214 which are usable).</p><h3>Two Special Cases when Assigning IPs</h3><p>There are two important cases you must consider before assigning IP addresses:</p><ul><li>The first address in your subnet</li><li>The last address in your subnet</li></ul><p>Let’s take a look at 192.168.1.0/24 :</p><pre>[192].[168].[1].[0 ~ 255]</pre><p>The first address is 192.168.1.0 and the last address is 192.168.1.255.</p><p>These IP addresses have a specific purpose, so it’s best practice not to assign them to any hosts when configuring your own private network. Doing this may later cause routing conflicts and all sorts of networking hell when your private network starts to interact with external ones.</p><h4>First Address of Subnet (Network IP)</h4><p>In the subnet 192.168.1.0/24, 192.168.1.0 is the <strong>Network IP. </strong>This is used by routers to know where a particular subnet starts. This is useful when you want to forward a request to your private network:</p><pre>Destination: 192.168.1.3/24</pre><p>In which then your router would decide:</p><pre>192.168.1.3 is in range 192.168.1.0/24 → Send through LAN interface</pre><p>Where a host connected via LAN would be able to receive the packet.</p><h4>Last Address of Subnet (Broadcast IP)</h4><p>In the subnet 192.168.1.0/24, 192.168.1.255 is the <strong>Broadcast IP</strong>. This is a special IP reserved for broadcasting, which sends data / messages to ALL hosts in the same subnet. This is used primarily when you want to locate a certain host in the same network but don’t have the IP address.</p><p>You would broadcast something like:</p><pre>To: 192.168.1.255<br>Message: Who has 192.168.1.4? Tell me your MAC!</pre><p>In which 192.168.1.4 would respond.</p><blockquote>Therefore, when you talk about the numbers of usable IP Addresses, you calculate using the formula 2^(number of bits that change) - 2, since the first and last IP Addresses are reserved. For 192.168.0.0/16, since the last 16 bits change (32–16) to create the range 192.168.0.0 ~ 192.168.255.255, you get 2¹⁶ - 2 = 65,534 usable IP Addresses.</blockquote><h3>Conclusion</h3><p>To conclude, CIDR notation allows IP Addresses to be divided into groups, or subnets. For the IP Address 192.168.0.0/24, /24 means that the first 24 bits of the IP Address is fixed, while the remaining 8 bits (32 – 24) change. This makes the IP Address range from:</p><pre>192.168.0.0 ~ 192.168.0.255</pre><p>In that range, the first IP Address of 192.168.0.0 is reserved for the Network IP, and the last IP Address of 192.168.0.255 is a broadcasting IP for talking to all IP Addresses in the same subnet.</p><p>Creating subnets with CIDR notation allows you to divide IP Addresses into network segments, which is super useful for building things like a Kubernetes cluster or a private VPN network.</p><p>Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1699fe65c6" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/understanding-ip-addresses-and-cidr-notation-bb1699fe65c6">Understanding IP Addresses and CIDR Notation</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up an Nginx Reverse Proxy and Load Balancer Using Docker]]></title>
            <link>https://blog.devops.dev/how-to-set-up-an-nginx-reverse-proxy-and-load-balancer-using-docker-7cf0c893bb78?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf0c893bb78</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 11:12:51 GMT</pubDate>
            <atom:updated>2025-03-27T19:14:11.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>A minimal Nginx reverse proxy and load balancer setup for Docker containers you can build upon.</h4><p>Hello everyone, in this article we are going to set up a Nginx reverse proxy server that will load balance traffic to two identical Docker images. By having a load balancer set up, when we use a CI/CD pipeline to deploy Docker images, we can enable blue-green deployment since Nginx will automatically direct traffic to running Docker images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiXutgojVRITAHxd8KX-hg.png" /><figcaption>Basic overview of the Nginx reverse proxy setup we’ll be building in this guide.</figcaption></figure><p>For more about blue green deployment, you can read my article here: <a href="https://medium.com/@jae.yoon7373/blue-green-deployment-with-jenkins-aws-ecr-and-aws-ec2-using-django-05c74887ad4c">Blue-Green Deployment with Jenkins, AWS ECR, and AWS EC2 Using Django</a>.</p><h3>1. Running Docker Processes</h3><h4>1.1 Create a docker network</h4><p>First, we need to create a Docker network that will connect our Nginx server and our Docker containers:</p><pre>sudo docker network create hello-network</pre><h4>1.2 Running two idential docker containers</h4><p>Next, we will run two nginxdemos/hello containers that map their internal port 80 to 8080 and 8081 on the host, respectively:</p><pre>sudo docker run -d \<br>  --name hello-service-1 \<br>  --network hello-network \<br>  -p 8080:80 \<br>  nginxdemos/hello<br><br>sudo docker run -d \<br>  --name hello-service-2 \<br>  --network hello-network \<br>  -p 8081:80 \<br>  nginxdemos/hello</pre><p>The nginxdemos/hello image runs a simple web server on port 80 inside the container and displays information such as headers and container hostnames.</p><p>Check that the services are running:</p><pre>sudo docker ps</pre><p>You should see something like this:</p><pre>2571fa780aa7   nginxdemos/hello   &quot;/docker-entrypoint.…&quot;   3 seconds ago   Up 2 seconds   0.0.0.0:8081-&gt;80/tcp, [::]:8081-&gt;80/tcp   hello-service-2<br>89b138942a71   nginxdemos/hello   &quot;/docker-entrypoint.…&quot;   3 seconds ago   Up 2 seconds   0.0.0.0:8080-&gt;80/tcp, [::]:8080-&gt;80/tcp   hello-service-1</pre><h3>2. Setting Up nginx.conf</h3><p>After we have two running containers on the same Docker network, we will create an nginx.conf file that will configure our Nginx server to load balance incoming requests to both hello-service-1 and hello-service-2.</p><h4>2.1 Configuring nginx</h4><p>First create an nginx directory:</p><pre>mkdir nginx</pre><p>Create a nginx.conf file inside the nginx directory:</p><pre>cd nginx<br>vim nginx.conf</pre><p>Paste the following contents into nginx.conf:</p><pre>upstream hello-backend {<br>    least_conn;<br>    server hello-service-1:80 max_fails=3 fail_timeout=30s;<br>    server hello-service-2:80 max_fails=3 fail_timeout=30s;<br>}<br><br>server {<br>    listen 6000;<br>    server_name localhost;<br><br>    location / {<br>        proxy_pass http://hello-backend;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><p><strong>The </strong><strong>upstream block:</strong></p><ul><li>upstream: defines a group of services that Nginx will forward traffic to. This is commonly used primarily for load balancing.</li><li>least_conn: the load balancing strategy — in this case, each request is sent to the server with fewest active connections.</li><li>server: points to a Docker container listening on port 80. Since Nginx and the service containers are in the same hello-network, we use the container name (instead of the IP address) and specify the port that the nginxdemos/hello container is running on inside the container (port 80, <strong>not </strong><strong>8080 or </strong><strong>8081</strong> which is mapped from the host).</li></ul><blockquote>To learn more about load balancing strategies for Nginx, you can check out my article here: <a href="https://medium.com/devops-dev/exploring-different-nginx-load-balancing-strategies-other-than-least-conn-3377d096b724">Exploring different Nginx Load Balancing Strategies (other than least_conn)</a></blockquote><p><strong>The </strong><strong>server block:</strong></p><ul><li>listen 6000: tells Nginx to listen on port 6000.</li><li>server_name: defines the domain name Nginx will respond to. If configuring for production, it would point to a domain name such as api.example.com. Since we are testing locally, we will use localhost.</li></ul><h3>3. Running Nginx Server with Docker Compose</h3><h4>3.1 Creating a Docker Compose File</h4><p>Create a nginx-compose.yml file with the following contents:</p><pre>services:<br>  nginx:<br>    image: nginx:latest<br>    ports:<br>      - &quot;6000:6000&quot;<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/conf.d/default.conf  # Updated nginx configuration<br>    container_name: nginx-hello-proxy<br>    networks:<br>      - hello-network<br>    restart: on-failure<br><br>networks:<br>  hello-network:<br>    external: true</pre><p>Important things to note:</p><ul><li>volumes: mounts the nginx.conf we created to /etc/nginx/conf.d/default.conf inside the container, so that our custom nginx.conf is applied to our reverse proxy server.</li><li>networks: we include our reverse proxy in the hello-network so that, in the nginx.conf file, our hostnames are resolved and correctly point to the Docker containers.</li></ul><h4>3.2 Running the Nginx Reverse Proxy with Docker Compose</h4><p>Now run your nginx-compose.yml file:</p><pre>sudo docker compose -f nginx-compose.yml up -d</pre><p>Important things to note:</p><ul><li>-f: specifies the docker compose file we will use.</li><li>-d: tells docker to run in detached mode, so that the reverse proxy keeps running even after we exit the terminal.</li></ul><p>Now check your services with:</p><pre>sudo docker ps</pre><p>You should see something like this:</p><pre>f3dec2e659ca   nginx:latest       &quot;/docker-entrypoint.…&quot;   3 seconds ago    Up 2 seconds    80/tcp, 0.0.0.0:6000-&gt;6000/tcp, :::6000-&gt;6000/tcp   nginx-hello-proxy<br>2571fa780aa7   nginxdemos/hello   &quot;/docker-entrypoint.…&quot;   58 seconds ago   Up 57 seconds   0.0.0.0:8081-&gt;80/tcp, [::]:8081-&gt;80/tcp             hello-service-2<br>89b138942a71   nginxdemos/hello   &quot;/docker-entrypoint.…&quot;   58 seconds ago   Up 58 seconds   0.0.0.0:8080-&gt;80/tcp, [::]:8080-&gt;80/tcp             hello-service-1</pre><h3>4. Testing Load Balancing</h3><h4>4.1 Open Logs for Service Containers</h4><p>In your terminal, open the logs for both hello-service-1 and hello-service-2:</p><pre>sudo docker logs hello-service-1 -f<br>sudo docker logs hello-service-2 -f</pre><p>You should see something like this for both your containers:</p><pre>...<br><br>/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh<br>/docker-entrypoint.sh: Configuration complete; ready for start up<br>2025/03/26 11:16:19 [notice] 1#1: using the &quot;epoll&quot; event method<br>2025/03/26 11:16:19 [notice] 1#1: nginx/1.27.4<br>2025/03/26 11:16:19 [notice] 1#1: built by gcc 14.2.0 (Alpine 14.2.0)<br>2025/03/26 11:16:19 [notice] 1#1: OS: Linux 6.6.51+rpt-rpi-2712<br>2025/03/26 11:16:19 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576<br>2025/03/26 11:16:19 [notice] 1#1: start worker processes<br>2025/03/26 11:16:19 [notice] 1#1: start worker process 20<br>2025/03/26 11:16:19 [notice] 1#1: start worker process 21<br>2025/03/26 11:16:19 [notice] 1#1: start worker process 22<br>2025/03/26 11:16:19 [notice] 1#1: start worker process 23</pre><h4>4.2 Pinging your Nginx Reverse Proxy Server:</h4><p>We configured our reverse proxy server to listen on localhost:6000. You can use curl to send a request:</p><pre>curl localhost:6000</pre><p>Run this command multiple times, and you should see logs in both your hello-service-1 and hello-service-2 containers:</p><p><strong>hello-service-1</strong></p><pre>172.18.0.4 - - [26/Mar/2025:10:13:31 +0000] &quot;GET / HTTP/1.0&quot; 200 12114 &quot;-&quot; &quot;curl/7.88.1&quot; &quot;172.18.0.1&quot;<br>172.18.0.4 - - [26/Mar/2025:10:13:43 +0000] &quot;GET / HTTP/1.0&quot; 200 12114 &quot;-&quot; &quot;curl/7.88.1&quot; &quot;172.18.0.1&quot;<br>172.18.0.4 - - [26/Mar/2025:10:13:44 +0000] &quot;GET / HTTP/1.0&quot; 200 12114 &quot;-&quot; &quot;curl/7.88.1&quot; &quot;172.18.0.1&quot;</pre><p><strong>hello-service-2</strong></p><pre>172.18.0.4 - - [26/Mar/2025:10:13:47 +0000] &quot;GET / HTTP/1.0&quot; 200 12114 &quot;-&quot; &quot;curl/7.88.1&quot; &quot;172.18.0.1&quot;<br>172.18.0.4 - - [26/Mar/2025:10:13:48 +0000] &quot;GET / HTTP/1.0&quot; 200 12114 &quot;-&quot; &quot;curl/7.88.1&quot; &quot;172.18.0.1&quot;<br>172.18.0.4 - - [26/Mar/2025:10:13:48 +0000] &quot;GET / HTTP/1.0&quot; 200 12114 &quot;-&quot; &quot;curl/7.88.1&quot; &quot;172.18.0.1&quot;</pre><h3>Conclusion</h3><p>There you have it! You’ve successfully configured a reverse proxy Nginx server that load balances traffic to two servers (hello-service-1 and hello-service-2). If hello-service-1 is down, Nginx will automatically redirect traffic to hello-service-2, which is crucial when maintaining a system with zero downtime.</p><p>One thing to note is that while we placed hello-service-1, hello-service-2, and nginx-hello-proxy containers on the same host, you would ideally want to spread them across multiple hosts in production environments. This ensures that if the host containing a service goes down, you have services in other hosts that Nginx can redirect traffic to.</p><p>Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf0c893bb78" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/how-to-set-up-an-nginx-reverse-proxy-and-load-balancer-using-docker-7cf0c893bb78">How to Set Up an Nginx Reverse Proxy and Load Balancer Using Docker</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring different Nginx Load Balancing Strategies (other than least_conn)]]></title>
            <link>https://blog.devops.dev/exploring-different-nginx-load-balancing-strategies-other-than-least-conn-3377d096b724?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3377d096b724</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 15:12:44 GMT</pubDate>
            <atom:updated>2025-04-03T02:47:11.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Alternative Approaches to Load Balancing for Different Use Cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gl8LjgNoLJno5SPDPylz6A.png" /><figcaption>Load balancing with Nginx using reverse proxy</figcaption></figure><p>Hello, in this article we will explore different load balancing strategies for Nginx reverse proxy, other than the most popular least_conn strategy.</p><p>A sample nginx.conf will look something like this:</p><pre>worker_processes 1;<br><br>events {<br>    worker_connections 1024;<br>}<br><br>http {<br>    upstream my_backend {<br>        least_conn;<br>        server service-1:80;<br>        server service-2:80;<br>    }<br><br>    server {<br>        listen 80;<br><br>        location / {<br>            proxy_pass http://my_backend;<br>            <br>            # ...Other header configurations<br>        }<br>    }<br>}</pre><p>Notice the upstream block. This block defines the services that the Nginx reverse proxy server should forward traffic to, along with the load balancing strategy. In this case, the strategy is set to least_conn.</p><p>Let’s take a look at the different load balancing strategies available in Nginx:</p><h3>1. round_robin (default)</h3><h4>Taking Turns Among Servers</h4><p>Nginx will distribute requests across servers sequentially — server A, then B, then C, and then back to A. If weights are set, Nginx adjusts the frequency accordingly.</p><pre>upstream backend {<br>  #default strategy is round_robin<br>  server service-1:80 weight=2;<br>  server service-2:80;<br>}</pre><p>In this case, weight=2 is set for service-1. This means that for every 3 requests, 2 requests will be mapped to service-1 and 1 request to service-2 (since the default weight is 1).</p><h4><strong>Characteristics:</strong></h4><ul><li>Default strategy, simple and reliable</li><li>Good for static websites, stateless microservices with uniform response time</li><li>Not adaptive to real-time load (e.g., slow backends still get requests)</li></ul><h3>2. ip_hash</h3><h4>Same IP, Same Server</h4><p>The server to which a request is sent is determined from the client’s IP address. The IPv4 or IPv6 address is used to calculate a hash value, which then maps the request to a specific server.</p><p>ip_hash guarantees that requests from the same IP address are always routed to the same backend.</p><pre>upstream backend {<br>    ip_hash;<br>    server service-1:80;<br>    server service-2:80;<br>}</pre><h4><strong>Characteristics:</strong></h4><ul><li>Provides session stickiness</li><li>Good for user dashboards or e-commerce apps that require in-memory sessions</li><li>Can lead to uneven traffic distribution — requests are always mapped to a specific server based on IP</li><li>Clients behind NAT (e.g., office networks, shared proxies) may all be hashed to the same backend, causing uneven load</li></ul><h3>3. least_conn</h3><h4><strong>Server with Least Active Connections</strong></h4><p>A request is sent to the server with the fewest active connections. This is dynamic and adapts as connections are opened and closed. Nginx can also consider server weights.</p><pre>upstream backend {<br>    least_conn;<br>    server service-1:80;<br>    server service-2:80;<br>}</pre><h4><strong>Characteristics:</strong></h4><ul><li>Dynamically adapts to backend load</li><li>Great for APIs with long-polling, file uploads, or WebSocket connections</li><li>Doesn’t account for backend CPU usage, memory load, or response latency</li></ul><h3>4. least_time (NGINX Plus only)</h3><h4><strong>Lowest Average Response Time</strong></h4><p>Tracks the average response time of each server and routes traffic to the backend with the lowest latency. You can measure this based on when the response header is received (header) or when the full response is received (last_byte).</p><pre>upstream backend {<br> least_time header;<br> server service-1:80;<br> server service-2:80;<br>}</pre><h4><strong>Characteristics:</strong></h4><ul><li>Reacts to real backend performance (not just connection count)</li><li>Only available in <strong>Nginx Plus</strong> 😢</li><li>Good for performance-critical applications like trading platforms or real-time dashboards</li></ul><h3>5. random</h3><h4>Rolling a Dice to Direct Traffic</h4><p>As the name suggests, Nginx randomly selects a backend for each incoming request.</p><pre>upstream backend {<br>    random two least_conn;<br>    server service-1:80;<br>    server service-2:80;<br>}</pre><p>You can specific the two parameter, which will have Nginx randomly select two servers and then choose one using the specified method:</p><ul><li>least_conn: least number of active connections</li><li>least_time=header: least average time to receive the response header (Nginx Plus only)</li><li>least_time=last_byte: least average time to receive the full response (Nginx Plus only)</li></ul><h4>Characteristics</h4><ul><li>Helps evenly distribute load in large server pools, random two balances simplicity with smarter distribution</li><li>Great for A/B testing, canary deployments, or systems with frequently changing server availability</li><li>Sadly, least_time strategies are only available in Nginx Plus 😢</li></ul><h3>6. hash</h3><h4>Same Key, Same Server</h4><p>Uses any specified variable to hash the request and map it to the same server every time. This is similar to ip_hash, but instead of using the IP address, you can specify a custom key — like a cookie value, user ID, or request URI.</p><pre>upstream backend {<br>    hash $arg_user_id consistent;<br>    server service-1:80;<br>    server service-2:80;<br>}</pre><p>In this case, $arg_user_id refers to the query string parameter user_id. For example:</p><pre>GET /profile?user_id=42 # $arg_user_id = 42 (used to hash the request)</pre><p>Also, with the consistent flag, Nginx uses consistent hashing to reduce remapping when backend servers are added or removed.</p><h4>Characteristics</h4><ul><li>Fully customizable stickiness based on any request attribute</li><li>Good for services that use session stickiness based on cookies, user IDs, or tokens</li><li>However, no consideration of server load or performance</li></ul><h3>Conclusion</h3><p>Choosing the right load balancing strategy in Nginx depends on your application’s specific needs — whether it’s performance optimization, session stickiness, simplicity, or dynamic scaling. While least_conn is a solid choice for many use cases, strategies like ip_hash, random, least_time, and hash offer unique strengths that can help you fine-tune your traffic distribution. By understanding how each one works, you can design a more efficient, resilient, and scalable infrastructure.</p><p>Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3377d096b724" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/exploring-different-nginx-load-balancing-strategies-other-than-least-conn-3377d096b724">Exploring different Nginx Load Balancing Strategies (other than least_conn)</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blue-Green Deployment with Jenkins, AWS ECR, and AWS EC2 Using Django]]></title>
            <link>https://blog.devops.dev/blue-green-deployment-with-jenkins-aws-ecr-and-aws-ec2-using-django-05c74887ad4c?source=rss-5629894f74a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/05c74887ad4c</guid>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Jaeyoon Lee]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 13:24:38 GMT</pubDate>
            <atom:updated>2025-03-27T19:25:03.789Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to set up a fully automated <strong>Blue-Green deployment pipeline</strong> for Django using <strong>Jenkins, AWS ECR, and EC2</strong>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrSTomNm360gYhLaNH2QhQ.png" /><figcaption>Image generated using DALL·E</figcaption></figure><p><strong>Blue-Green deployment</strong> is a DevOps strategy that minimizes downtime and risk during software releases. It involves two identical production environments: one active (Blue) and one standby (Green). While users interact with the active environment, you update and test the standby environment. Once it’s verified, you can seamlessly switch traffic to the newly updated environment, thus achieving zero-downtime deployments.</p><p>In this article, we will create a Jenkins pipeline that:</p><ol><li>Builds and pushes a Dockerized Django application to <strong>AWS ECR</strong> (Elastic Container Registry).</li><li>Deploys these Docker images to <strong>AWS EC2</strong> instances.</li><li>Uses a Blue-Green approach to keep downtime minimal.</li></ol><p>By the end, you’ll have a basic CI/CD pipeline and a repeatable method for releasing Django application updates without interrupting your users.</p><h3>1. Prerequisites</h3><h4>1.1 Install Jenkins Plugins</h4><p>Make sure you have the following Jenkins plugins installed beforehand:</p><ul><li><a href="https://plugins.jenkins.io/aws-credentials/">AWS Credentials Plugin</a></li><li><a href="https://plugins.jenkins.io/docker-workflow/">Docker Pipeline</a></li><li><a href="https://plugins.jenkins.io/ssh-agent/">SSH Agent</a></li></ul><h4>1.2 Jenkins Credentials</h4><p>Configure Jenkins Credentials in <strong>Manage Jenkins → Manage Credentials</strong>. Here is an overview:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfc6d117c3064779b253acdc1bc560a/href">https://medium.com/media/1bfc6d117c3064779b253acdc1bc560a/href</a></iframe><p>After you’ve set up the credentials, in your Jenkins Console, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLheNCj2TbL-EYxR9oSMkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSWnkOyHr5GR86GVA5hXuQ.png" /></figure><h4>1.3 Load Balancer</h4><p>This guide assumes a load balancer is already set up, directing traffic to both of your EC2 instances. If you don’t yet have a load balancer, you can still deploy to multiple servers, but you’ll need a different mechanism to switch traffic seamlessly.</p><h3>2. Pipeline Overview</h3><h4>2.1 Create a Jenkinsfile with Defined Deployments</h4><p>First, define your EC2 targets in a list called deployments. Each entry includes:</p><ul><li>title: A descriptive name (used in the pipeline UI).</li><li>name: The Docker container name for running on that server.</li><li>credentialsId: The Jenkins credential ID containing the SSH key.</li><li>host: The public DNS or IP of the EC2 instance.</li><li>user: The SSH username (e.g., ubuntu on Ubuntu).</li><li>port: The external port on the EC2 instance mapped to the Django container’s port (commonly 8000).</li></ul><pre>def deployments = [<br>    [<br>        &quot;title&quot;: &quot;Server 1&quot;,<br>        &quot;name&quot;: &#39;project-server-1&#39;,<br>        &quot;credentialsId&quot;: &#39;project-ec2-ssh&#39;,<br>        &quot;host&quot;: &#39;&lt;ec2 url&gt;&#39;,<br>        &quot;user&quot;: &#39;ubuntu&#39;,<br>        &quot;port&quot;: &#39;8000&#39;<br>    ],<br>    [<br>        &quot;title&quot;: &quot;Server 2&quot;,<br>        &quot;name&quot;: &#39;project-server-2&#39;,<br>        &quot;credentialsId&quot;: &#39;project-ec2-ssh&#39;,<br>        &quot;host&quot;: &#39;&lt;ec2 url&gt;&#39;,<br>        &quot;user&quot;: &#39;ubuntu&#39;,<br>        &quot;port&quot;: &#39;8000&#39;<br>    ]<br>]</pre><h4>2.2 Define a Pipeline with Environment Variables</h4><p>Next, create your pipeline and set environment variables for AWS:</p><pre>def deployments = [<br>  //defined deployments from above<br>]<br><br>pipeline {<br>    agent any<br><br>    environment {<br>        AWS_REGION = &#39;&lt;ap-northeast-2&gt;&#39;<br>        ECR_REGISTRY = &#39;&lt;your ecr registry&gt;&#39;<br>        ECR_REPO = &#39;&lt;ecr repo name&gt;&#39;<br>    }<br><br>   //... add the stages as you continue this guide<br>}</pre><p>Where:</p><ul><li>AWS_REGION: Your AWS region (e.g., ap-northeast-2).</li><li>ECR_REGISTRY: The URI for your ECR registry (e.g., 123456789012.dkr.ecr.ap-northeast-2.amazonaws.com).</li><li>ECR_REPO: The name of your ECR repository (e.g., my-django-app).</li></ul><h4>2.3 Retrieve Git Commit Message</h4><p>In the first stage, get the latest commit message to use as a Docker tag. Docker tags are limited to 128 characters, so you’ll truncate accordingly:</p><pre>stage(&#39;Get Git Commit Message&#39;) {<br>            steps {<br>                script {<br>                    // Get the commit message, sanitize it, and save it as a new environment variable<br>                    COMMIT_MESSAGE = sh(script: &quot;git log -1 --pretty=%B | tr -d &#39;\n&#39; | tr &#39; &#39; &#39;-&#39; | tr -cd &#39;[:alnum:]._-&#39;&quot;, returnStdout: true).trim()<br>                    env.COMMIT_TAG = COMMIT_MESSAGE.take(128) // Docker tags are limited to 128 characters<br>                    echo &quot;${env.COMMIT_TAG}&quot;<br>                }<br>            }<br>        }</pre><h4>2.4 Stage: Load Env file</h4><p>Load your Django (or other application) .env variables from Jenkins Credentials:</p><pre>stage(&#39;Load Env File from Jenkins Credentials&#39;) {<br>            steps {<br>                withCredentials([file(credentialsId: &#39;project-server-env&#39;, variable: &#39;ENV_FILE&#39;)]) {<br>                    // Copy the uploaded .env file to the project<br>                    sh &#39;&#39;&#39;<br>                        if [ -f .env ]; then<br>                            rm .env<br>                        fi<br>                    &#39;&#39;&#39;<br>                    sh &#39;cp $ENV_FILE .env&#39;<br>                }<br>            }<br>        }</pre><ul><li>campable-server-env: The Jenkins “Secret file” credential ID that holds your application’s .env.</li></ul><h4>2.5 Stage: Build Docker Image</h4><p>Build the Docker image for your Django app, then push it to ECR:</p><pre>stage(&#39;Build Docker Image&#39;) {<br>            steps {<br>                 withCredentials([[$class: &#39;AmazonWebServicesCredentialsBinding&#39;, credentialsId: &#39;project-aws-ecr-cred&#39;]]) {<br>                        sh &#39;&#39;&#39;<br>                        aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_REGISTRY}<br>                        &#39;&#39;&#39;<br><br>                        sh &#39;&#39;&#39;<br>                        docker buildx build --platform linux/amd64 -t ${ECR_REPO} .<br>                        docker tag ${ECR_REPO}:latest ${ECR_REGISTRY}/${ECR_REPO}:latest<br>                        docker tag ${ECR_REPO}:latest ${ECR_REGISTRY}/${ECR_REPO}:${COMMIT_TAG}<br>                        &#39;&#39;&#39;<br><br>                        sh &#39;&#39;&#39;<br>                        docker push ${ECR_REGISTRY}/${ECR_REPO}:latest<br>                        docker push ${ECR_REGISTRY}/${ECR_REPO}:${COMMIT_TAG}<br>                        &#39;&#39;&#39;<br>                    }<br>            }<br>        }</pre><h4>2.6 Stage: SSH into EC2</h4><p>Finally, deploy the image to each EC2 instance. For each server in deployments, Jenkins will:</p><ol><li>SSH into the server using the specified credentials.</li><li>Log in to ECR and pull the latest Docker image.</li><li>Tag the pulled image locally.</li><li>Stop and remove any existing container with the same name.</li><li>Run the new container on the desired port.</li><li>Prune old Docker images to save disk space.</li></ol><pre>stage(&#39;SSH into EC2 and Pull Image&#39;) {<br>            steps {<br>                script {<br>                    deployments.each { server -&gt;<br>                        stage(&quot;Deploy to ${server.title}&quot;) {<br>                            withCredentials([[$class: &#39;AmazonWebServicesCredentialsBinding&#39;, credentialsId: &#39;project-aws-ecr-cred&#39;]]) {<br>                                sshagent(credentials: [server.credentialsId]) {<br>                                    sh &quot;&quot;&quot;<br>                                    ssh -o StrictHostKeyChecking=no ${server.user}@${server.host} &quot;<br>                                        aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_REGISTRY}<br>                                        docker pull ${ECR_REGISTRY}/${ECR_REPO}:latest<br>                                        docker tag ${ECR_REGISTRY}/${ECR_REPO}:latest ${server.name}<br>                                        docker stop ${server.name} || true<br>                                        docker rm ${server.name} || true<br>                                        docker run -d -p ${server.port}:8000 --name ${server.name} --network campable-network ${server.name}<br>                                        docker image prune -f<br>                                    &quot;<br>                                    &quot;&quot;&quot;<br>                                }<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }</pre><h4><strong>2.7 Full Pipeline</strong></h4><p>Here’s the complete Jenkinsfile, combining all the stages:</p><pre>def deployments = [<br>    [<br>        &quot;title&quot;: &quot;Server 1&quot;,<br>        &quot;name&quot;: &#39;project-server-1&#39;,<br>        &quot;credentialsId&quot;: &#39;project-ec2-ssh&#39;,<br>        &quot;host&quot;: &#39;&lt;ec2 url&gt;&#39;,<br>        &quot;user&quot;: &#39;ubuntu&#39;,<br>        &quot;port&quot;: &#39;8000&#39;<br>    ],<br>    [<br>        &quot;title&quot;: &quot;Server 2&quot;,<br>        &quot;name&quot;: &#39;project-server-2&#39;,<br>        &quot;credentialsId&quot;: &#39;project-ec2-ssh&#39;,<br>        &quot;host&quot;: &#39;&lt;ec2 url&gt;&#39;,<br>        &quot;user&quot;: &#39;ubuntu&#39;,<br>        &quot;port&quot;: &#39;8000&#39;<br>    ]<br>]                 <br><br>pipeline {<br>  agent any<br><br>    environment {<br>        AWS_REGION = &#39;&lt;ap-northeast-2&gt;&#39;<br>        ECR_REGISTRY = &#39;&lt;your ecr registry&gt;&#39;<br>        ECR_REPO = &#39;&lt;ecr repo name&gt;&#39;<br>    }<br>    <br>    stages {<br><br>        stage(&#39;Get Git Commit Message&#39;) {<br>            steps {<br>                script {<br>                    // Get the commit message, sanitize it, and save it as a new environment variable<br>                    COMMIT_MESSAGE = sh(script: &quot;git log -1 --pretty=%B | tr -d &#39;\n&#39; | tr &#39; &#39; &#39;-&#39; | tr -cd &#39;[:alnum:]._-&#39;&quot;, returnStdout: true).trim()<br>                    env.COMMIT_TAG = COMMIT_MESSAGE.take(128) // Docker tags are limited to 128 characters<br>                    echo &quot;${env.COMMIT_TAG}&quot;<br>                }<br>            }<br>        }<br><br>        stage(&#39;Load Env File from Jenkins Credentials&#39;) {<br>            steps {<br>                withCredentials([file(credentialsId: &#39;project-server-env&#39;, variable: &#39;ENV_FILE&#39;)]) {<br>                    // Copy the uploaded .env file to the project<br>                    sh &#39;&#39;&#39;<br>                        if [ -f .env ]; then<br>                            rm .env<br>                        fi<br>                    &#39;&#39;&#39;<br>                    sh &#39;cp $ENV_FILE .env&#39;<br>                }<br>            }<br>        }<br><br>        stage(&#39;Build Docker Image&#39;) {<br>            steps {<br>                 withCredentials([[$class: &#39;AmazonWebServicesCredentialsBinding&#39;, credentialsId: &#39;project-aws-ecr-cred&#39;]]) {<br>                        sh &#39;&#39;&#39;<br>                        aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_REGISTRY}<br>                        &#39;&#39;&#39;<br><br>                        sh &#39;&#39;&#39;<br>                        docker buildx build --platform linux/amd64 -t ${ECR_REPO} .<br>                        docker tag ${ECR_REPO}:latest ${ECR_REGISTRY}/${ECR_REPO}:latest<br>                        docker tag ${ECR_REPO}:latest ${ECR_REGISTRY}/${ECR_REPO}:${COMMIT_TAG}<br>                        &#39;&#39;&#39;<br><br>                        sh &#39;&#39;&#39;<br>                        docker push ${ECR_REGISTRY}/${ECR_REPO}:latest<br>                        docker push ${ECR_REGISTRY}/${ECR_REPO}:${COMMIT_TAG}<br>                        &#39;&#39;&#39;<br>                    }<br>            }<br>        }<br>        <br>        stage(&#39;SSH into EC2 and Pull Image&#39;) {<br>            steps {<br>                script {<br>                    deployments.each { server -&gt;<br>                        stage(&quot;Deploy to ${server.title}&quot;) {<br>                            withCredentials([[$class: &#39;AmazonWebServicesCredentialsBinding&#39;, credentialsId: &#39;project-aws-ecr-cred&#39;]]) {<br>                                sshagent(credentials: [server.credentialsId]) {<br>                                    sh &quot;&quot;&quot;<br>                                    ssh -o StrictHostKeyChecking=no ${server.user}@${server.host} &quot;<br>                                        aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_REGISTRY}<br>                                        docker pull ${ECR_REGISTRY}/${ECR_REPO}:latest<br>                                        docker tag ${ECR_REGISTRY}/${ECR_REPO}:latest ${server.name}<br>                                        docker stop ${server.name} || true<br>                                        docker rm ${server.name} || true<br>                                        docker run -d -p ${server.port}:8000 --name ${server.name} --network campable-network ${server.name}<br>                                        docker image prune -f<br>                                    &quot;<br>                                    &quot;&quot;&quot;<br>                                }<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>3. Testing</h3><h4>3.1 Testing Blue-Green Deployment</h4><p>To confirm there’s <strong>no downtime</strong> during deployment, create a script that sends requests to your application endpoint every second. If your setup is correct, you’ll see continuous HTTP 200 (or your success code) responses throughout the update.</p><p>Create a monitor_deployment.sh script:</p><pre>nano monitor_deployment.sh</pre><p>Paste in the following (update TARGET_URL to your own health-check or application endpoint):</p><pre>#!/usr/bin/env bash<br><br># Paste in your Target URL for health checks<br>TARGET_URL=&quot;https://your-api-endpoint.com/health&quot;<br><br>SLEEP_INTERVAL=1<br><br>echo &quot;Starting deployment monitor...&quot;<br>echo &quot;Sending requests to: $TARGET_URL&quot;<br>echo &quot;Interval: $SLEEP_INTERVAL second(s)&quot;<br>echo &quot;Press Ctrl + C to stop.&quot;<br><br>while true; do<br>  TIMESTAMP=$(date +&quot;%Y-%m-%d %T&quot;)<br><br>  HTTP_CODE=$(curl -s -o /dev/null -w &quot;%{http_code}&quot; &quot;$TARGET_URL&quot;)<br><br>  echo &quot;[${TIMESTAMP}] - HTTP ${HTTP_CODE}&quot;<br><br>  sleep $SLEEP_INTERVAL<br>done</pre><p>Make the script executable:</p><pre>chmod +x monitor_deployment.sh</pre><p>Run the script:</p><pre>./monitor_deployment.sh</pre><p>You should see something like this:</p><pre>Starting deployment monitor...<br>Sending requests to: https://your-api-endpoint.com/health<br>Interval: 1 second(s)<br>Press Ctrl + C to stop.<br>[2025-03-10 10:15:01] - HTTP 200<br>[2025-03-10 10:15:02] - HTTP 200<br>[2025-03-10 10:15:03] - HTTP 200<br>...</pre><h4>3.2 Deploy a new update</h4><p>With the monitoring script running, push a new update (e.g., run your Jenkins pipeline again).</p><p>If your Blue-Green deployment is configured correctly, you should see <strong>no downtime</strong> in your monitoring script logs (i.e., continuous 200 responses or whichever success code you expect).</p><h4>3.3 Verify Docker Containers</h4><p>After the pipeline completes, SSH into each EC2 instance and confirm the new containers are running:</p><pre>sudo docker ps</pre><p>A successful run might look like this:</p><p><strong>Server 1</strong></p><pre>//server 1<br><br>CONTAINER ID   IMAGE              COMMAND                  CREATED      STATUS      PORTS                                           NAMES<br>7b7s2v42ab3e   project-server-1   &quot;gunicorn --bind 0.0…&quot;   1 min ago    Up 1 min    0.0.0.0:8000-&gt;8000/tcp, :::8000-&gt;8000/tcp       project-server-1</pre><p><strong>Server 2</strong></p><pre>//server 2<br><br>CONTAINER ID   IMAGE              COMMAND                  CREATED      STATUS      PORTS                                           NAMES<br>7b5f6e12ab3e   project-server-2   &quot;gunicorn --bind 0.0…&quot;   1 min ago    Up 1 min    0.0.0.0:8000-&gt;8000/tcp, :::8000-&gt;8000/tcp       project-server-2</pre><p>If both containers are listed, and your monitoring script showed no failed requests, you’ve successfully performed a Blue-Green deployment with zero downtime!</p><h3>Conclusion</h3><p>By following the steps in this guide, you have successfully created a <strong>Blue-Green deployment</strong> pipeline using <strong>Jenkins</strong>, <strong>Docker</strong>, <strong>AWS ECR</strong>, and <strong>EC2</strong>. Specifically, you:</p><ol><li><strong>Defined Jenkins Environments</strong> to maintain consistent AWS configuration (region, ECR registry, and repository).</li><li><strong>Retrieved Git Commit Messages</strong> to generate meaningful Docker tags.</li><li><strong>Loaded Environment Variables (.env)</strong> from Jenkins Credentials for application-specific secrets.</li><li><strong>Built and Pushed Docker Images</strong> to ECR, leveraging AWS credentials for secure access.</li><li><strong>Deployed to EC2 Instances</strong> by pulling the newest image, stopping/removing old containers, and running the updated containers.</li><li><strong>Verified Zero Downtime</strong> by continuously monitoring your application endpoint with a simple Bash script.</li></ol><p>With this pipeline, you can confidently deploy new versions of your Django application without interrupting user traffic. Feel free to expand on these steps — by adding automated tests, integrating load balancer logic, or enhancing your monitoring approach — to tailor the solution to your specific production requirements.</p><p>Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05c74887ad4c" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/blue-green-deployment-with-jenkins-aws-ecr-and-aws-ec2-using-django-05c74887ad4c">Blue-Green Deployment with Jenkins, AWS ECR, and AWS EC2 Using Django</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>