<?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 Dasun Wickramasooriya on Medium]]></title>
        <description><![CDATA[Stories by Dasun Wickramasooriya on Medium]]></description>
        <link>https://medium.com/@iamdasun?source=rss-8b1178b12209------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*boJ8-Uuzt1jB6yox4-mOcQ.png</url>
            <title>Stories by Dasun Wickramasooriya on Medium</title>
            <link>https://medium.com/@iamdasun?source=rss-8b1178b12209------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:37:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamdasun/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[Dockerizing a Node.js Express App with a MySQL Database: A Complete Guide with Best Practices]]></title>
            <link>https://iamdasun.medium.com/dockerizing-a-node-js-express-app-with-a-mysql-database-a-complete-guide-with-best-practices-8c79004131df?source=rss-8b1178b12209------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c79004131df</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dockerize-nodejs-app]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Dasun Wickramasooriya]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 06:52:05 GMT</pubDate>
            <atom:updated>2025-09-03T09:26:00.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-2uKg4OUcAXY3Xnc3Hb_g.jpeg" /></figure><h3>Introduction</h3><p>Docker makes it easy to package and run applications in isolated environments called containers. This guide will help you Dockerize a simple Node.js Express server step by step, explaining the important concepts along the way.</p><h3>Why Use Docker?</h3><p>Software often works differently on different computers due to variations in dependencies and system configurations. Docker solves this problem by creating a <strong>consistent environment</strong> for applications. It does this through:</p><ul><li><strong>Dockerfile</strong>: Defines the environment setup.</li><li><strong>Docker Image</strong>: A snapshot of the environment.</li><li><strong>Docker Container</strong>: A running instance of the image.</li></ul><p>This ensures that the application runs the same way on every machine.</p><h3>Cloning the Repository</h3><p>Start by cloning the sample project:</p><pre>git clone https://github.com/dasunhq/dockerize-node-app.git<br>cd dockerize-node-app</pre><p>This repository has two branches:</p><ul><li>without-docker: The base Node.js application.</li><li>dockerized: The Dockerized version.</li></ul><p>Switch to the base branch:</p><pre>git checkout without-docker</pre><h3>Installing Docker</h3><ol><li><strong>Windows/Mac</strong>: Install <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a>.</li><li><strong>Linux:</strong> Install <a href="https://docs.docker.com/engine/install/">Docker Engine</a>.</li><li>Verify the installation:</li></ol><pre>docker --version</pre><p>Check running containers:</p><pre>docker ps</pre><p>Should get an output similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOi8tsec6gCancSU790w4Q.png" /></figure><h3>Understanding Host vs. Container</h3><ul><li><strong>Host</strong>: Your computer where Docker is installed.</li><li><strong>Container</strong>: An isolated environment running your application.</li></ul><h3>Understanding Docker Layers</h3><p>Each step in a Dockerfile creates a <strong>layer</strong>. If a layer remains unchanged, Docker uses the cached version to speed up builds. This helps avoid redundant installations and improves efficiency.</p><h3>Writing the Simple Node.js Express Server</h3><p>index.js:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello, Docker!&#39;);<br>});<br><br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><h3>Writing the Dockerfile</h3><p>Switch to the dockerized branch and check Dockerfile:</p><pre>FROM node:22-alpine3.21<br><br>WORKDIR /app<br><br>COPY package.json ./<br><br>RUN npm install<br><br>COPY . .<br><br>ENV PORT=3000<br><br>EXPOSE 3000<br><br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><h3>Why Each Instruction?</h3><h4><strong>FROM node:22-alpine3.21</strong></h4><ul><li>This selects the base image for our container. node:22-alpine3.21 is a lightweight version of Node.js built on Alpine Linux, which significantly reduces image size and improves efficiency.</li></ul><h4>WORKDIR /app</h4><ul><li>Sets the working directory inside the container. All subsequent commands will be run from this directory. This ensures that file paths are relative to /app, keeping things organized.</li></ul><h4>COPY package.json ./</h4><ul><li>Copies only package.json first before copying the entire source code. This is done to optimize <strong>Docker&#39;s caching mechanism</strong>. Since dependencies don’t change often, Docker can cache this layer and reuse it in future builds, avoiding unnecessary reinstallation of dependencies if only the source code changes.</li></ul><h4>RUN npm install</h4><ul><li>Installs all required dependencies listed in package.json. Since we copied only package.json earlier, this step benefits from caching—dependencies are installed once and won&#39;t be reinstalled unless package.json changes. This speeds up builds significantly.</li></ul><h4>COPY . .</h4><ul><li>Copies all application files from the local machine to the container. This includes the source code, configuration files, and other necessary assets.</li></ul><h4>ENV PORT=3000</h4><ul><li>Defines an <strong>environment variable</strong> inside the container. This makes it easy to change the port without modifying the source code. If needed, we can override this when running the container.</li></ul><h4>EXPOSE 3000</h4><ul><li>Informs Docker that the application inside the container listens on port 3000. This does <strong>not</strong> publish the port to the host machine but serves as metadata for documentation and linking purposes.</li></ul><h4>CMD [&quot;npm&quot;, &quot;start&quot;]</h4><ul><li>Specifies the command to run when the container starts. Here, npm start will launch our Node.js server. Unlike RUN, which executes at build time, CMD executes at runtime when the container starts.</li></ul><h3>Building the Docker Image</h3><p>Run:</p><pre>docker build -t dasunwickr/dockerized-node-app:1.0 .</pre><h4>Explanation:</h4><ul><li>docker build: Builds an image.</li><li>t dasunwickr/dockerized-node-app:1.0: Tags the image with a name and version.</li><li>.: Uses the current directory as the context.</li></ul><h3>Running the Docker Container</h3><p>Run the container:</p><pre>docker run -p 8080:3000 dasunwickr/dockerized-node-app:1.0</pre><h4>Explanation:</h4><ul><li>docker run: Creates and starts a container.</li><li>p 8080:3000: Maps <strong>host port 8080</strong> to <strong>container port 3000</strong>.</li></ul><p>Access the app at: <a href="http://localhost:8080/">http://localhost:8080</a></p><h3>Docker Compose</h3><p>For multi-container setups, we use Docker Compose.</p><h4>Setting Up Docker Compose</h4><p>Docker Compose allows us to define and manage multi-container applications using a simple YAML file.</p><h4>Example compose.yml:</h4><pre>services:<br>  app:<br>    container_name: my_custom_app<br>    build: .<br>    ports:<br>      - &quot;8080:3000&quot;<br>    depends_on:<br>      - db<br>  db:<br>    container_name: my_custom_db<br>    image: mysql:latest<br>    restart: always<br>    environment:<br>      MYSQL_ROOT_PASSWORD: root<br>      MYSQL_DATABASE: testdb</pre><h4>Explanation of compose.yml</h4><ul><li>services: Defines different containers.</li></ul><p><strong>app:</strong></p><ul><li>container_name: my_custom_app: Assigns a custom name to the container.</li><li>build: .: Builds the app using the Dockerfile in the current directory.</li><li>ports: Maps port 8080 on the host to 3000 inside the container.</li><li>depends_on: Ensures the database container starts before the app.</li></ul><p><strong>db:</strong></p><ul><li>container_name: my_custom_db: Assigns a custom name to the database container.</li><li>image: mysql:latest: Uses the latest MySQL image.</li><li>restart: always: Ensures the container restarts if it stops.</li><li>environment: Defines environment variables for MySQL setup.</li></ul><h3>Running with Docker Compose</h3><pre>docker compose up -d</pre><h3>Explanation:</h3><ul><li>docker compose up: Starts all services defined in the compose.yml file.</li><li>d: Runs the containers in detached mode (background).</li></ul><p>To stop the containers:</p><pre>docker compose down</pre><h3>Conclusion</h3><p>You&#39;ve successfully Dockerized a Node.js Express app! Experiment with modifying the ports and adding more services to deepen your understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c79004131df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a Raspberry Pi Headless Using Raspberry Pi Imager (No Monitor, Keyboard, or Mouse)]]></title>
            <link>https://iamdasun.medium.com/setting-up-a-raspberry-pi-headless-using-raspberry-pi-imager-no-monitor-keyboard-or-mouse-8b0d4c8523f6?source=rss-8b1178b12209------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b0d4c8523f6</guid>
            <category><![CDATA[raspberry-pi-imager]]></category>
            <category><![CDATA[headless-raspberry-pi]]></category>
            <category><![CDATA[ssh-raspberry-pi]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[raspberry-pi-os]]></category>
            <dc:creator><![CDATA[Dasun Wickramasooriya]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 02:25:44 GMT</pubDate>
            <atom:updated>2024-09-17T04:14:52.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*wTLpMx5SOPgZSCbLHg6w9A.png" /></figure><p>Setting up a Raspberry Pi headlessly is an ideal approach if you don’t have access to a spare monitor, keyboard, or mouse, or simply want a more streamlined process. With a few quick steps, you can have your Raspberry Pi up and running, controlled entirely from your laptop or desktop. This guide will walk you through the process of setting up your Raspberry Pi without needing external peripherals.</p><h3>Prerequisites:</h3><ul><li>Raspberry Pi (any model)</li><li>MicroSD card (at least 8GB)</li><li>Laptop or desktop computer</li><li>MicroSD card reader</li><li>Wi-Fi or Ethernet connection</li><li>Power adapter for Raspberry Pi</li></ul><h3>Step 1: Install Bonjour Services (for Windows Users)</h3><p>If you’re on <strong>Windows</strong>, you’ll need to install <strong>Bonjour services</strong> to connect to your Raspberry Pi by hostname (e.g., pi.local). This step is unnecessary for macOS and Linux users, as these operating systems support the mDNS protocol natively.</p><ol><li><strong>Download Bonjour</strong>: If <strong>Bonjour</strong> isn’t already installed, download it from <a href="https://support.apple.com/kb/DL999?locale=en_US">Apple’s website</a>.</li><li><strong>Install Bonjour</strong>: Follow the steps to install it on your system, enabling network discovery for your Raspberry Pi.</li></ol><p><strong>Alternative for macOS and Linux Users</strong></p><p>For <strong>macOS</strong> and <strong>Linux</strong> users, you can use the Pi’s hostname (pi.local) out of the box since <strong>mDNS</strong> is already supported. No additional software is required.</p><p>If you’d prefer not to use pi.local, you can find the IP address using:</p><ul><li><strong>Router’s device list</strong>: Check your router for connected devices.</li><li><strong>Terminal commands</strong>: Use network scanning tools like nmap (Linux) or <strong>ping</strong> (macOS) to find the Raspberry Pi on your network.</li></ul><h3>Step 2: Download and Install Raspberry Pi OS</h3><p>To install the operating system on your Raspberry Pi:</p><ol><li><strong>Download Raspberry Pi Imager</strong>: Visit the <a href="https://www.raspberrypi.com/software/">Raspberry Pi website</a> and download Raspberry Pi Imager for your operating system (Windows, macOS, or Linux).</li><li><strong>Insert the microSD card</strong> into your computer using a card reader.</li><li><strong>Open Raspberry Pi Imager</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*fGAA9UD2At6Aip26DnkjOg.png" /><figcaption>Raspberry Pi Imager</figcaption></figure><ul><li>Under <strong>Raspberry Pi Devices, </strong>select the device that you have. For this demonstration Raspberry Pi Zero W, is used.</li><li>Under <strong>Operating System</strong>, select Raspberry Pi OS Lite (32-bit). The Lite OS — Debian with security updates no desktop environment. A desktop environment won’t be needed since we will remote desktop into the device using SSH.</li><li>Under <strong>Storage</strong>, choose your microSD card.</li><li>Click <strong>Next </strong>to proceed further.</li></ul><p>4. <strong>Using OS customization (Optional but RECOMMENDED)</strong></p><p>These steps are optional and can be manually set up once the OS is flashed to the microSD card. But using these configuration settings is easier compared to manually setting up the configurations.</p><p><strong>General Settings</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*kPdB3gKPZ24hWoBWCppzjQ.png" /></figure><ul><li>A <strong>hostname</strong> is a unique name assigned to a device on a network that helps identify and differentiate it from other devices, allowing users to connect to it using a readable name instead of an IP address. You can set a hostname by ticking the checkbox <strong><em>Set hostname </em></strong>and inserting a name.</li><li>You can configure user credentials to your Raspberry Pi by ticking the checkbox <strong><em>Set username and password</em></strong>.</li><li>Check on <strong><em>Configure wireless LAN</em></strong> and insert the SSD (Name of you Wi-fi Router) and the Password.</li></ul><p><strong>Services</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*AzNZzYcd3r3Qr1TOR5TMNw.png" /></figure><ul><li><strong><em>Check on Enable SSH</em></strong> and select the <strong><em>Use password authentication </em></strong>option. This will enable option for you to remote desktop into you Raspberry Pi.</li></ul><p><strong>5. Applying OS Customization and Writing the OS to the microSD</strong></p><p>Click on Save and click on YES to apply the OS customizations. This will start writing the OS to the microSD card.</p><h3>Step 3: Enable SSH and Configure Wi-Fi (For those who skipped the OS Customization step)</h3><p>Since this is a headless setup, you need to enable SSH for remote access and configure Wi-Fi (optional).</p><ol><li><strong>Eject and reinsert the SD Card</strong>: After writing the OS, eject and reinsert the SD card.</li><li><strong>Enable SSH</strong>: In the boot partition of the SD card, create an empty file named ssh (without any extension). This enables SSH on the first boot.</li><li><strong>Set Up Wi-Fi</strong> (Optional):</li></ol><ul><li>Create a file named wpa_supplicant.conf in the same partition, and paste the following content:</li></ul><pre>country=US<br>ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev<br>update_config=1<br>network={<br>    ssid=&quot;your_network_name&quot;<br>    psk=&quot;your_network_password&quot;<br>}</pre><ul><li>Replace the placeholders with your network details and save the file.</li></ul><h3>Step 4: Boot the Raspberry Pi</h3><p>Insert the microSD card into your Raspberry Pi and connect the power supply. If Wi-Fi is configured correctly, the Raspberry Pi will connect to your network, or you can connect it via Ethernet.</p><h3>Step 5: Find the Raspberry Pi’s IP Address</h3><p><strong>Windows users</strong> can connect using pi.local if bonjour is installed. <strong>macOS</strong> and <strong>Linux users</strong> can use the same pi.local without any additional software.</p><p>Alternatively, you can find the Raspberry Pi’s IP address by:</p><ul><li>Checking your router’s connected devices list.</li><li>Using network scanners like <strong>Fing</strong> or <strong>Angry IP Scanner</strong>.</li><li>By pinging the hostname. The IP address of the Raspberry Pi in the following example is <strong><em>192.168.8.191</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*reyQviQMftteEaF_xm_83Q.png" /></figure><h3>Step 6: SSH Into the Raspberry Pi</h3><p>Once you’ve located the IP address (or if you’re using pi.local), you can SSH into your Raspberry Pi:</p><ol><li>For macOS, Linux and Windows with Bonjour Services installed:</li></ol><pre>ssh pi@pi.local</pre><p>or</p><pre>ssh pi@&lt;IP_ADDRESS&gt;</pre><p>2. <strong>For Windows</strong>: Open Command Prompt or use an SSH client like <strong>PuTTY</strong>, then enter the IP address or pi.local. Use the username and password that you setup in the OS customization. For those who didn’t use the customization option, the default username is pi, and the password is raspberry and the hostname is raspberrypi.local</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*LMdDAhwOYZyxiq78kU-YOA.png" /></figure><ul><li>In Linux based terminals, you cannot see the password being typed. Just type your password and then press Enter.</li></ul><p>3. Enjoy using your Raspberry Pi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*ZeRspT8MQnOT8YCly9aa5w.png" /></figure><h3>Common Issues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*SpUV2FnySQ4kr64s-rvQyA.png" /></figure><p>When you connect your Raspberry Pi to a power source, it takes a few seconds to minutes to boot up. If you try to SSH in as soon as you connect the Raspberry Pi to power, the error shown above will pop up. Therefore, wait for a little time and try again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0d4c8523f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Cheat Sheet for Docker: Essential Commands and Concepts]]></title>
            <link>https://iamdasun.medium.com/a-cheat-sheet-for-docker-essential-commands-and-concepts-d2c4f7614118?source=rss-8b1178b12209------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2c4f7614118</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Dasun Wickramasooriya]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 12:41:34 GMT</pubDate>
            <atom:updated>2024-08-13T12:41:34.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cheat Sheet for Docker: Essential Commands and Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nzVDh73Tj6sl04qGjf1Fw.png" /></figure><p>Docker is a powerful tool that simplifies the process of building, deploying, and managing applications in a consistent and efficient manner. It uses containerization to package applications with all their dependencies, allowing them to run seamlessly across different environments. This cheat sheet provides a quick reference to essential Docker commands and concepts for developers at any level.</p><h4>1. Docker Basics</h4><ul><li><strong>Install Docker:</strong><br>Follow the official <a href="https://docs.docker.com/get-docker/">installation guide</a> for your operating system.</li><li><strong>Docker Version:</strong></li></ul><pre>docker --version</pre><ul><li><strong>Docker Info:</strong><br>Displays system-wide information about Docker.</li></ul><pre>docker info</pre><h4>2. Docker Images</h4><ul><li><strong>List Images:</strong></li></ul><pre>docker images</pre><ul><li><strong>Pull Image:</strong><br>Fetches an image from a Docker registry (e.g., Docker Hub).</li></ul><pre>docker pull [image:tag]</pre><ul><li><strong>Build Image:</strong><br>Creates a new image from a Dockerfile.</li></ul><pre>docker build -t [image:tag] [path]</pre><ul><li><strong>Remove Image:</strong><br>Deletes an image from your local storage.</li></ul><pre>docker rmi [image:tag]</pre><ul><li><strong>Tag Image:</strong><br>Tags an image with a new name.</li></ul><pre>docker tag [source-image:tag] [target-image:tag]</pre><h4>3. Docker Containers</h4><ul><li><strong>List Containers:</strong><br>Lists running containers.</li></ul><pre>docker ps</pre><ul><li><strong>List All Containers:</strong><br>Lists all containers, including stopped ones.</li></ul><pre>docker ps -a</pre><ul><li><strong>Run Container:</strong><br>Creates and starts a new container from an image.</li></ul><pre>docker run [options] [image:tag] [command]</pre><ul><li><strong>Stop Container:</strong><br>Stops a running container.</li></ul><pre>docker stop [container-id]</pre><ul><li><strong>Remove Container:</strong><br>Deletes a container.</li></ul><pre>docker rm [container-id]</pre><ul><li><strong>Exec into Container:</strong><br>Executes a command inside a running container.</li></ul><pre>docker exec -it [container-id] [command]</pre><ul><li><strong>Logs:</strong><br>Displays logs from a container.</li></ul><pre>docker logs [container-id]</pre><h4>4. Docker Volumes</h4><ul><li><strong>List Volumes:</strong><br>Shows all Docker volumes.</li></ul><pre>docker volume ls</pre><ul><li><strong>Create Volume:</strong><br>Creates a new Docker volume.</li></ul><pre>docker volume create [volume-name]</pre><ul><li><strong>Remove Volume:</strong><br>Deletes a volume.</li></ul><pre>docker volume rm [volume-name]</pre><ul><li><strong>Inspect Volume:</strong><br>Provides detailed information about a volume.</li></ul><pre>docker volume inspect [volume-name]</pre><h4>5. Docker Networks</h4><ul><li><strong>List Networks:</strong><br>Displays all Docker networks.</li></ul><pre>docker network ls</pre><ul><li><strong>Create Network:</strong><br>Creates a new Docker network.</li></ul><pre>docker network create [network-name]</pre><ul><li><strong>Remove Network:</strong><br>Deletes a network.</li></ul><pre>docker network rm [network-name]</pre><ul><li><strong>Inspect Network:</strong><br>Provides detailed information about a network.</li></ul><pre>docker network inspect [network-name]</pre><h4>6. Docker Compose</h4><ul><li><strong>Install Docker Compose:</strong><br>Follow the <a href="https://docs.docker.com/compose/install/">installation guide</a> for Docker Compose.</li><li><strong>Start Services:</strong><br>Starts services defined in a docker-compose.yml file.</li></ul><pre>docker-compose up</pre><ul><li><strong>Stop Services:</strong><br>Stops services defined in a docker-compose.yml file.</li></ul><pre>docker-compose down</pre><ul><li><strong>Build Services:</strong><br>Builds or rebuilds services.</li></ul><pre>docker-compose build</pre><ul><li><strong>View Logs:</strong><br>Shows logs from services.</li></ul><pre>docker-compose logs</pre><h4>7. Dockerfile Basics</h4><ul><li><strong>FROM:</strong><br>Specifies the base image.</li></ul><pre>FROM [image:tag]</pre><ul><li><strong>RUN:</strong><br>Executes commands in the container.</li></ul><pre>RUN [command]</pre><ul><li><strong>COPY:</strong><br>Copies files from the host into the container.</li></ul><pre>COPY [source] [destination]</pre><ul><li><strong>CMD:</strong><br>Provides default commands to run when the container starts.</li></ul><pre>CMD [&quot;command&quot;]</pre><ul><li><strong>EXPOSE:</strong><br>Informs Docker that the container listens on the specified network ports.</li></ul><pre>EXPOSE [port]</pre><ul><li><strong>ENV:</strong><br>Sets environment variables.</li></ul><pre>ENV [key]=[value]</pre><ul><li><strong>VOLUME:</strong><br>Creates a mount point with the specified path.</li></ul><pre>VOLUME [&quot;/path&quot;]</pre><h4>8. Docker Registries</h4><ul><li><strong>Log in to Docker Hub:</strong></li></ul><pre>docker login</pre><ul><li><strong>Push Image:</strong><br>Uploads an image to a Docker registry.</li></ul><pre>docker push [image:tag]</pre><ul><li><strong>Pull Image:</strong><br>Downloads an image from a Docker registry.</li></ul><pre>docker pull [image:tag]</pre><p>This cheat sheet provides a snapshot of key Docker commands and concepts to help you get started and efficiently manage your Docker environments. For more detailed information and advanced usage, refer to the <a href="https://docs.docker.com/">official Docker documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2c4f7614118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dependency Injection with Java Spring Boot]]></title>
            <link>https://iamdasun.medium.com/understanding-dependency-injection-with-java-spring-boot-611b716c0d18?source=rss-8b1178b12209------2</link>
            <guid isPermaLink="false">https://medium.com/p/611b716c0d18</guid>
            <category><![CDATA[field-injection]]></category>
            <category><![CDATA[setter-injection]]></category>
            <category><![CDATA[constructor-injection]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Dasun Wickramasooriya]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 01:32:15 GMT</pubDate>
            <atom:updated>2024-08-13T01:32:15.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8E8zjnPvK4iO-GH9yrzgA.png" /></figure><p>Dependency Injection (DI) is a design pattern that improves modularity and testability in software applications by injecting dependencies from the outside rather than creating them internally. In Java, Spring Boot provides an efficient way to manage DI through annotations and configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKYkjBWrqhBRX-lWMrAP8Q.png" /><figcaption>Fig 1.1. Dependency Injection explained in a diagram</figcaption></figure><h4>Types of Dependency Injection in Spring Boot</h4><ol><li><strong>Constructor Injection</strong></li><li><strong>Setter Injection</strong></li><li><strong>Field Injection</strong></li></ol><p>Below, we’ll explore examples of each type of Dependency Injection in a Spring Boot application.</p><h4>1. Constructor Injection</h4><p>Constructor Injection is the most recommended form of DI. Dependencies are provided through the class constructor, ensuring that all required dependencies are available when the object is created.</p><p><strong>Example:</strong></p><p><strong>Repository Interface</strong></p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>}</pre><p><strong>Service Class</strong></p><pre>@Service<br>public class UserService {<br>  private final UserRepository userRepository;<br><br>  @Autowired<br>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br>  public User findUserById(Long id) {<br>        return userRepository.findById(id).orElse(null);<br>    }<br>}</pre><p><strong>Controller Class</strong></p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br>  <br>  private final UserService userService;<br>  <br>  @Autowired<br>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>  @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;User&gt; getUserById(@PathVariable Long id) {<br>        User user = userService.findUserById(id);<br>        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();<br>    }<br>}</pre><p>In this example, UserService and UserController receive their dependencies via constructor parameters, ensuring immutability and mandatory dependencies.</p><h4>2. Setter Injection</h4><p>Setter Injection involves injecting dependencies via setter methods. This approach allows for more flexibility, but can lead to objects being in an incomplete state if all setters are not called.</p><p><strong>Example:</strong></p><p><strong>Repository Interface</strong></p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>}</pre><p><strong>Service Class</strong></p><pre>@Service<br>public class UserService {<br>  private UserRepository userRepository;<br>  <br>@Autowired<br>  public void setUserRepository(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }<br><br>  public User findUserById(Long id) {<br>        return userRepository.findById(id).orElse(null);<br>    }<br>}</pre><p><strong>Controller Class</strong></p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br><br>  private UserService userService;<br><br>  @Autowired<br>    public void setUserService(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>  @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;User&gt; getUserById(@PathVariable Long id) {<br>        User user = userService.findUserById(id);<br>        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();<br>    }<br>}</pre><p>Here, dependencies are injected using setter methods. This allows for optional dependencies but may lead to incomplete object states if not all setters are invoked.</p><h4>3. Field Injection</h4><p>Field Injection involves injecting dependencies directly into fields using the @Autowired annotation. This approach is simple but less preferred due to its potential impact on testability and code clarity.</p><p><strong>Example:</strong></p><p><strong>Repository Interface</strong></p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>}</pre><p><strong>Service Class</strong></p><pre>@Service<br>public class UserService {<br><br>  @Autowired<br>  private UserRepository userRepository;<br><br>  public User findUserById(Long id) {<br>        return userRepository.findById(id).orElse(null);<br>    }<br>}</pre><p><strong>Controller Class</strong></p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br><br>  @Autowired<br>  private UserService userService;<br><br>  @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;User&gt; getUserById(@PathVariable Long id) {<br>        User user = userService.findUserById(id);<br>        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();<br>    }<br>}</pre><p>In this example, dependencies are injected directly into fields. While convenient, it can make the code less maintainable and harder to test.</p><h4>Conclusion</h4><p>Dependency Injection in Spring Boot provides several methods to manage dependencies, each with its advantages and drawbacks. Constructor Injection is generally recommended for its benefits in maintaining immutability and ensuring mandatory dependencies. Setter Injection offers flexibility, while Field Injection, though convenient, is typically avoided in favor of the other methods.</p><h3>References</h3><p>[1] P. Johnson and B. Beck, <em>“Spring in Action,”</em> 5th ed., Manning Publications, 2021.</p><p>[2] J. Bloch, <em>“Effective Java,”</em> 3rd ed., Addison-Wesley, 2018.</p><p>[3] G. L. Jones, <em>“Spring Boot: Up and Running,”</em> O’Reilly Media, 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=611b716c0d18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the SOLID Principles: A Guide to Better Software Design]]></title>
            <link>https://iamdasun.medium.com/understanding-the-solid-principles-a-guide-to-better-software-design-c8d528486998?source=rss-8b1178b12209------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d528486998</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[solid-principles-in-java]]></category>
            <dc:creator><![CDATA[Dasun Wickramasooriya]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 07:53:15 GMT</pubDate>
            <atom:updated>2024-08-13T01:49:09.525Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving world of software development, adhering to sound design principles is crucial for creating systems that are scalable, maintainable, and efficient. One of the most widely recognized frameworks for good design is the SOLID principles. SOLID is an acronym representing five core principles of object-oriented design: <strong>Single Responsibility Principle (SRP)</strong>, <strong>Open/Closed Principle (OCP)</strong>, <strong>Liskov Substitution Principle (LSP)</strong>, <strong>Interface Segregation Principle (ISP)</strong>, and <strong>Dependency Inversion Principle (DIP)</strong>. In this post, we’ll explore each of these principles with practical examples to help you improve your software design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*jPROahDWDQ2fWnKixUZhAw.png" /><figcaption>Fig. 1. SOLID Principles</figcaption></figure><h4>1. Single Responsibility Principle (SRP)</h4><p><strong>Definition:</strong> A class should have only one reason to change, meaning it should have only one responsibility.</p><p><strong>Example:</strong></p><p>Imagine you have a UserManager class that handles both user data and authentication:</p><pre>public class UserManager {<br>    public void addUser(User user) {<br>        // Code to add user to database<br>    }<br><br>  public void authenticate(User user, String password) {<br>        // Code to authenticate user<br>    }<br>}</pre><p>Here, UserManager has two responsibilities. To adhere to SRP, you should split it into separate classes:</p><pre>public class UserRepository {<br>    public void addUser(User user) {<br>        // Code to add user to database<br>    }<br>}<br><br>public class Authenticator {<br>    public void authenticate(User user, String password) {<br>        // Code to authenticate user<br>    }<br>}</pre><p>By doing this, UserRepository manages user data, while Authenticator handles authentication, each focusing on a single responsibility.</p><p><strong>Reference:</strong><br>Martin, R. C. <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>. Prentice Hall, 2008.</p><h4>2. Open/Closed Principle (OCP)</h4><p><strong>Definition:</strong> Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.</p><p><strong>Example:</strong></p><p>Consider a DiscountCalculator class that calculates discounts based on order types:</p><pre>public class DiscountCalculator {<br>    public double calculateDiscount(Order order) {<br>        if (order.getType() == OrderType.REGULAR) {<br>            return order.getTotal() * 0.1;<br>        } else if (order.getType() == OrderType.PREMIUM) {<br>            return order.getTotal() * 0.2;<br>        }<br>        return 0;<br>    }<br>}</pre><p>To follow OCP, avoid modifying DiscountCalculator when adding new discount types. Instead, use polymorphism:</p><pre>public interface DiscountStrategy {<br>    double calculateDiscount(Order order);<br>}<br><br>public class RegularDiscount implements DiscountStrategy {<br>    public double calculateDiscount(Order order) {<br>        return order.getTotal() * 0.1;<br>    }<br>}<br>public class PremiumDiscount implements DiscountStrategy {<br>    public double calculateDiscount(Order order) {<br>        return order.getTotal() * 0.2;<br>    }<br>}<br>public class DiscountCalculator {<br>    private DiscountStrategy strategy;<br>    public DiscountCalculator(DiscountStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br>    public double calculateDiscount(Order order) {<br>        return strategy.calculateDiscount(order);<br>    }<br>}</pre><p>This way, you can add new discount strategies without changing existing code.</p><p><strong>Reference:</strong><br>Martin, R. C. <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>. Prentice Hall, 2008.</p><h4>3. Liskov Substitution Principle (LSP)</h4><p><strong>Definition:</strong> Subtypes must be substitutable for their base types without altering the correctness of the program.</p><p><strong>Example:</strong></p><p>Consider a Bird class with a fly() method, and a Penguin subclass:</p><pre>public class Bird {<br>    public void fly() {<br>        // Code for flying<br>    }<br>}<br><br>public class Penguin extends Bird {<br>    @Override<br>    public void fly() {<br>        // Penguins cannot fly<br>        throw new UnsupportedOperationException(&quot;Penguins can&#39;t fly&quot;);<br>    }<br>}</pre><p>Here, Penguin violates LSP because substituting it for Bird results in incorrect behavior. To adhere to LSP, separate the flying behavior:</p><pre>public abstract class Bird {<br>    // Common bird behaviors<br>}<br><br>public interface Flyable {<br>    void fly();<br>}<br><br>public class Sparrow extends Bird implements Flyable {<br>    @Override<br>    public void fly() {<br>        // Code for flying<br>    }<br>}<br>public class Penguin extends Bird {<br>    // Penguins don&#39;t fly, so no fly method<br>}</pre><p>Now, Penguin can be used wherever Bird is expected without causing issues.</p><p><strong>Reference:</strong><br>Liskov, B. <em>Data Abstraction and Hierarchy</em>, ACM SIGPLAN Notices, vol. 23, no. 7, pp. 50–59, Jul. 1988.</p><h4>4. Interface Segregation Principle (ISP)</h4><p><strong>Definition:</strong> Clients should not be forced to depend on interfaces they do not use.</p><p><strong>Example:</strong></p><p>Consider an interface Worker with methods for both working and attending meetings:</p><pre>public interface Worker {<br>    void work();<br>    void attendMeeting();<br>}</pre><p>A class RemoteWorker may not need the attendMeeting method:</p><pre>public class RemoteWorker implements Worker {<br>    @Override<br>    public void work() {<br>        // Remote work<br>    }<br><br>    @Override<br>    public void attendMeeting() {<br>        // Remote workers don’t attend meetings<br>    }<br>}</pre><p>To adhere to ISP, split Worker into separate interfaces:</p><pre>public interface Workable {<br>    void work();<br>}<br><br>public interface MeetingAttendee {<br>    void attendMeeting();<br>}<br>public class RemoteWorker implements Workable {<br>    @Override<br>    public void work() {<br>        // Remote work<br>    }<br>}</pre><p>Now, RemoteWorker only implements Workable, avoiding unnecessary methods.</p><p><strong>Reference:</strong><br>Martin, R. C. <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>. Prentice Hall, 2008.</p><h4>5. Dependency Inversion Principle (DIP)</h4><p><strong>Definition:</strong> High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.</p><p><strong>Example:</strong></p><p>Consider a ReportGenerator class that directly depends on a PDFPrinter:</p><pre>public class ReportGenerator {<br>    private PDFPrinter printer;<br><br>public ReportGenerator() {<br>        printer = new PDFPrinter();<br>    }<br>    public void generateReport() {<br>        // Code to generate report<br>        printer.print();<br>    }<br>}</pre><p>To follow DIP, introduce an abstraction for printing:</p><pre>public interface Printer {<br>    void print();<br>}<br><br>public class PDFPrinter implements Printer {<br>    @Override<br>    public void print() {<br>        // Print PDF<br>    }<br>}<br>public class ReportGenerator {<br>    private Printer printer;<br>    public ReportGenerator(Printer printer) {<br>        this.printer = printer;<br>    }<br>    public void generateReport() {<br>        // Code to generate report<br>        printer.print();<br>    }<br>}</pre><p>With this design, ReportGenerator depends on the Printer abstraction, allowing for different Printer implementations and promoting flexibility.</p><p><strong>Reference:</strong><br>Martin, R. C. <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>. Prentice Hall, 2008.</p><h3>Conclusion</h3><p>The SOLID principles provide a strong foundation for designing software that is modular, flexible, and maintainable. By following the Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle, developers can create systems that are easier to manage and extend. These principles are not just theoretical constructs but practical guidelines for improving software architecture and design.</p><p><strong>References:</strong></p><p>[1] Martin, R. C. <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>. Prentice Hall, 2008.<br>[2] Liskov, B. <em>Data Abstraction and Hierarchy</em>, ACM SIGPLAN Notices, vol. 23, no. 7, pp. 50–59, Jul. 1988.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d528486998" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>