<?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 Sudhakar Gumparthi on Medium]]></title>
        <description><![CDATA[Stories by Sudhakar Gumparthi on Medium]]></description>
        <link>https://medium.com/@vsgump?source=rss-fb199312c601------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*p7NpgWUIxxFof9tB</url>
            <title>Stories by Sudhakar Gumparthi on Medium</title>
            <link>https://medium.com/@vsgump?source=rss-fb199312c601------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:52:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vsgump/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[Building Python 3.11 on CentOS 8 with Enhanced Security and a Custom Virtual Environment]]></title>
            <link>https://vsgump.medium.com/building-python-3-11-on-centos-8-with-enhanced-security-and-a-custom-virtual-environment-ebd80c356250?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd80c356250</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[centos-8]]></category>
            <category><![CDATA[customlibrary]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 18:33:24 GMT</pubDate>
            <atom:updated>2024-09-22T12:54:12.383Z</atom:updated>
            <content:encoded><![CDATA[<p>CentOS 8 officially reached its end of life (EOL) in<strong> 2021</strong>, leaving users without official updates, security patches, and support. With CentOS 8 no longer receiving maintenance updates, many developers and system administrators have shifted to alternative solutions like CentOS Stream or Rocky Linux. However, some environments still rely on CentOS 8 due to its stability and specific use cases.</p><p>In this post, we’ll explore how to build a custom Python 3.11 environment on CentOS 8 despite its EOL status. We’ll dive into upgrading critical libraries like <strong>OpenSSL</strong>, <strong>zlib</strong>, <strong>bzip2</strong>, and <strong>NCurses</strong> to ensure security and functionality in the absence of official updates. We’ll also discuss how to manage the library paths and use custom installation approaches to mitigate risks posed by CentOS 8’s end of life.</p><blockquote><strong><em>What happens with EOL …?</em></strong></blockquote><ul><li><strong>Security patches</strong>: Any vulnerabilities discovered after the EOL date are not addressed.</li><li><strong>Bug fixes</strong>: No further improvements or fixes are provided.</li><li><strong>Support for repositories</strong>: Official repositories may no longer function, requiring manual interventions.</li></ul><p>This means that continuing to use CentOS 8 can expose your systems to security risks unless steps are taken to mitigate them. For those who still need to operate in CentOS 8 environments, a custom installation of key components becomes necessary to ensure that essential libraries and services remain up to date and secure.</p><blockquote><strong>Handling Repository Issues and Custom Installation Paths</strong></blockquote><p>Since the CentOS 8 repositories are no longer maintained, the first challenge is ensuring that packages can still be installed. The CentOS mirrors no longer provide packages, so we must switch to using the <strong>CentOS Vault</strong>, which holds older packages for legacy purposes.</p><blockquote><strong>Now, let us write docker file first and we see any theory later</strong></blockquote><p><strong><em>Before we jump on, we are not discussing many concepts here in detail like Docker, docker commands, python and virtual environments, Security Vulnerabilities and OS concepts and other.</em></strong></p><p><strong><em>This blog is intended for python developers, architects who wants to develop a docker container using centos 8 (EOL) with some patch upgrades and compile from sources and especially python 3.11 on centos 8 and , setting up python venv, and run the applications.</em></strong></p><h4>Base Image and Environment Variables</h4><p>We begin by pulling CentOS 8 as the base image. Environment variables are set for the different package versions we’ll be using in this build, including NCurses, zlib, bzip2, and expat.</p><pre>FROM centos:8<br><br>ENV NCURSES_VERSION=&quot;6.2&quot;<br>ENV ZLIB_VERSION=&quot;1.3.1&quot;<br>ENV BZIP2_VERSION=&quot;1.0.8&quot;<br>ENV PYTHON_VERSION=&quot;3.11.6&quot;<br>ENV EXPAT_VERSION=&quot;2.6.1&quot;</pre><h4>Updating CentOS Repositories</h4><p>Since CentOS 8 repositories have been archived, we need to replace the default mirrorlist with the correct baseurl that points to the CentOS Vault.</p><pre>RUN sed -i &#39;s/mirrorlist/#mirrorlist/g&#39; /etc/yum.repos.d/CentOS-Linux-*<br>RUN sed -i &#39;s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g&#39; /etc/yum.repos.d/CentOS-Linux-*</pre><h4>Installing Development Tools</h4><p>The next step is to update the system and install essential development tools and libraries. These packages are crucial for compiling Python and its dependencies from source.</p><pre>RUN yum -y update &amp;&amp; yum -y upgrade<br><br>RUN yum -y install wget make cmake gcc libffi-devel perl tar which openssl-devel &amp;&amp; \<br>    yum -y groupinstall &quot;Development Tools&quot; &amp;&amp; \<br>    yum -y install perl-IPC-Cmd perl-Digest-MD5 perl-Digest-SHA</pre><h4>Installing Expat</h4><p>Expat is an XML parser library used in several programming languages, including Python. We download, build, and install it from source.</p><pre>WORKDIR /app<br><br>RUN EXPAT_VERSION_UNDERSCORE=$(echo ${EXPAT_VERSION} | tr &#39;.&#39; &#39;_&#39;) &amp;&amp; wget https://github.com/libexpat/libexpat/releases/download/R_${EXPAT_VERSION_UNDERSCORE}/expat-${EXPAT_VERSION}.tar.gz \<br>    &amp;&amp; tar -xzf expat-${EXPAT_VERSION}.tar.gz \<br>    &amp;&amp; cd expat-${EXPAT_VERSION} \<br>    &amp;&amp; ./configure --prefix=/usr/local/expat\<br>    &amp;&amp; make \<br>    &amp;&amp; make install \<br>    &amp;&amp; cd .. \<br>    &amp;&amp; rm -rf expat-${EXPAT_VERSION} expat-${EXPAT_VERSION}.tar.gz<br>ENV PATH=&quot;/usr/local/expat/lib:${PATH}&quot;</pre><h4>Installing bzip2</h4><p>bzip2 is a compression tool used in various software, including Python. We compile and install it from source.</p><pre>RUN wget https://sourceware.org/pub/bzip2/bzip2-${BZIP2_VERSION}.tar.gz &amp;&amp; \<br>    tar -xvf bzip2-${BZIP2_VERSION}.tar.gz<br>RUN cd bzip2-${BZIP2_VERSION}  &amp;&amp; ls -lart .  \<br>    &amp;&amp; make &amp;&amp; \<br>    make install &amp;&amp; \<br>    cd .. &amp;&amp; \<br>    rm -rf bzip2-${BZIP2_VERSION}</pre><h4>Installing ncurses</h4><p>ncurses is a library for handling terminal-based GUIs. Python requires ncurses for its interactive shell and other terminal-based applications.</p><pre>RUN wget ftp://ftp.gnu.org/gnu/ncurses/ncurses-${NCURSES_VERSION}.tar.gz &amp;&amp; \<br>    tar -xvf ncurses-${NCURSES_VERSION}.tar.gz &amp;&amp; \<br>    cd ncurses-${NCURSES_VERSION} &amp;&amp; \<br>    ./configure &amp;&amp; \<br>    make &amp;&amp; \<br>    make install &amp;&amp; \<br>    cd .. &amp;&amp; \<br>    rm -rf ncurses-${NCURSES_VERSION}*</pre><h4>Installing zlib</h4><p>zlib is a compression library that is widely used for file compression in applications like Python. Here, we install it from source.</p><pre>RUN wget https://github.com/madler/zlib/releases/download/v${ZLIB_VERSION}/zlib-${ZLIB_VERSION}.tar.gz &amp;&amp; \<br>    tar -xvf zlib-${ZLIB_VERSION}.tar.gz &amp;&amp; \<br>    cd zlib-${ZLIB_VERSION} &amp;&amp; \<br>    ./configure --prefix=/usr/local/zlib &amp;&amp; \<br>    make &amp;&amp; \<br>    make install &amp;&amp; \<br>    cd .. &amp;&amp; \<br>    rm -rf zlib-${ZLIB_VERSION}*<br>ENV PATH=&quot;/usr/local/zlib/lib:${PATH}&quot;</pre><h4>Installing OpenSSL</h4><p>OpenSSL is critical for secure network communication. By installing the latest version of OpenSSL from source, we ensure compatibility with Python 3.11.</p><pre>RUN git clone -b OpenSSL_1_1_1w https://github.com/openssl/openssl.git &amp;&amp; \<br>    cd openssl* &amp;&amp; \<br>    ./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl &amp;&amp; \<br>    make -j $(nproc) &amp;&amp; \<br>    make install &amp;&amp; \<br>    ldconfig &amp;&amp; \<br>    cd .. &amp;&amp; \<br>    rm -rf openssl* \<br>ENV PATH=&quot;/usr/local/openssl/bin:${PATH}&quot;</pre><h4>Installing Python 3.11</h4><p>Finally, we download and install Python 3.11 from source. We configure it to use our custom-built zlib and OpenSSL installations.</p><pre>RUN wget https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tgz &amp;&amp; \<br>    tar -xf Python-$PYTHON_VERSION.tgz &amp;&amp; \<br>    cd Python-$PYTHON_VERSION &amp;&amp; \<br>    LDFLAGS=&quot;${LDFLAGS} -Wl,-rpath=/usr/local/openssl/lib&quot; ./configure --enable-shared --with-openssl=/usr/local/openssl --with-zlib=/usr/local/zlib &amp;&amp; \<br>    make &amp;&amp; \<br>    make altinstall &amp;&amp; \<br>    cd .. &amp;&amp; \<br>    rm -rf Python-$PYTHON_VERSION* &amp;&amp; \<br>    ldconfig<br><br>RUN echo &#39;/usr/local/lib&#39; &gt;&gt; /etc/ld.so.conf &amp;&amp; \<br>    ldconfig</pre><p><strong><em>Point to note</em></strong> is here we are using <strong><em>altinstall. </em></strong>Using make altinstall when installing Python from source prevents the new version from overwriting the system&#39;s default Python, which is crucial for CentOS 8&#39;s internal tools. It allows multiple Python versions to coexist without conflicts, ensuring that system utilities relying on the default version remain functional. This approach avoids modifying important symlinks like python and pip, reducing the risk of breaking system dependencies. It&#39;s a safe way to add a new Python version without disrupting the OS.</p><h4>Validate and Setting up a Virtual Environment</h4><p>A Python virtual environment allows you to manage dependencies and isolate your development workspace. Here’s how you create one using Python 3.11’s venv module.</p><pre>RUN python3.11 --version<br>RUN python3.11 -m venv /venv</pre><p>Once the virtual environment is created, we install the latest pip and setuptools to ensure your packages are up to date</p><pre>RUN /venv/bin/python3.11 -m ensurepip<br>RUN /venv/bin/pip install --upgrade pip setuptools</pre><p>Now, your virtual environment is ready. You can easily activate the virtual environment and start installing packages as below. But, let us see why do we need a virtual environment. Every one of the below item has its own weight in handling multiple scenarios in development phase.</p><ol><li><strong>Dependency Isolation</strong>: Each project can have its own set of dependencies, preventing conflicts across projects.</li><li><strong>Version Control</strong>: You can use different Python versions and library versions in different environments.</li><li><strong>Security</strong>: By linking your virtual environment with the latest OpenSSL and zlib, you minimize exposure to vulnerabilities in older versions.</li><li><strong>Reproducibility</strong>: Using a requirements.txt file, you can replicate the environment on any system.</li></ol><pre>RUN source /venv/bin/activate</pre><h4>Testing the Installation</h4><p>To confirm everything is working correctly, we can run several checks to verify Python, pip, and our custom libraries are correctly installed:</p><pre>RUN /venv/bin/python --version<br>RUN /venv/bin/pip --version<br>RUN /venv/bin/python -m pip list<br>RUN openssl version<br>RUN bzip2 --version<br>RUN ncurses6-config --version<br>RUN python3.11 --version<br>RUN xmlwf -v</pre><blockquote><strong>Conclusion</strong></blockquote><p><strong><em>I tried to put multiple things in one simple docker file for developers to explore and use it as needed.</em></strong></p><p>Running CentOS 8 after its EOL requires taking additional steps to maintain system security and functionality. By switching to the <strong>CentOS Vault</strong> and manually compiling critical libraries such as <strong>OpenSSL</strong>, <strong>zlib</strong>, <strong>bzip2</strong>, and <strong>ncurses</strong>, we ensure that our environment remains secure even in the absence of official updates.</p><p>The key takeaway is that <strong>custom installations</strong> of essential libraries, coupled with a Python virtual environment, allow you to maintain an updated, isolated, and secure Python environment. This approach ensures that your CentOS 8 systems remain functional and less vulnerable despite their unsupported status.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd80c356250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypting and Decrypting Files with OpenSSL]]></title>
            <link>https://vsgump.medium.com/encrypting-and-decrypting-files-with-openssl-9bd1b0f2c87b?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bd1b0f2c87b</guid>
            <category><![CDATA[openssl]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[decryption]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 05:11:49 GMT</pubDate>
            <atom:updated>2024-09-06T05:15:43.719Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of cybersecurity, protecting data confidentiality is paramount. One of the fundamental techniques for safeguarding data is encryption, which converts plaintext into an unreadable format unless decrypted with the appropriate key. In this guide, we’ll delve into a practical implementation of file encryption and decryption using OpenSSL, a robust and versatile cryptographic toolkit prevalent in Unix-like environments.</p><p>OpenSSL provides a suite of cryptographic operations, including support for a variety of encryption algorithms. In this blog, we’ll focus on the AES-256-CBC (Advanced Encryption Standard with 256-bit keys in Cipher Block Chaining mode) encryption algorithm. We’ll demonstrate how to use a Bash script to automate the process of generating a secure encryption key and initialization vector (IV), performing the encryption of a file, and subsequently decrypting it.</p><blockquote><strong>I have a question, what is Encryption and Decryption?</strong></blockquote><p>Before diving into the script, let’s briefly cover what encryption and decryption are:</p><ul><li><strong>Encryption</strong> is the process of converting plaintext data into a coded format to prevent unauthorized access. This is done using an algorithm and an encryption key.</li><li><strong>Decryption</strong> is the reverse process, where the encrypted data is converted back into its original format using the same or a corresponding decryption key.</li></ul><blockquote><strong>What do we do now to achieve this?</strong></blockquote><p>We aim to encrypt a file using AES-256-CBC encryption and then decrypt it back to its original form. AES-256 is a strong encryption algorithm, and CBC (Cipher Block Chaining) mode is one of the common modes of operation for AES.</p><p><em>Hmmmm</em> … let us develop a simple shell script to achieve our goal of encrypting a file and decrypting it using <strong>Openssl</strong></p><h4><strong>Step 1. Generating Encryption Key and IV</strong></h4><blockquote><strong>Hold on … what are these?</strong></blockquote><ul><li><strong>Encryption Key:</strong> We generate a 256-bit (32 bytes) key using OpenSSL’s rand command. AES-256 requires a 256-bit key for encryption.</li><li><strong>IV :</strong> Initialization Vector (IV) is a random or pseudo-random value used in encryption algorithms. This is crucial for maintaining data confidentiality and preventing patterns that might be exploited by attackers. We generate a 128-bit (16 bytes) IV. The IV ensures that the same plaintext encrypted with the same key produces different ciphertexts.</li></ul><p>Now, let us start writing script, say <strong><em>encryptfile.sh</em></strong></p><pre>#!/bin/bash<br><br># Generate a 256-bit key in hexadecimal format<br>key=$(openssl rand -hex 32)<br><br># Generate a 128-bit IV in hexadecimal format<br>iv=$(openssl rand -hex 16)<br><br>echo &quot;Encryption Key: $key&quot;<br>echo &quot;Initialization Vector (IV): $iv&quot;</pre><p>Now that we get Encryption Key and IV, we will encrypt the file, let us assume we have some file say .prop</p><h4><strong>Step 2. Encrypting the File</strong></h4><pre>openssl enc -aes-256-cbc -salt -in /tmp/conf/.prop -out /tmp/conf/.encrypted-prop -K $key -iv $iv</pre><p>For our info let us display these Encryption Key and IV</p><pre>encoded_key=$(echo -n $key | base64)<br>echo &quot;Encrypted file with key: $encoded_key&quot;<br>echo &quot;IV for decryption: $iv&quot;</pre><blockquote>I got a question … did we really encrypt the file? can we decrypt it to its original form?</blockquote><h4>Step 3. Decrypting the File</h4><p>let us take openssl help here to decrypt the file, but don’t forget, we need encryption key and iv that are used for encryption.</p><pre>openssl enc -d -aes-256-cbc -in /tmp/conf/.encrypted-prop -out /tmp/conf/.decrypted-prop -K $key -iv $iv</pre><p>Now, you can combine all those shell script and make <strong><em>encryptfile.sh</em> </strong>and also take any file that you want to encrypt and play with the script.</p><p>For a simple demo, we took one <strong><em>.prop</em></strong> file here with three dummy properties and shown the encrypt and decrypt procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzSnu5Ql9ocd1SbfdZBj6w.png" /></figure><blockquote><strong>Is that all?</strong></blockquote><p>Let us look into bit more details here,</p><h4>Security Considerations</h4><ol><li><strong>Key Management:</strong> The key should be stored securely. In this example, the key is displayed in plaintext, which is not ideal for real-world scenarios. Consider using secure key management systems.</li><li><strong>IV Handling:</strong> The IV should be unique and random for each encryption operation to ensure security.</li><li><strong>File Paths:</strong> Ensure that the file paths used in the script are secure and accessible only to authorized users.</li></ol><p><em>Before concluding, we didn’t discuss in detail many topics related to security and the terms we used here, I left these to readers’ interest and the need. We kept this blog just for those who need the encryption and decryption using openssl.</em></p><h4>Conclusion</h4><p>Encryption is a vital component of securing sensitive information. This script demonstrates a simple yet effective way to encrypt and decrypt files using AES-256-CBC with OpenSSL. By following these steps, you can ensure that your data remains protected from unauthorized access.</p><p>Feel free to adapt this script to suit your needs and explore more advanced features of OpenSSL for enhanced security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bd1b0f2c87b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing File Uploads to Amazon S3 Using multi-part with Pre-signed URLs and Threaded Parallelism]]></title>
            <link>https://vsgump.medium.com/enhancing-file-uploads-to-amazon-s3-with-pre-signed-urls-and-threaded-parallelism-23890b9d6c54?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/23890b9d6c54</guid>
            <category><![CDATA[file-upload-to-s3]]></category>
            <category><![CDATA[aws-multipart-upload]]></category>
            <category><![CDATA[large-file-upload]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 08:23:23 GMT</pubDate>
            <atom:updated>2024-03-08T04:23:39.576Z</atom:updated>
            <content:encoded><![CDATA[<p>Efficiently handling file uploads to Amazon S3 is crucial for today’s applications, especially those dealing with large amounts of data. In this guide, we’ll delve into methods to improve file upload processes using pre-signed URLs and threaded parallelism. By the end of this blog, you’ll understand how to enhance your file upload workflows to Amazon S3 using these techniques, making your application more efficient and responsive.</p><blockquote><strong>Let’s Start</strong></blockquote><p>We are not discussing any details of AWS or Python concepts in this blog, we explore the ways of uploading a large file (&gt;5GB) to AWS s3 buckets. This blog will give you an idea how to design your upload functionality effectively touching basic concepts of multipart upload and pre-signed urls.</p><p><em>Efficiently managing file uploads to Amazon S3 is essential for modern applications. In this guide, we’ll explore techniques such as pre-signed URLs and threaded parallelism to optimize the upload process. Pre-signed URLs offer secure and efficient uploads, while threaded parallelism enhances performance. By understanding these methods, developers can streamline file uploads and improve application responsiveness.</em></p><blockquote><strong>Do you know that is multi-part upload?</strong></blockquote><p>Multipart upload in Amazon S3 is a feature that allows you to upload large objects in parts, which can improve reliability, speed, and efficiency of uploads. Multipart upload in Amazon S3 is a feature that allows you to upload large objects in parts, which can improve reliability, speed, and efficiency of uploads.</p><blockquote>Multipart upload in Amazon S3 offers a robust solution for <strong>uploading large files</strong> efficiently. It enables resumable uploads, parallel uploading, and optimized network bandwidth usage, making it ideal for scenarios such as large file transfers, streaming data, and backup operations. By breaking down objects into smaller parts, multipart upload enhances reliability by reducing the impact of failures and providing a mechanism for real-time data uploads. Its versatility addresses the challenges of managing large datasets, ensuring improved performance and minimizing upload times, thus making it an indispensable feature for various industries and applications in cloud storage environments</blockquote><blockquote><strong>Let’s explore the solution approach in some basic steps:</strong></blockquote><ol><li>Understand the importance of file upload optimization.</li><li>Leverage pre-signed URLs for secure and efficient uploads.</li><li>Implement pre-signed URL generation in Python using Boto3.</li><li>Upload file parts to Amazon S3 using pre-signed URLs.</li><li>Complete the multipart upload process to consolidate file parts.</li></ol><blockquote><strong>Understanding the Importance of File Upload Optimization:</strong></blockquote><p>Efficient file uploads are crucial for user experience and system performance, especially when dealing with large files. Optimizing file uploads ensures faster transfer times, reduces server load, and enhances overall application responsiveness.</p><blockquote><strong>Leveraging Pre-signed URLs for Secure and Efficient Uploads:</strong></blockquote><p>Pre-signed URLs offer a<strong> secure method</strong> for uploading files directly to Amazon S3 <strong>without exposing sensitive credentials.</strong> They provide temporary access to specific S3 resources, enhancing security and minimizing potential risks.</p><blockquote><strong>Implementing Pre-signed URL Generation in Python:</strong></blockquote><p>We’ll delve into the Python code required to generate pre-signed URLs using the Boto3 library.</p><pre>def generate_presigned_url_transfer_accel(bucket_name, object_key, part_number, upload_id, expiration=3600):<br>    try:<br>        s3_client = boto3.client(&#39;s3&#39;, config=Config(<br>            s3={<br>                &#39;use_accelerate_endpoint&#39;: True<br>            }<br>        ))<br>        response = s3_client.generate_presigned_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&#39;upload_part&#39;,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20Params={%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&#39;Bucket&#39;:%20bucket_name,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&#39;Key&#39;:%20object_key,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&#39;PartNumber&#39;:%20part_number,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&#39;UploadId&#39;:%20upload_id%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20},%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20ExpiresIn=expiration%3Cbr%3E)<br>        return response<br>    except Exception as e:<br>        print(f&quot;Error generating presigned URL for part {part_number}: {str(e)}&quot;)<br>        return None</pre><blockquote><strong>Uploading File Parts with Pre-signed URLs:</strong></blockquote><p>The following function uploads individual file parts to Amazon S3 using pre-signed URLs.</p><pre>def upload_part_with_presigned_url(https://medium.com/url,%20part_data):<br>    try:<br>        # Upload the part using the pre-signed URL<br>        response = requests.put(url, data=part_data,headers={&#39;Content-Encoding&#39;: &#39;gzip&#39;})<br>        response.raise_for_status()<br><br>        # Extract the ETag for the part from the response headers<br>        etag = response.headers.get(&#39;ETag&#39;)<br>        if etag:<br>            print(f&quot;Part uploaded successfully! ETag: {etag}&quot;)<br>            return etag<br>        else:<br>            print(&quot;Failed to retrieve ETag from response headers&quot;)<br>            return None<br>    except Exception as e:<br>        print(f&quot;An error occurred during upload: {str(e)}&quot;)<br>        traceback.print_exc()<br>        return None</pre><blockquote><strong>Completing the Multipart Upload Process:</strong></blockquote><p>Once all file parts are uploaded, the multipart upload process must be completed to consolidate the parts into a single object within the S3 bucket.</p><pre>def complete_multipart_upload(bucket_name, object_key, upload_id, parts):<br>    try:<br>        s3_client = boto3.client(&#39;s3&#39;)<br>        response = s3_client.complete_multipart_upload(<br>            Bucket=bucket_name,<br>            Key=object_key,<br>            UploadId=upload_id,<br>            MultipartUpload={&#39;Parts&#39;: parts}<br>        )<br>        print(&quot;Multipart upload completed successfully!&quot;)<br>    except Exception as e:<br>        print(f&quot;Error completing multipart upload: {str(e)}&quot;)</pre><blockquote><strong>Where is main program, that chunks parts and upload?</strong></blockquote><p>This function upload_large_file_to_s3_with_presigned_urls takes a file path, bucket name, and object key as input parameters. It uploads large files to Amazon S3 by breaking them into smaller parts and uploading each part using pre-signed URLs. The function ensures efficient and reliable uploads while handling potential errors gracefully.</p><pre>def upload_large_file_to_s3_with_presigned_urls(file_path, bucket_name, object_key, part_size=10 * 1024 * 1024):<br>    st = time.time()<br>    try:<br>        s3_client = boto3.client(&#39;s3&#39;)<br>        response = s3_client.create_multipart_upload(<br>            Bucket=bucket_name,<br>            Key=object_key<br>        )<br>        upload_id = response[&#39;UploadId&#39;]<br>        print(f&#39;upload_id: {upload_id}&#39;)<br>        parts = []<br>        file_size = os.path.getsize(file_path)<br>        num_parts = math.ceil(file_size / part_size)<br>        with open(file_path, &#39;rb&#39;) as file:<br>            for part_number in range(1, num_parts + 1):<br>                # Read the part data with the specified part size<br>                part_data = file.read(part_size)<br><br>                # Generate pre-signed URL for the current part<br>                url = generate_presigned_url_transfer_accel(bucket_name, object_key, part_number, upload_id)<br>                if url:<br>                    print(f&#39;Pre-signed URL for part {part_number}: {url}&#39;)<br>                    etag = upload_part_with_presigned_url(https://medium.com/url,%20part_data)<br>                    if etag:<br>                        parts.append({&#39;PartNumber&#39;: part_number, &#39;ETag&#39;: etag})<br>                    else:<br>                        print(f&quot;Failed to upload part {part_number}&quot;)<br>                        traceback.print_exc()<br>                        s3_client.abort_multipart_upload(<br>                            Bucket=bucket_name,<br>                            Key=object_key,<br>                            UploadId=upload_id<br>                        )<br>                        return<br>                else:<br>                    print(f&quot;Failed to generate presigned URL for part {part_number}&quot;)<br>                    # Abort the multipart upload if any part fails<br>                    s3_client.abort_multipart_upload(<br>                        Bucket=bucket_name,<br>                        Key=object_key,<br>                        UploadId=upload_id<br>                    )<br>                    return<br><br>        # Complete multipart upload<br>        complete_multipart_upload(bucket_name, object_key, upload_id, parts)<br>        print(f&#39;Totle time taken {time.time() - st}&#39;)<br>    except Exception as e:<br>        print(f&quot;An error occurred during upload: {str(e)}&quot;)</pre><blockquote><strong>Who calls above function?</strong></blockquote><p>Your main program, and assumption is you handled AWS credentials as environment variables in your local AWS setup.</p><p>For eg., one of way of setting these is</p><p><em>os.environ[‘AWS_DEFAULT_PROFILE’] = ‘your-profile-name’<br>os.environ[‘AWS_REGION_NAME’] = ‘your-region-deployment’</em></p><pre>if __name__ == &quot;__main__&quot;:<br>  bucket_name = &#39;bucket_name&#39;<br>  file_name = &#39;my_file.tar.gz&#39;<br>  file_to_upload = f&#39;C:/test/{file_name}&#39;<br>  print(f&#39;Original file size bytes {os.path.getsize(file_to_upload)}&#39;)<br>  object_key = f&#39;multi-part-folder/{file_name}&#39;<br>  part_size = 5 * 1024 * 1024 #This is your part size, that should be greater than 5MB for AWS multipart upload<br>  st = time.time()<br>  upload_large_file_to_s3_with_presigned_urls(file_to_upload, bucket_name, object_key, part_size)<br>  print(f&#39;Upload time {time.time() -st}&#39;)</pre><p>Let us inspect a bit, if we can increase its performance further???</p><p>Let us add some threads and parallelism, if we can,</p><ol><li>Add some threaded parallelism for enhanced performance.</li><li>Implement threaded parallelism in file uploads using Python’s ThreadPoolExecutor.</li></ol><p>We change the function implementation little to add parallelism, see below code snippet,</p><pre>def upload_large_file_to_s3_with_presigned_urls(file_path, bucket_name, object_key, part_size=10 * 1024 * 1024):<br>    st = time.time()<br>    try:<br>        s3_client = boto3.client(&#39;s3&#39;)<br>        response = s3_client.create_multipart_upload(<br>            Bucket=bucket_name,<br>            Key=object_key<br>        )<br>        upload_id = response[&#39;UploadId&#39;]<br>        print(f&#39;upload_id: {upload_id}&#39;)<br>        parts = []<br>        file_size = os.path.getsize(file_path)<br>        num_parts = math.ceil(file_size / part_size)<br><br>        def upload_part(part_number):<br>            with open(file_path, &#39;rb&#39;) as file:<br>                file.seek((part_number - 1) * part_size)<br>                part_data = file.read(part_size)<br>            url = generate_presigned_url_transfer_accel(bucket_name, object_key, part_number, upload_id)<br>            if url:<br>                print(f&#39;Pre-signed URL for part {part_number}: {url}&#39;)<br>                etag = upload_part_with_presigned_url(https://medium.com/url,%20part_data)<br>                if etag:<br>                    return {&#39;PartNumber&#39;: part_number, &#39;ETag&#39;: etag}<br>                else:<br>                    print(f&quot;Failed to upload part {part_number}&quot;)<br>                    return None<br>            else:<br>                print(f&quot;Failed to generate presigned URL for part {part_number}&quot;)<br>                return None<br><br>        # Upload parts in parallel<br>        with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:<br>            future_to_part = {executor.submit(upload_part, part_number): part_number for part_number in<br>                              range(1, num_parts + 1)}<br>            for future in concurrent.futures.as_completed(future_to_part):<br>                part_number = future_to_part[future]<br>                try:<br>                    data = future.result()<br>                    if data:<br>                        parts.append(data)<br>                except Exception as exc:<br>                    print(f&#39;Part {part_number} generated an exception: {exc}&#39;)<br>        for part in parts:<br>            if part is None:<br>                print(&quot;Error: Some parts failed to upload. Aborting multipart upload.&quot;)<br>                s3_client.abort_multipart_upload(<br>                    Bucket=bucket_name,<br>                    Key=object_key,<br>                    UploadId=upload_id<br>                )<br>                return<br>        parts.sort(key=lambda x: x[&#39;PartNumber&#39;])<br>        complete_multipart_upload(bucket_name, object_key, upload_id, parts)<br>        print(f&#39;Total time taken {time.time() - st}&#39;)<br>    except Exception as e:<br>        print(f&quot;An error occurred during upload: {str(e)}&quot;)</pre><p>The above function is self explanatory, but let us look at one important instruction</p><pre>parts.sort(key=lambda x: x[&#39;PartNumber&#39;])</pre><p>This is very important where you need to sort the all parts before you do a final upload method’s call</p><blockquote><strong>Any Challenges with this parallel execution of parts?</strong></blockquote><p>While threaded parallelism offers significant performance gains, it also introduces challenges such as resource overhead, thread safety considerations, and context switching. Understanding these nuances is essential for effective utilization of threaded parallelism in file uploads.</p><blockquote><strong>Conclusion and Next Steps:</strong></blockquote><p>In conclusion, optimizing file uploads to Amazon S3 requires a combination of pre-signed URLs and threaded parallelism. By implementing these techniques effectively, developers can streamline file upload workflows, enhance system efficiency, and deliver an optimal user experience. As you continue to explore file upload optimization, consider experimenting with additional strategies and staying updated on best practices in cloud storage management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23890b9d6c54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unorthodox Design: Using Nginx as a Reverse Proxy for CloudFront]]></title>
            <link>https://vsgump.medium.com/unorthodox-design-using-nginx-as-a-reverse-proxy-for-cloudfront-942275834e0f?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/942275834e0f</guid>
            <category><![CDATA[nginx-url-rewrite-for-cdn]]></category>
            <category><![CDATA[nginx-proxy-for-cdn]]></category>
            <category><![CDATA[cloudfront-pre-signed-url]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 12:51:48 GMT</pubDate>
            <atom:updated>2024-01-10T12:51:48.550Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we will explore a unique and effective design pattern that involves using Nginx as a reverse proxy in front of an Amazon CloudFront CDN (Content Delivery Network). This unconventional setup allows for enhanced control and customization over content delivery while leveraging the global reach and scalability of CloudFront.</p><p><strong><em>It is Unorthodox …</em></strong></p><p>The term “Unorthodox” is used in this context to highlight that the design choice of using Nginx as a reverse proxy for CloudFront is not the most common or traditional approach. In typical setups, CloudFront is often used directly without an intermediate reverse proxy like Nginx</p><blockquote><strong>Introduction</strong></blockquote><p>Content delivery is a critical aspect of web applications, and leveraging a Content Delivery Network (CDN) can significantly enhance performance and user experience. In this blog post, we’ll dive into a design choice that involves placing Nginx, a powerful and flexible web server, as a reverse proxy in front of a CloudFront distribution.</p><p>In addition, we will briefly discuss about the self-sign certificates configuration on Nginx for the “demoserver.com”</p><blockquote><strong>Design</strong></blockquote><p>In this unconventional design, Nginx takes center stage as a robust reverse proxy, orchestrating the flow of incoming requests. The use of self-signed SSL certificates adds a layer of security, while the Nginx configuration file (nginx.conf) becomes a canvas for customization, housing directives for SSL settings, proxy configurations, and even bespoke scripts for dynamic URL modifications. This orchestration allows for fine-grained control over the content delivery process. Nginx acts as a gatekeeper, forwarding requests to the CloudFront CDN distribution, and enabling users to implement specific behaviors, redirects, or adjustments to incoming URLs before they reach the global edge locations. This unorthodox yet powerful setup not only enhances security but also empowers users with a high degree of flexibility in tailoring the content delivery network to unique application requirements.</p><blockquote><strong>The Nginx Proxy Requirement!</strong></blockquote><p>As our intention is to redirect requests from <a href="https://demoserver.com/hel/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF">https://demoserver.com/hel/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF</a> to <a href="https://a1b54cd98ef9gh.cloudfront.net/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF">https://a1b54cd98ef9gh.cloudfront.net/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF</a> (Sample CFN URL) using Nginx as a proxy before CFN</p><p>You can customize <strong><em>&quot;/hel&quot; or </em></strong><strong><em>&quot;/heav&quot;or </em></strong><strong><em>&quot;/anything&quot;</em></strong> based on your need for re-writing of the url or for any customizations!!!</p><p>Let us look at the components we are going to use in this demonstration,</p><p><strong><em>Nginx.conf, docker-compose.yaml and an existing CloudFront URL</em></strong> (this is not discussed in this blog, out of scope for us, cheers …)</p><blockquote><strong>Nginx Configuration</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*m3FK8zLHqxQKsh1oyz7Qyg.png" /></figure><p><strong><em>Brief explanation of SSL Params!!</em></strong></p><ul><li>ssl_session_timeout 5m;: This parameter sets the maximum time a client SSL session may be reused. In this case, it&#39;s set to 5 minutes (5m), meaning that if a client reconnects within this time frame, the SSL session can be reused, improving performance by avoiding unnecessary handshakes.</li><li>ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;: Specifies the SSL/TLS protocols that the server will accept. This configuration allows for a range of protocols to ensure compatibility with a variety of clients while prioritizing the use of modern and secure TLS versions.</li><li>ssl_ciphers &#39;EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH&#39;;: Defines the allowed ciphers for the SSL connection. The specified ciphers prioritize those that offer strong encryption and are considered secure.</li><li>ssl_prefer_server_ciphers on;: This directive instructs the server to prefer the order of ciphers specified on the server side over the client&#39;s order. It ensures that the server&#39;s preferred ciphers are used whenever possible.</li><li>ssl_dhparam /etc/nginx/certs/dhparam.pem;: Specifies the location of the Diffie-Hellman parameter file. Diffie-Hellman is used to provide Perfect Forward Secrecy (PFS), enhancing the security of the SSL/TLS connection.</li><li>ssl_trusted_certificate /etc/nginx/certs/fullchain.crt;: Specifies a file containing trusted certificates when acting as a client. In this case, it helps establish trust with the CloudFront distribution when making requests.</li></ul><p>These SSL parameters collectively contribute to a secure and performant SSL/TLS configuration for the Nginx reverse proxy.</p><blockquote><strong>Certificate Generation with OpenSSL</strong></blockquote><p>Before deploying the Nginx reverse proxy, we need to generate self-signed certificates for secure communication. OpenSSL can help us accomplish this. Follow these steps to generate the required certificates:</p><p><strong><em>Generate a Private Key:</em></strong></p><p>The first step is to generate a private key using the openssl genpkey command. In this case, we use the RSA algorithm and secure it with AES-256 encryption. The private key is a crucial component of the SSL/TLS process, providing a secure means of encrypting and decrypting data.</p><p>openssl genpkey -algorithm RSA -out selfsigned.key -aes256</p><p>G<strong><em>enerate a Certificate Signing Request (CSR):</em></strong></p><p>Next, we create a Certificate Signing Request (CSR) using the private key generated in the previous step. The CSR includes information about the entity requesting the certificate, such as its country, state, organization, and more.</p><p>openssl req -new -key selfsigned.key -out selfsigned.csr</p><p>During this step, you will be prompted to provide details for the certificate. Ensure that the Common Name (CN) matches the domain or hostname for which the certificate is intended.</p><p><strong><em>Generate a Self-Signed Certificate:</em></strong></p><p>With the CSR in hand, we proceed to generate a self-signed certificate using the openssl x509 command. This certificate is valid for a specified duration, in this case, 365 days. The self-signed certificate establishes the trustworthiness of the server to clients.</p><p>openssl x509 -req -days 365 -in selfsigned.csr -signkey selfsigned.key -out selfsigned.crt</p><p><strong><em>Generate an Intermediate Certificate Signing Request (CSR)</em></strong></p><p>This command generates a new CSR (intermediate.csr) using the same private key (selfsigned.key). Intermediate CSRs are optional and may be used in more complex certificate chain configurations.</p><p>openssl req -new -key selfsigned.key -out intermediate.csr</p><p><strong><em>Generate an Intermediate Self-Signed Certificate</em></strong></p><p>This command signs the intermediate CSR, creating an intermediate self-signed certificate (intermediate.crt). The certificate is valid for 365 days in this example.</p><p>openssl x509 -req -days 365 -in intermediate.csr -signkey selfsigned.key -out intermediate.crt</p><p><strong><em>Generate a Diffie-Hellman Parameter for Perfect Forward Secrecy(Optional):</em></strong></p><p>For enhanced security, you can generate a Diffie-Hellman parameter file. This file, created with the openssl dhparam command, is used to enable Perfect Forward Secrecy (PFS) in the SSL/TLS handshake process.</p><p>openssl dhparam -out dhparam.pem 2048</p><p><strong><em>Concatenate Certificates to Create the Certificate Chain</em></strong></p><p>cat selfsigned.crt intermediate.crt &gt; fullchain.crt</p><p>This command concatenates the self-signed certificate (selfsigned.crt) and the intermediate certificate (intermediate.crt) into a single file (fullchain.crt). The resulting file represents the complete certificate chain, which is used in the Nginx configuration for SSL/TLS</p><p>PFS ensures that even if an attacker compromises the private key in the future, past communications remain secure.</p><blockquote><strong>What to do with all these certificates ????</strong></blockquote><p>Place these generated files (selfsigned.key, selfsigned.crt, and dhparam.pem if generated) in the certs directory as specified in the Docker Compose script.</p><p>Docker compose script ??? what is this? Ok, let us look at the script below, and we look into further</p><blockquote><strong>Docker Compose Integration</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*lCyBCAzkCgBdG46Zg9ZI9g.png" /></figure><p>This Docker Compose script defines a service named nginx-proxy based on the official Nginx image. It mounts configuration files, certificates, and logs as volumes, ensuring that changes to the configuration are reflected in the running container. The service is exposed on ports 80 and 443 for HTTP and HTTPS traffic, respectively.</p><p>Now that I have the generated <strong><em>self-signed certificates</em></strong>, I have <strong><em>nginx.conf</em></strong> script and the <strong><em>docker-compose.yaml, </em></strong>let us see how can we get this proxy ready and up!!!</p><p>Simple, copy <strong><em>nginx.conf and docker-compose.yaml</em></strong> into a folder called , “<strong><em>nginx”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*iICHupsrRt7zYUF4MZ2KUw.png" /></figure><p>“certs” folder looks like the below, I mean you can put all the generated self-signed certificates here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*iXENmpFC58MmfheviTSOLA.png" /></figure><blockquote><strong>I have all this now, what to do next?</strong></blockquote><p>Go to your <strong>“nginx”</strong> folder, run the below command</p><p><strong>docker-compose up</strong></p><p>This will bring your Nginx proxy setup up with the redirection, ssl termination and forward your request to your CDN URL, refer to the requirement section.</p><p>With this, your docker container with Nginx proxy is up on your host machine listening on 80 and 443, go and use <strong><em>“demoserver.com”</em></strong></p><p>Generate a CloudFront pre-signed url (<strong><em>you know it is active for pre-defined time</em></strong>) and use the Nginx redirection with the setup we have developed, access the url (<strong><em>it is just sample!</em></strong>)</p><p>Hit the URL <a href="https://demoserver.com/hel/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF">https://demoserver.com/hel/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF</a> in browser</p><p>and will be redirected to</p><p><a href="https://a1b54cd98ef9gh.cloudfront.net/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF">https://a1b54cd98ef9gh.cloudfront.net/demofile.zip?Expires=AAsLFEn80....&amp;Key-Pair-Id=TY8J74ABCD1EF</a></p><p><strong><em>demoserver.com to be mapped to your localhost, and you know it!!!</em></strong></p><p>The blog mentions the redirection of URLs from /hel to / as an example of unconventional URL rewriting. This customization may be necessary for specific use cases or application requirements</p><blockquote><strong>Best Practices for CloudFront Signed URLs</strong></blockquote><p>When using CloudFront to distribute content via signed URLs, it’s crucial to follow best practices. Always sign URLs with an <strong><em>alternate domain name</em></strong> (CNAME) rather than using the default CloudFront domain. This practice ensures that the signed URLs match the SSL/TLS certificate used by the Cloud</p><blockquote><strong>Considerations and Challenges!!!</strong></blockquote><p>While the described architecture provides unique advantages, it comes with a set of considerations. One aspect to consider is the potential increase in data transfer costs. AWS CloudFront optimizes data delivery with its global edge locations, but the additional layer introduced by Nginx may lead to increased data transfer, particularly if not carefully managed. Furthermore, in the context of CA-signed SSL certificates, ensuring widespread trust across client applications becomes essential. CA-signed certificates enhance security and trust but may involve additional costs and management overhead compared to self-signed alternatives.</p><p>Scaling considerations should also be taken into account, as the setup might introduce complexity in managing and scaling the Nginx layer alongside CloudFront. Monitoring and optimizing data flow, considering the cost implications of CA-signed certificates, and addressing potential scaling challenges are essential aspects when adopting this unorthodox design. Ultimately, the decision to embrace this configuration should align with specific use cases, balancing the benefits of customization with the associated considerations and the choice between self-signed and CA-signed certificates.</p><blockquote><strong>Conclusion</strong></blockquote><p>Some of the concepts like generating Pre-signed URLs, docker/docker-compose setup, proxy setups are left to reader’s understanding and experience!</p><p>I tried to put the blog around the use of Nginx proxy before CFN URLs, with re-write URL (as additional )</p><p>In this exploration of an unorthodox yet powerful architecture, we delved into the intricacies of leveraging Nginx as a versatile reverse proxy in conjunction with AWS CloudFront. The orchestration of self-signed SSL certificates, fine-grained Nginx configurations, and custom scripts for URL modifications provides a unique avenue for control and customization over the content delivery process. While this setup may be unconventional, its strength lies in the ability to enhance security, tailor content delivery to specific application needs, and exercise granular control over the flow of incoming requests. As technology continually evolves, such innovative configurations underscore the adaptability and versatility of these foundational tools. Whether for testing environments or specific use cases demanding a high level of customization, this unorthodox design showcases the flexibility and power that Nginx brings to the realm of content delivery networks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=942275834e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This is a blog is intended to develop a SAM Template for Deploying an API Gateway with Custom…]]></title>
            <link>https://vsgump.medium.com/this-is-a-blog-is-intended-to-develop-a-sam-template-for-deploying-an-api-gateway-with-custom-f3464214bd08?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3464214bd08</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[serverless-application]]></category>
            <category><![CDATA[custom-lambda-authorizer]]></category>
            <category><![CDATA[sam-template]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 11:40:19 GMT</pubDate>
            <atom:updated>2023-04-13T12:04:06.110Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>AWS Serverless Application Model — Demo with API Gateway, Lambda and Custom Authorizer</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/0*Ni0vV0P-AjlGf3U_.png" /></figure><blockquote><em>Hej! Welcome to this exciting SAM template exercise, where we’ll be building a secure RESTful API with Amazon API Gateway and AWS Lambda functions! By leveraging the power of Serverless Application Model (SAM), we’ll be able to quickly and easily deploy our API with all the necessary resources, including a Lambda Authorizer for secure access control. Whether you’re new to serverless development or a seasoned pro, this exercise is a great opportunity to learn how to build and deploy secure serverless applications using the latest AWS technologies. So let’s dive in and start building!”</em></blockquote><p>This is a blog is intended to develop a SAM Template for Deploying an API Gateway with Custom Lambda Authorizer and a Demo User Lambda which will download a file from S3 and stream. This is for the techies or developers who doesn’t know much has little or no understanding about AWS application development, looking for a straightforward working demo with little complex and custom logic that opens up the functional scope for enhancing AWS development.</p><p>There are so many blogs, much information floating over internet on this. I wanted to keep it simple, use the code and develop the application. Also, you will get a fair idea how to start developing serverless applications.</p><p>Other than your AWS setup, you can simply take the code snippets, run them and enhance with your developments it is that simple!</p><blockquote><em>Let us take the Model Architecture from AWS!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u91kUANS2kVvZqXw.png" /></figure><blockquote><strong><em>Core Components</em></strong></blockquote><ol><li>AWS CLI</li><li>SAM CLI</li><li>API Gateway</li><li>User Lambda</li><li>Custom Lambda Authorizer</li><li>S3 Bucket</li></ol><p>Assumptions and things that are not discussed in this blog are installation of AWS CLI and SAM CLI and AWS Profile configuration.</p><blockquote><strong><em>Architectural Components</em></strong></blockquote><p>Below are the core components of our DEMO</p><p><strong><em>AWS Serverless API Gateway (MyDemoApiGateway) </em></strong>— This component serves as the front-end for the serverless application. It receives requests from users and directs them to the appropriate AWS Lambda function.</p><p><strong><em>AWS Lambda Function (MyDemoApiJwtAuthorizerFunc) </em></strong>— This component is responsible for authenticating user requests. It receives a JWT token from the API Gateway and decodes it to extract user information like user_id, for eg., in this scenario.</p><p><strong><em>AWS Lambda Function (MyDemoApiUser) </em></strong>— This component is responsible for processing user requests. It receives requests from the API Gateway and performs the necessary operations on the user’s data.</p><p><strong><em>AWS Lambda Layers (JWTLibLayer and Boto3LibLayer) </em></strong>— These components are used to package and deploy additional libraries or dependencies for the Lambda functions.</p><p><strong><em>AWS Lambda Permissions (MyDemoApiJwtAuthorizerFuncPermission and MyDemoApiUserPerm)</em></strong> — These components grant permissions to the API Gateway to invoke the Lambda functions.</p><p><strong><em>AWS S3 Bucket (apidev-sam2-bucket) </em></strong>— This component is used to store data related to user requests.</p><p>No more waiting ….. just put the top gear…</p><p>All together in SAM template below.</p><blockquote><strong><em>SAM Template — template.yaml</em></strong></blockquote><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: A serverless  Demo Stack</pre><pre>Globals:<br>  Function:<br>    Timeout: 9</pre><pre>Resources:<br>  MyDemoApiGateway:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Sub ${AWS::StackName}-demoapi-gateway<br>      StageName: dev<br>      TracingEnabled: true<br>      OpenApiVersion: 3.0.1<br>      MethodSettings:<br>        - HttpMethod: &#39;*&#39;<br>          LoggingLevel: INFO<br>          ResourcePath: &#39;/*&#39;<br>          MetricsEnabled: true<br>          DataTraceEnabled: true<br>      Auth:<br>        DefaultAuthorizer: CustomAuthorizer<br>        Authorizers:<br>          CustomAuthorizer:<br>            FunctionArn: !GetAtt MyDemoApiJwtAuthorizerFunc.Arn<br>            Identity:<br>              Header: Authorization<br>              ReauthorizeEvery: 10<br>  MyDemoApiJwtAuthorizerFunc:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: !Sub ${AWS::StackName}-demoapi-authorizer<br>      Handler: authorizer.lambda_handler<br>      Runtime: python3.9<br>      CodeUri: demo/auth<br>      Layers:<br>        - !Ref JWTLibLayer<br>        - !Ref Boto3LibLayer<br>      Policies:<br>        - CloudWatchLambdaInsightsExecutionRolePolicy</pre><pre>  MyDemoApiUser:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: !Sub ${AWS::StackName}-demoapi-get-user<br>      Handler: user.lambda_handler<br>      Runtime: python3.9<br>      CodeUri: demo/user<br>      Layers:<br>        - !Ref JWTLibLayer<br>      Policies:<br>        - CloudWatchLambdaInsightsExecutionRolePolicy<br>        - S3CrudPolicy:<br>            BucketName: apidev-sam2-bucket<br>      Events:<br>        GetApi:<br>          Type: Api<br>          Properties:<br>            Path: /user<br>            Method: get<br>            RestApiId:<br>              Ref: MyDemoApiGateway</pre><pre>  JWTLibLayer:<br>    Type: AWS::Serverless::LayerVersion<br>    Properties:<br>      LayerName: !Sub ${AWS::StackName}-demoapi-pyjwt-lib<br>      ContentUri: ./demo/jwtlib<br>      CompatibleRuntimes:<br>        - python3.9<br>    Metadata:<br>      BuildMethod: python3.9</pre><pre>  Boto3LibLayer:<br>    Type: AWS::Serverless::LayerVersion<br>    Properties:<br>      LayerName: !Sub ${AWS::StackName}-demoapi-pyboto3-lib<br>      ContentUri: ./demo/boto3lib<br>      CompatibleRuntimes:<br>        - python3.9<br>    Metadata:<br>      BuildMethod: python3.9</pre><pre>  MyDemoApiJwtAuthorizerFuncPermission:<br>    Type: AWS::Lambda::Permission<br>    DependsOn:<br>      - MyDemoApiGateway<br>      - MyDemoApiJwtAuthorizerFunc<br>    Properties:<br>      Action: lambda:InvokeFunction<br>      FunctionName:<br>        Ref: MyDemoApiJwtAuthorizerFunc<br>      Principal: apigateway.amazonaws.com</pre><pre>  MyDemoApiUserPerm:<br>    Type: AWS::Lambda::Permission<br>    DependsOn:<br>      - MyDemoApiGateway<br>      - MyDemoApiUser<br>    Properties:<br>      Action: lambda:InvokeFunction<br>      FunctionName:<br>        Ref: MyDemoApiUser<br>      Principal: apigateway.amazonaws.com</pre><pre>Outputs:<br>  MyDemoApiGatewayEndpoint:<br>    Description: URL for the demo API Gateway endpoint<br>    Value: !Sub &quot;https://${MyDemoApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${MyDemoApiGateway.StageName}</pre><p>Let us read something about above components to understand,</p><p>The above template defines several AWS resources including a Serverless API Gateway, two Serverless Functions, two Lambda Layers, and two Lambda Permissions. The resources are defined using the AWS Serverless Application Model (SAM) specification, which is an extension of AWS CloudFormation for building serverless applications.</p><p>The Serverless API Gateway is defined under the “MyDemoApiGateway” resource, with various properties such as the name, stage, and auth settings. The auth settings specify a custom authorizer function (“MyDemoApiJwtAuthorizerFunc”) to authenticate requests with a JWT token.</p><p>The two Serverless Functions are defined under “MyDemoApiUser” and “MyDemoApiJwtAuthorizerFunc” resources respectively. Both functions are written in Python 3.9 and have a lambda_handler function. The “MyDemoApiJwtAuthorizerFunc” function is used as a custom authorizer function for the API Gateway, and the “MyDemoApiUser” function is used to handle GET requests to the “/user” endpoint of the API Gateway.</p><p>Two Lambda Layers are defined under “JWTLibLayer” and “PyBoto3LibLayer” resources respectively. Both layers contain third-party Python libraries that the Serverless Functions can use. The layers are compatible with Python 3.9.</p><p>Finally, two Lambda Permissions defined under “MyDemoApiUserPerm” and “MyDemoApiJwtAuthorizerFuncPermission” resources respectively. Both permissions allow the API Gateway to invoke the corresponding Serverless Functions.</p><p>Now you may have questions who will provide user and authorizer lambdas and information about Lambda Layers and so on ….</p><blockquote><strong><em>User Lambda — user.py</em></strong></blockquote><pre>import json<br>import os<br>import io<br>import gzip<br>import base64<br>import boto3</pre><pre>s3 = boto3.resource(&#39;s3&#39;)<br></pre><pre>def lambda_handler(event, context):<br>    print(event)<br>    user_id = event[&#39;requestContext&#39;][&#39;authorizer&#39;][&#39;userId&#39;]<br>    print(&#39;User ID:&#39;, user_id)</pre><pre>    bucket_name = os.getenv(&#39;S3_BUCKET&#39;, &#39;demo-store-bucket&#39;)<br>    file_name = &#39;demo-uploads/demofile.tar.gz&#39;</pre><pre>    # Specify the bucket and file you want to download<br>    s3_object = s3.Object(bucket_name, file_name)</pre><pre>    buffer = io.BytesIO()<br>    s3_object.download_fileobj(buffer)</pre><pre>    # Rewind the buffer to the beginning<br>    buffer.seek(0)</pre><pre>    # Extract the file contents from the buffer<br>    contents = buffer.getvalue()</pre><pre>    # Decode the contents if it&#39;s gzip-encoded<br>    if s3_object.content_encoding == &#39;gzip&#39;:<br>        contents = gzip.decompress(contents)</pre><pre>    # Set the response headers<br>    headers = {<br>        &#39;Content-Type&#39;: &#39;application/octet-stream&#39;,<br>        &#39;Content-Disposition&#39;: f&#39;attachment; filename={file_name}&#39;<br>    }</pre><pre>    # Base64-encode the response body to prevent any encoding issues<br>    body = base64.b64encode(contents).decode(&#39;utf-8&#39;)</pre><pre>    # Return the response object<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;headers&#39;: headers,<br>        &#39;body&#39;: body,<br>        &#39;isBase64Encoded&#39;: True<br>    }</pre><p>This shows simply, it downloads an object from s3 and passes back to gateway as byte stream.</p><blockquote><strong><em>Custom Authorizer — authorizer.py</em></strong></blockquote><pre>import jwt<br></pre><pre>def lambda_handler(event, context):<br>    print(event)<br>    token = event[&#39;authorizationToken&#39;]<br>    print(token)<br>    try:<br>        if &#39;Bearer&#39; in token:<br>            token = token.replace(&quot;Bearer &quot;, &quot;&quot;)<br>        else:<br>            raise<br>        print(token)<br>        decoded = jwt.decode(token, options={&quot;verify_signature&quot;: False})<br>        print(decoded)<br>        user_id = decoded[&#39;user_id&#39;]<br>        context = {&#39;userId&#39;: user_id}<br>        pol = {&#39;principalId&#39;: &#39;apigateway.amazonaws.com&#39;, &#39;policyDocument&#39;: {<br>            &#39;Version&#39;: &#39;2012-10-17&#39;,<br>            &#39;Statement&#39;: [<br>                {<br>                    &#39;Action&#39;: &#39;execute-api:Invoke&#39;,<br>                    &#39;Effect&#39;: &#39;Allow&#39;,<br>                    &#39;Resource&#39;: event[&#39;methodArn&#39;]<br>                }<br>            ]<br>        }, &#39;context&#39;: context}<br>        print(pol)<br>        return pol<br>    except Exception as e:<br>        print(e)<br>        return {<br>            &#39;principalId&#39;: &#39;unknown&#39;,<br>            &#39;policyDocument&#39;: {<br>                &#39;Version&#39;: &#39;2012-10-17&#39;,<br>                &#39;Statement&#39;: [<br>                    {<br>                        &#39;Action&#39;: &#39;execute-api:Invoke&#39;,<br>                        &#39;Effect&#39;: &#39;Deny&#39;,<br>                        &#39;Resource&#39;: event[&#39;methodArn&#39;]<br>                    }<br>                ]<br>            }<br>        }</pre><p>This is an AWS Lambda function that implements a custom authorizer for API Gateway. The purpose of this function is to authenticate the user making the request and generate an AWS Identity and Access Management (IAM) policy that allows or denies access to the requested API endpoint.</p><p>The function expects an HTTP request containing an authorization token in the <strong>authorizationToken</strong> field of the event. The function first extracts the token from the event and checks whether it has a <strong>Bearer</strong> prefix. If it does, the prefix is removed. The token is then decoded using the <strong>jwt</strong> library.</p><p>If the decoding is successful, the function extracts the <strong>user_id</strong> from the decoded token and creates a <strong>context</strong> object containing the <strong>userId</strong> field. The function then generates an IAM policy document that allows access to the requested API endpoint and returns it as part of a JSON object containing the <strong>principalId</strong> and <strong>context</strong>.</p><p>If the decoding fails for any reason, the function generates an IAM policy document that denies access to the requested API endpoint and returns it as part of a JSON object containing the <strong>principalId</strong>.</p><p>The generated IAM policy document is used by API Gateway to authorize the user making the request to access the requested API endpoint.</p><p><strong>NOTE</strong>: You can use this authorizer and customize the authentication mechanism for accessing APIs behind API gateway.</p><blockquote><em>Below are some of advantages of Custom Lambda Authorizers</em></blockquote><p>Custom Lambda Authorizers are used to authenticate and authorize incoming requests to an API Gateway before they reach the backend service. They are useful in scenarios where you want to control access to your API Gateway based on custom logic and rules.</p><p>1.<strong> Fine-grained access control:</strong> Custom Lambda Authorizers allow you to define granular access control policies that can be applied to specific endpoints or methods within an API Gateway. This allows you to provide access only to authorized users or groups.</p><p>2. <strong>Custom authentication:</strong> If you need to authenticate users using a custom authentication mechanism that is not supported by API Gateway out of the box, Custom Lambda Authorizers can provide a flexible solution.</p><p>3. <strong>Centralized authorization:</strong> Custom Lambda Authorizers allow you to centralize authorization logic in a single place, which can make it easier to manage and maintain access control policies across multiple services and applications.</p><p>4.<strong> Authorization with external systems:</strong> Most important many times, custom Lambda Authorizers can integrate with external systems like LDAP or Active Directory to perform authentication and authorization.</p><blockquote><strong><em>Lambda Layers</em></strong></blockquote><p>Now, let us see what lambda layer code contains. requirements.txt would be enough and SAM will build the requirements.</p><p>Boto2Layer includes a requirements.txt, with <strong><em>boto3==1.26.35</em></strong></p><p>JWTLayer inculdes a requirements.txt, with</p><p><em>PyJWT==2.5.0<br>cryptography==37.0.4<br>argon2-cffi<br>pycparser<br>chardet<br>cffi<br>certifi<br>rsa==4.8</em></p><blockquote><strong><em>You didn’t tell me how to arrange all the artifacts you mentioned?</em></strong></blockquote><blockquote><strong><em>Here you go!</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*pH1GWNMhlpG3wEak.png" /></figure><blockquote><strong><em>Build and Deployment</em></strong></blockquote><p>Now that, we had all the components, we first build the application navigating to the folder structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XZBOBSFJmY7lDMS9.png" /></figure><blockquote><strong><em>How to deploy this to AWS?</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*EeMA-imi-bp8iTUN.png" /></figure><p>Let us discuss more on the deploy command , what it does…</p><p>This command is used to deploy the AWS SAM application to AWS cloud infrastructure. Let’s break down each component of this command:</p><p><strong>sam deploy</strong>: This is the AWS SAM command used to deploy your application.</p><p><strong>--template-file ./.aws-sam/build/template.yaml</strong>: This specifies the path to the CloudFormation template that AWS SAM generates. In this case, it points to the generated template located at <strong>.aws-sam/build/template.yaml</strong>.</p><p><strong>--capabilities CAPABILITY_IAM</strong>: This is required when your application needs IAM resources. It acknowledges that your stack will create or modify IAM resources.</p><p><strong>--s3-bucket apidev-stacks</strong>: This specifies the S3 bucket where your deployment artifacts will be stored.</p><p><strong>--region us-west-2</strong>: This specifies the AWS region where you want to deploy your application.</p><p><strong>--profile aws-demo-user</strong>: This specifies the named profile you want to use from your AWS credentials file.</p><p><strong>--stack-name apidemo-sam2</strong>: This specifies the name you want to give your CloudFormation stack.</p><p>When you run this command, AWS SAM creates a CloudFormation stack with the name <strong>apidemo-sam2</strong> and deploys your application to the specified region, using the specified S3 bucket to store your deployment artifacts. It also acknowledges the creation or modification of IAM resources that your application needs.</p><h3>Coming all the way back …</h3><p>You want to understand bit more on the SAM Template we developed here and what is that template describe all about? Below is some additional information</p><blockquote><em>Section 1: AWSTemplateFormatVersion and Transform</em></blockquote><ul><li>The <strong>AWSTemplateFormatVersion</strong> is set to <strong>2010–09–09</strong>, which specifies the AWS CloudFormation template version.</li><li>The <strong>Transform</strong> is set to <strong>AWS::Serverless-2016–10–31</strong>, which indicates the use of the AWS Serverless Application Model (SAM) to define serverless applications.</li></ul><blockquote><strong><em>Section 2: Description</em></strong></blockquote><ul><li>The <strong>Description</strong> field provides a description of the serverless demo stack.</li></ul><blockquote><strong><em>Section 3: Globals</em></strong></blockquote><ul><li>The <strong>Globals</strong> section defines global settings that apply to all functions in the SAM template.</li><li>In this case, the <strong>Function</strong> section is used to set the <strong>Timeout</strong> for all functions to 9 seconds.</li></ul><blockquote><strong><em>Section 4: Resources</em></strong></blockquote><ul><li>The <strong>Resources</strong> section is where you define the AWS resources for your serverless application.</li></ul><p><strong>API Gateway</strong></p><ul><li>The <strong>MyDemoApiGateway</strong> resource defines an AWS Serverless REST API Gateway.</li><li>The <strong>Name</strong> property specifies the name of the API Gateway.</li><li>The <strong>StageName</strong> property sets the name of the deployment stage to “dev”.</li><li>The <strong>TracingEnabled</strong> property enables X-Ray tracing for the API.</li><li>The <strong>OpenApiVersion</strong> property sets the version of the OpenAPI specification to 3.0.1.</li><li>The <strong>MethodSettings</strong> property sets the logging, metric, and data trace settings for all HTTP methods and resource paths.</li><li>The <strong>Auth</strong> property specifies the custom authorizer function to use for authentication.</li></ul><p><strong>Custom Authorizer Function</strong></p><ul><li>The <strong>MyDemoApiJwtAuthorizerFunc</strong> resource defines a custom authorizer function.</li><li>The <strong>FunctionName</strong> property sets the name of the function to a combination of the CloudFormation stack name and “demoapi-authorizer”.</li><li>The <strong>Handler</strong> property sets the entry point for the Lambda function to “authorizer.lambda_handler”.</li><li>The <strong>Runtime</strong> property sets the runtime environment for the function to Python 3.9.</li><li>The <strong>CodeUri</strong> property sets the path to the code for the function.</li><li>The <strong>Layers</strong> property specifies the PyJWT and Boto3 libraries to use for the function.</li><li>The <strong>Policies</strong> property sets the execution role policies for the function to enable CloudWatch Lambda Insights execution role policy.</li></ul><p><strong>User Function</strong></p><ul><li>The <strong>MyDemoApiUser</strong> resource defines a Lambda function to retrieve a user.</li><li>The <strong>FunctionName</strong> property sets the name of the function to a combination of the CloudFormation stack name and “demoapi-get-user”.</li><li>The <strong>Handler</strong> property sets the entry point for the Lambda function to “user.lambda_handler”.</li><li>The <strong>Runtime</strong> property sets the runtime environment for the function to Python 3.9.</li><li>The <strong>CodeUri</strong> property sets the path to the code for the function.</li><li>The <strong>Layers</strong> property specifies the PyJWT library to use for the function.</li><li>The <strong>Policies</strong> property sets the execution role policies for the function to enable CloudWatch Lambda Insights execution role policy and S3 CRUD policy.</li><li>The <strong>Events</strong> property specifies the event trigger for the function, which in this case is an HTTP GET request to the /user resource path.</li></ul><p><strong>JWT Library Layer</strong></p><p>This resource defines an AWS Lambda layer containing the JWT library for Python. The <strong>Type</strong> property is set to <strong>AWS::Serverless::LayerVersion</strong>, indicating that this resource represents a layer. The <strong>Properties</strong> section specifies the name of the layer, the location of its content in the <strong>ContentUri</strong> property, and the compatible runtime for the layer (in this case, Python 3.9). The <strong>Metadata</strong> section provides additional information about the layer, including the build method used to create it.</p><p><strong>BOTO3 Layer Resource</strong></p><p>This resource defines another AWS Lambda layer, this time containing the boto3 library for Python. The properties of these layers are similar.</p><blockquote><strong><em>Section 5: Outputs:</em></strong></blockquote><p>This creates an output value that provides the URL for the demo API Gateway endpoint, using the <strong>!Sub</strong> function to substitute the values of the <strong>MyDemoApiGateway</strong> resource and the AWS region into the URL. The output value can be used by other AWS resources or in other SAM templates by referencing the <strong>MyDemoApiGatewayEndpoint</strong> output.</p><blockquote><strong><em>How to run the application?</em></strong></blockquote><p>curl <a href="https://0df0105p77.execute-api.us-west-2.amazonaws.com/dev/user">https://1ab123eb123.execute-api.us-west-2.amazonaws.com/dev/user</a> — header ‘Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJSb2xlIjoiREVNT0FkbWluIiwiSXNzdWVyIjoiSXNzdWVyIiwiVXNlcm5hbWUiOiJkZW1vdXNlciIsInVzZXJfaWQiOiJERU1PIiwiZXhwIjoxNjgwOTIyMzc2LCJpYXQiOjE2ODA5MjIzNzZ9.MTUcT1wPYJIB9HOqLaKN3R1jahYBBlQBKAqW1UXy97g’ -o demofile.tar.gz -sS</p><p>Hope we can start now developing Serverless Lambdas with customer authorizers with decent design to scale.</p><blockquote><strong><em>What next?</em></strong></blockquote><p>After developing and deploying your serverless applications using SAM, the next step would be to monitor and manage them effectively. AWS provides various tools and services for monitoring and troubleshooting serverless applications, such as CloudWatch Logs, CloudWatch Metrics, and X-Ray.</p><p>You can use CloudWatch Logs to monitor and analyze the logs generated by your Lambda functions and API Gateway. CloudWatch Metrics provide real-time metrics for your Lambda functions and other AWS services. X-Ray helps you to debug and trace your serverless applications by providing a visual representation of how your application is performing and where it is failing.</p><p>In addition to monitoring, you can also manage your serverless applications using AWS tools like CloudFormation, CodePipeline, and CodeDeploy. These tools help you to automate the deployment and management of your serverless applications, making it easier to scale and update them as your needs change.</p><blockquote><strong><em>Back to pavilion — What is SAM?</em></strong></blockquote><p>AWS Serverless Application Model (SAM) is an open-source framework that makes it easy to build serverless applications on AWS. It is an extension of AWS CloudFormation, which is used for infrastructure as code (IaC). SAM provides a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application.</p><p>With SAM, you can define your serverless application using a YAML or JSON template. The template can be used to define your AWS resources, including AWS Lambda functions, Amazon API Gateway APIs, Amazon S3 buckets, and more. SAM also provides a CLI tool that can be used to build, package, and deploy your application to AWS.</p><p>Using SAM, you can quickly and easily create, test, and deploy serverless applications. SAM abstracts the complexity of the underlying AWS services, allowing developers to focus on building their applications. It also provides a local testing environment for Lambda functions, enabling developers to test their functions without deploying them to AWS.</p><p>Finally, SAM simplifies the process of building, deploying, and managing serverless applications on AWS, making it a popular choice among developers who want to build serverless applications quickly and efficiently.</p><blockquote><strong><em>Let us s…t…r…e…t…c…h more and talk about Lambda Layers … briefly</em></strong></blockquote><p>Advantages of Lambda Layers:</p><p><strong><em>1. Code Reusability: </em></strong>With Lambda Layers, developers can share code and libraries across multiple functions, reducing code duplication and improving maintainability.</p><p><strong><em>2. Fast Deployment: </em></strong>Lambda Layers allow developers to separate their code from their configuration and deployment code, making it easier to manage and deploy Lambda functions.</p><p><strong><em>3. Version Control:</em></strong> Lambda Layers support version control, allowing developers to manage different versions of their code and libraries.</p><p><strong><em>4. Reduced Function Size: </em></strong>By using Lambda Layers, developers can reduce the size of their Lambda functions, which can improve performance and reduce deployment time.</p><p><strong>Limitations of Lambda Layers:</strong></p><p><strong><em>1. Increased Complexity: </em></strong>Using Lambda Layers can add complexity to the deployment process, requiring additional steps to package and deploy code and libraries.</p><p><strong>2. Limited Size:</strong> Lambda Layers have a size limit of 50 MB, which can be a limitation for larger codebases.</p><p><strong><em>NOTE</em></strong>: You can add up to five layers to a Lambda function. The total unzipped size of the function and all layers cannot exceed the unzipped deployment package size quota of 250 MB.</p><p><strong><em>3. Dependency Management:</em></strong> Managing dependencies between Lambda Layers and functions can be challenging, especially when there are multiple layers involved.</p><blockquote><strong><em>Buddy… you didn’t talk anything about limitations of SAM templates ???</em></strong></blockquote><p><strong><em>Yes, here you go with few</em></strong></p><p><strong><em>1. Limited Community Support:</em></strong> SAM is a relatively new tool, and there is limited community support available for it compared to other deployment tools.</p><p><strong><em>2. Limited Flexibility: </em></strong>SAM templates are based on AWS CloudFormation, which means that they have some limitations compared to other deployment tools.</p><p><strong><em>3. Complexity :</em></strong> Configuring complex serverless applications can be challenging with SAM templates, and it requires a good understanding of AWS services and CloudFormation.</p><p>The concept of SAM is vast, I tried to keep simple for learners, Let’s not dive into too much theory …. let’s start coding …</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3464214bd08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop Windows MSI on Linux Using Python/Docker/ Wine]]></title>
            <link>https://vsgump.medium.com/develop-windows-msi-on-linux-using-python-docker-wine-dd50cd3e69c3?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd50cd3e69c3</guid>
            <category><![CDATA[winehq]]></category>
            <category><![CDATA[cxfreeze]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mi]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 16:29:14 GMT</pubDate>
            <atom:updated>2022-09-23T06:48:55.134Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is written keeping the views of enthusiastic developer who wanted to experiment/work with distribution models of a python project or scripts.</p><p>Itried to put the required information and the design to achieve the final point, straight and simple. The concepts/tools like Docker, WINE and Python programming language are very wide. Without waiting further let us start drive along the way.</p><p><strong>Docker</strong></p><p>Docker is an open platform for developing, shipping, and running applications. Docker enables to separate your applications from infrastructure so you can deliver software quickly. The below design show brief information about the Docker architecture. We are using Docker scripts to achieve the goal.</p><figure><img alt="Representative Docker Model" src="https://cdn-images-1.medium.com/max/660/1*HlaN8DTu26qr1dAOp2z0_w.png" /></figure><p>Assuming that we all have docker installed on the machine where we are using, for windows , a Docker Desktop would be the right place to start.</p><p><strong>Wine</strong></p><p>Wine Is Not an Emulator. Wine is a compatibility layer capable of running Windows applications on several POSIX-compliant operating systems. Wine translates Windows API calls into POSIX calls on-the-fly. It is Open source. References <a href="https://wiki.winehq.org/Ubuntu">https://wiki.winehq.org/Ubuntu</a></p><p><strong>Python</strong></p><p>Python programming language is what we are using in the blog. We are using “cx_Freeze” library to build the .<strong>msi </strong>file from the python project.</p><p>‘cx_Freeze’ is open-source python library. It creates standalone executables from Python scripts. Python 3.6–3.10 on Windows requires the Visual C++ Redistributable, and it is free! cx_Freeze, when building the msi file, doesn’t automatically ship VC++ with the application.</p><p><strong>Demo/Development</strong></p><p>Till now we just scratched the tools that we are going to use, now lets develop a sample application and convert that into msi file.</p><p>WINE is windows on Linux, so we use here Docker Linux host and use Ubuntu. The docker script below builds the image.</p><pre>FROM ubuntu:20.04<br><br>ENV DEBIAN_FRONTEND noninteractive<br><br>ARG WINE_VERSION=winehq-stable<br>ARG PYTHON_VERSION=3.8.10<br><br># we need wine for this all to work, so we&#39;ll use the PPA<br>RUN set -x \<br>    &amp;&amp; dpkg --add-architecture i386 \<br>    &amp;&amp; apt-get update -qy \<br>    &amp;&amp; apt-get install --no-install-recommends -qfy apt-transport-https software-properties-common wget gpg-agent rename \<br>    &amp;&amp; wget -nv https://dl.winehq.org/wine-builds/winehq.key \<br>    &amp;&amp; apt-key add winehq.key \<br>    &amp;&amp; add-apt-repository &#39;https://dl.winehq.org/wine-builds/ubuntu/&#39; \<br>    &amp;&amp; apt-get update -qy \<br>    &amp;&amp; apt-get install --no-install-recommends -qfy $WINE_VERSION winbind cabextract \<br>    &amp;&amp; apt-get clean \<br>    &amp;&amp; wget -nv https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks \<br>    &amp;&amp; chmod +x winetricks \<br>    &amp;&amp; mv winetricks /usr/local/bin<br><br># wine settings<br>ENV WINEARCH win64<br>ENV WINEDEBUG <em>fixme-all<br></em>ENV WINEPREFIX /wine<br><br>ENV PYPI_URL=https://pypi.python.org/<br>ENV PYPI_INDEX_URL=https://pypi.python.org/simple<br><br>RUN wine --version<br>RUN wine64 --version<br>RUN set -x \<br>    &amp;&amp; winetricks win10<br><br><br>RUN set -x \<br>    &amp;&amp; for msifile in `echo core dev exe lib path pip tcltk tools`; do \<br>        wget -nv &quot;https://www.python.org/ftp/python/$PYTHON_VERSION/amd64/${msifile}.msi&quot;; \<br>        wine64 msiexec /i &quot;${msifile}.msi&quot; /qb TARGETDIR=C:/Python38; \<br>        rm ${msifile}.msi; \<br>    done \<br>    &amp;&amp; cd /wine/drive_c/Python38 \<br>    &amp;&amp; echo &#39;wine &#39;\&#39;&#39;C:\Python38\python.exe&#39;\&#39;&#39; &quot;$@&quot;&#39; &gt; /usr/bin/python \<br>    &amp;&amp; echo &#39;wine &#39;\&#39;&#39;C:\Python38\Scripts\easy_install.exe&#39;\&#39;&#39; &quot;$@&quot;&#39; &gt; /usr/bin/easy_install \<br>    &amp;&amp; echo &#39;wine &#39;\&#39;&#39;C:\Python38\Scripts\pip.exe&#39;\&#39;&#39; &quot;$@&quot;&#39; &gt; /usr/bin/pip \<br>    &amp;&amp; echo &#39;wine &#39;\&#39;&#39;C:\Python38\Scripts\pyinstaller.exe&#39;\&#39;&#39; &quot;$@&quot;&#39; &gt; /usr/bin/pyinstaller \<br>    &amp;&amp; echo &#39;wine &#39;\&#39;&#39;C:\Python38\Scripts\pyupdater.exe&#39;\&#39;&#39; &quot;$@&quot;&#39; &gt; /usr/bin/pyupdater \<br>    &amp;&amp; echo &#39;assoc .py=PythonScript&#39; | wine cmd \<br>    &amp;&amp; echo &#39;ftype PythonScript=c:\Python38\python.exe &quot;%1&quot; %*&#39; | wine cmd \<br>    &amp;&amp; while pgrep wineserver &gt;/dev/null; do echo &quot;Waiting for wineserver&quot;; sleep 1; done \<br>    &amp;&amp; chmod +x /usr/bin/python /usr/bin/easy_install /usr/bin/pip /usr/bin/pyinstaller /usr/bin/pyupdater \<br>    &amp;&amp; rm -rf /tmp/.wine-*<br><br>ENV W_DRIVE_C=/wine/drive_c<br>ENV W_WINDIR_UNIX=&quot;$W_DRIVE_C/windows&quot;<br>ENV W_SYSTEM64_DLLS=&quot;$W_WINDIR_UNIX/system32&quot;<br>ENV W_TMP=&quot;$W_DRIVE_C/windows/temp/_$0&quot;<br><br>#wheel<br>RUN python -m pip install --upgrade wheel<br><br># upgrade pip<br>RUN wine /wine/drive_c/Python38/python.exe -m pip install --upgrade pip<br><br>RUN pip --version<br>RUN python --version<br><br># install Microsoft Visual C++ Redistributable for Visual Studio 2017 dll files<br>RUN set -x \<br>    &amp;&amp; rm -f &quot;$W_TMP&quot;/* \<br>    &amp;&amp; wget -P &quot;$W_TMP&quot; https://download.visualstudio.microsoft.com/download/pr/11100230/15ccb3f02745c7b206ad10373cbca89b/VC_redist.x64.exe \<br>    &amp;&amp; cabextract -q --directory=&quot;$W_TMP&quot; &quot;$W_TMP&quot;/VC_redist.x64.exe \<br>    &amp;&amp; cabextract -q --directory=&quot;$W_TMP&quot; &quot;$W_TMP/a10&quot; \<br>    &amp;&amp; cabextract -q --directory=&quot;$W_TMP&quot; &quot;$W_TMP/a11&quot; \<br>    &amp;&amp; cd &quot;$W_TMP&quot; \<br>    &amp;&amp; rename &#39;s/_/\-/g&#39; *.dll \<br>    &amp;&amp; cp &quot;$W_TMP&quot;/*.dll &quot;$W_SYSTEM64_DLLS&quot;/</pre><p>Save the above content in a file, ex, Dockerfile.winpy, and run the below command</p><p><strong><em>docker build -t pywin-demo -f Dockerfile.winpy .</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kMCqZfFZq_ykg3hGUm9AEw.gif" /><figcaption>We are waiting …. here 15 to 20 min</figcaption></figure><p>Required WINE on Ubuntu server is ready as a docker image by now, let us test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKnd8AhXvudncZvlRTWHZQ.png" /></figure><p>We are ready with image, lets move to write a simple python application</p><p>Write python application which will take simple command line argument and print.</p><p>Create a folder demoproj, and create 3 files Dockerfile, main.py and setup.py. Shown below respectively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*kyTMl9iXeqh33XxMWjAG-w.png" /></figure><pre>FROM pywin-demo<br><br>WORKDIR /app<br>COPY . .<br>RUN chmod 777 -R .<br><br>RUN apt-get update -y<br>RUN python -m pip install --upgrade pip pywin32 cx_Freeze==6.8 importlib-metadata==4.8.1 setuptools==60.6.0<br><br>CMD python setup.py bdist --format=msi &amp;&amp; mv dist/*Demo*.msi dist/DemoPywin.msi</pre><p>Below is main program,</p><pre>import argparse<br><br>if __name__ == &#39;__main__&#39;:<br>    parser = argparse.ArgumentParser(description=&#39;Demo Application&#39;)<br>    parser.add_argument(&quot;-n&quot;, &quot;--name-val&quot;, help=&#39;This will be printed on console&#39;, default=&#39;default&#39;)<br>    args, unknown = parser.parse_known_args()<br>    if unknown:<br>        print(&#39;Invalid command args&#39;)<br>    if args:<br>        print(f&#39; Args passed is {args.name_val}&#39;)</pre><p>Now we need setup file, this is key we talk about little more on this.</p><pre>from cx_Freeze import setup, Executable<br><br>setup(name=&quot;DemoPywin&quot;,<br>      version=&quot;0.0.1&quot;,<br>      description=&quot;Demo Application&quot;,<br>      executables=[Executable(&quot;main.py&quot;, shortcut_name=&quot;Demo&quot;,<br>                              shortcut_dir=&quot;DesktopFolder&quot;, )],<br>      )</pre><p>This file uses setup method from cx_Freeze library, it will have lot customizable features. Read carefully, we say to use main.py and create a desktop short cut with name “Demo” . This setup file is key to generate installable msi, and here you can pass all required python libraries and dependencies and lot more… leaving it to the programmer capabilities and understanding. We have now enough for the demo.</p><p>Refer the link for more <a href="https://pypi.org/project/cx-Freeze/">https://pypi.org/project/cx-Freeze/</a></p><p>Lets build the msi, you need to do two steps, first build the docker image, then run. Go the project folder and run below commands</p><p><strong><em>docker build -t demo .</em></strong></p><p>Once the build complete, check if images are there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*r1c1IWhwTL3uvDKw35a5HQ.png" /></figure><p>Then run the below command to the file in your C drive (whereever you need)</p><p><strong><em>docker run -it -v C:/test12/demodel:/app/dist demo</em></strong></p><p>Cann’t wait ??? It takes just a while to build, then we go the folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v2f7fuzw4p_F47oHbTkUA.png" /></figure><p>Yes, you have msi file, let us install it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*teA99ssN9t6mwU6U33SdpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*FxS_TyfSKWSJxo2wbzYF2w.png" /></figure><p>Wrap up and go to the folder where it is installed,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRUrLP88s64ccfb9dkVs0A.png" /></figure><p>Let us wait, here and see what are all these files??</p><p>main.exe is the starting point for our application to run. Rest all lib and python.dll and others are app dependencies.</p><p>Run the program,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*r37gOrmkC14sJIsOhIaoNg.png" /></figure><p>That’s all folks, you have msi to ship and install.</p><p><strong>Take Away</strong></p><p>1.Windows EXE/MSI files can be built on Linux with the help of WINE Server</p><p>2.Docker images can be used to build Windows environment on Linux containers</p><p>3.CX Freeze is used to build MSI/EXEs using Python application programming language</p><p><strong><em>Additional Questions?</em></strong></p><p><strong>1.Are there any docker/wine/python images available on docker hub?</strong></p><p>Yes, many.</p><p><strong>2.Will you be able to run the generate EXE on all windows versions?</strong></p><p>Subjective, but mostly on all windows versions, yes. You might need to install certain dependent windows DLLs if needed any. cx_Freeze will not ship any windows’s dependencies when the application is built. It will ship all dependent python libraries. You need to exercise the dependencies cautiously.</p><p><strong>3.Python already have commands to generate MSI/EXE. Why CX Freeze?</strong></p><p>This library puts all application dependencies together, so application just runs on any windows machine, no hassle of setting up python and site-packages and if any …</p><p><strong>4.I have various python dependencies and my application is very large, do I need any additional things to generate EXE/MSI?</strong></p><p>I think, no need, all required links to your main.py will be picked up, may need to explore the cx_Freeze options.</p><p><strong>5.I wanted to have nice interactive Installation wizard can I customize?</strong></p><p>This will provide decent wizard, if you want any addons need to take different route …</p><p><strong>6.What if I need additional DLLs for my application?</strong></p><p>All the windows related libraries/os dlls licensed versions will not be shipped with application.</p><p><strong>7.Can this be deployed as Windows service?</strong></p><p>Multiple ways, we will explore one such later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd50cd3e69c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tomcat, Nginx, Docker Containers -App Deployment with High Available/Scalable Containers]]></title>
            <link>https://vsgump.medium.com/tomcat-nginx-docker-containers-app-deployment-with-high-available-scalable-containers-5a4509ad6c50?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a4509ad6c50</guid>
            <category><![CDATA[containers-loadbalance]]></category>
            <category><![CDATA[tomcat-cluster-redis]]></category>
            <category><![CDATA[nginx-tomcat-docker]]></category>
            <category><![CDATA[containers-sticky-session]]></category>
            <category><![CDATA[docker-tomcat-cluster]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Thu, 20 May 2021 14:31:34 GMT</pubDate>
            <atom:updated>2022-03-30T05:01:18.007Z</atom:updated>
            <content:encoded><![CDATA[<p>This post provides insights and simple deployment model. Application deployment on tomcat Docker containers , load balanced with Nginx and Proxy servers with SSL communication setup and along with sticky sessions, and session propagation</p><p>The operating system we choose here is Ubuntu 18.04, and with root permissions. All that we are trying here is to deploy a simple web application, SampleWebApp.war or any if you have handy, to multiple tomcat containers. Try to access the application with some host name, e.g., <strong>t1.my-site.com</strong> or <strong>t2.my-site.com</strong>.</p><p>We are deploying t1.my-site.com to two different Docker containers and t2.my-site.com on two different containers and these sites are load balanced among the two containers respectively for each site.</p><p>We access these two sites over SSL, like <a href="https://t2.my-site.com/"><strong><em>https://t1.my-site.com</em></strong></a> or <a href="https://t2.my-site.com/"><strong><em>https://t2.my-site.com</em></strong></a><strong><em>. </em></strong>So, have to discuss how to setup SSL as well.</p><p>Configure Log file setup for the 4 containers and verify the logs, many might have question how to access the application logs from containers. So, we look into that and some basics.</p><p>Finally, session propagation or sticky sessions, tricky part of the applications, where we cannot avoid some situations that demand sticky sessions. I still, would prefer stateless apis approach. But, as part of this deployment model, we will discuss sticky sessions and session propagation and setup.</p><p>That is pretty much the context, and we are not going to discuss any of these Tomcat, Cluster, Sticky Sessions, Docker, Container, Redis anything in depth. Many of our contributors published lot of information and tips on these topics. We simply use these tools to have a working deployment setup and see a hello world.</p><p>Let us split the story into multiple sections for easy readability and understanding.</p><ol><li>Install Docker and Docker Compose</li><li>Docker Compose scripts</li><li>Nginx Virtual Site Configuration</li><li>Deploy and Verify Sample Application</li><li>Sticky Session vs Session Propagation — Docker Script</li><li>Verify Sticky Sessions</li></ol><p><strong>Docker and Docker Compose</strong></p><p>Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers. <strong>Containers</strong> are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels. These containers provides high scalability and availability.</p><p>Open the Ubuntu terminal or VM Terminal. Run the commands to see if docker is already installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*ChSkN1ZvqmVtV6ltASVjDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*HbLN4VzO-_lIUBAyogfnbA.png" /></figure><p>On my machine, they already installed, but if it is not installed already on your system, you can install it by a simple command,</p><p><em>sudo apt-get update</em></p><p><em>sudo apt-get upgrade</em></p><p><em>sudo apt-get install docker-ce docker-compose</em></p><p>For details steps and understanding, please visit the docker official site, <a href="https://docs.docker.com/engine/install/ubuntu/">https://docs.docker.com/engine/install/ubuntu/</a></p><p><strong>Docker Compose scripts</strong></p><p><em>Docker-Compose</em> is a tool for defining and running multi-container Docker applications. With this, we use a YAML file to configure application’s services. Then, with a single command, create and start all the services from the configuration file created.</p><p>Let us define first container for one site, for<em> t1.my-site.com</em></p><pre>tomcat_1:<br>  image: tomcat:9-jdk8-openjdk<br>  environment:<br>    VIRTUAL_HOST: t1.my-site.com<br>    VIRTUAL_PORT: 8080<br>  restart: always<br>  volumes:<br>    - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>    - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;</pre><p>Second container,</p><pre>tomcat_3:<br>  image: tomcat:9-jdk8-openjdk<br>  environment:<br>    VIRTUAL_HOST: t1.my-site.com<br>    VIRTUAL_PORT: 8080<br>  restart: always<br>  volumes:<br>    - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>    - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;</pre><p>The above two configurations represent two containers.</p><p><em>Where is the application to deploy?</em> Let us inspect, <strong>“volumes”</strong> section and we configured <strong>“<em>./tomcat/webapps/</em>”</strong> which is on the host system (or the VM we are working). Here, the SampleWebApp.war file will be placed and it is deployed to the tomcat server of the above two containers.</p><p><em>Where did we say, it is tomcat server?</em> Let us inspect <strong>“image”</strong> section, and it is the docker image pulled from docker site. You can use any of the images available.</p><p><em>How do we get the log files from containers? </em>Check the <strong>“volumes”</strong> section and <strong><em>“./tomcat/logs”</em></strong></p><p>Similarly, we define two container services for <strong><em>t2.my-site.com. </em></strong>I’m not mentioning any details here, as we see the final version of the file towards the end of this section.</p><p>So, we now have to sites and two containers for each site. And, the question is <em>who will load balance?</em></p><p>That is Nginx, reverse-proxy</p><pre>reverse-proxy:<br>  <strong>image: jwilder/nginx-proxy</strong><br>  restart: always<br>  ports:<br>    - &quot;80:80&quot;<br>    - &quot;443:443&quot;<br>  volumes:<br>    - /var/run/docker.sock:/tmp/docker.sock:ro<br>    <strong>- ./nginx/certs:/etc/nginx/certs</strong><br>    <strong>- ./nginx/nginx-proxy.conf:/etc/nginx/conf.d/nginx-proxy.conf:ro</strong><br>  links:<br>    - tomcat_1<br>    - tomcat_2<br>    - tomcat_3<br>    - tomcat_4</pre><p>The highlighted parts of above configuration show that we are using Nginx reverse proxy of image “jwilder”. The folder on host system, or VM, <strong><em>“./nginx/certs” </em></strong>contains certificates of my-site.com (sample self signed certificates for demonstrative purpose). This contain two files, <em>my-site.com.crt</em> and <em>my-site.com.key.</em></p><p>The folder “<strong>./nginx/nginx-proxy.conf</strong>” is for Ngnix, 80 to 443 redirection and virtual host setup.</p><p>So, we have now, all the container configurations that go into “<strong><em>docker-compose.yml” </em></strong>and<strong><em> </em></strong>Nginx configuration that goes to<strong><em> “</em>nginx-proxy.conf” </strong>file. Now, let us see the <em>folder structure</em> that gives a clear picture which file go where, see the below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*qlvdIaZKgubEXKKJVhRW6A.png" /></figure><p>If you have the below two files, the entire deployment is done, that simple.</p><p><strong><em>docker-compose.yml</em></strong></p><pre>version: &quot;3&quot;<br><br>services:<br><br>  tomcat_1:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t1.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br><br>  tomcat_2:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t2.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br><br>  tomcat_3:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t1.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br><br>  tomcat_4:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t2.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br><br>  reverse-proxy:<br>    image: jwilder/nginx-proxy<br>    restart: always<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - /var/run/docker.sock:/tmp/docker.sock:ro<br>      - ./nginx/certs:/etc/nginx/certs<br>      - ./nginx/nginx-proxy.conf:/etc/nginx/conf.d/nginx-proxy.conf:ro<br>    links:<br>      - tomcat_1<br>      - tomcat_2<br>      - tomcat_3<br>      - tomcat_4</pre><p><strong><em>nginx-proxy.conf</em></strong></p><pre>server {<br>    listen 80;<br>    server_name t1.my-site.com;<br>    return 301 https://$host$request_uri;<br>}<br>server {<br>    listen 443 ;<br>    server_name t1.my-site.com;<br>    access_log /var/log/nginx/data-access.log combined;<br>    location / {<br>        proxy_pass http://t1.my-site.com:8080/;<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>   }<br>server {<br>    listen 80;<br>    server_name t2.my-site.com;<br>    return 301 https://$host$request_uri;<br>}<br>server {<br>    listen 443 ;<br>    server_name t2.my-site.com;<br>    access_log /var/log/nginx/data-access.log combined;<br>    location / {<br>        proxy_pass http://t2.my-site.com:8080/;<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>Nginx Virtual Site Configuration</strong></p><p>The above <em>nginx-proxy.conf</em>, show that we defined two virtual host configurations for each site, one for listening on 80 port, and the other listening on 443. If the request comes via port 80, it is redirected to 443 and the configuration is self explanatory in the above section.</p><p><strong>Deploy and Verify Sample Application</strong></p><p>Let us navigate to the folder, <strong><em>…/tomcat-nginx-docker,</em></strong> you must have created the folder structure by now. Also, you have a sample web-app ready and placed under <em>… /tomcat-nginx-docker/tomcat/webapps folder. </em>SSL cert and key , we have not discussed how to generate those, you can use openssl and generate them.</p><p>Simply run the command ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*3h-EpcmYB0OxizuoGjPKnA.png" /></figure><p>Wait a min, the docker-compose.yml, will pull all the needed container images, build them, and make up and running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMuN9HZq_acefoo0G5c9QQ.png" /></figure><p>Now, our infra is ready, the sample web application is up and running against two different site addresses we mentioned, <em>t1.my-site.com</em> and <em>t2.my-site.com</em>. We have not discussed here in this post, how to map the site name to host ip and configuration and setup. Just to make it simple, go to <strong><em>/etc/hosts </em></strong>file on the host system we are trying to set up the deployment environment, add the following,</p><p>127.0.1.1 t1.my-site.com</p><p>127.0.1.1 t2.my-site.com</p><p>The below are various screenshots of the two different sites of the sample application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQ7G2p4-KjKtLZpyAIn3ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZvsRAyTPFMqxAgenfUMWKQ.png" /></figure><p>The above two, show <strong><em>different hosts</em></strong> addressed user requests and the <strong><em>session ids vary.</em></strong> That means, it keeps creating different sessions for each request. Let us see the screen shots of the other site,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiwzQkbSeH17OP5Fct9OtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-D-MYsHsODmu_PL-BXHw3Q.png" /></figure><p>So, the same case here with t2.my-host.com as well.</p><p>And, it is time to discuss and implement session and propagation across containers in contrast with sticky and next section for those who need it!</p><p><strong>Session Propagation Setup — Docker Script</strong></p><p>Sticky, Sticky, Sticky … !</p><p>It is time, to loosen little bit from stickiness! Its true!!!</p><p>Coming to the point, it is bit challenging to maintain sticky sessions for various reasons. It demands maintenance from the infra point and application point as well.</p><p>So, let us get started to balance load keeping session intact, discussed, deployment model. Containers are very individual, and tomcats deployed to those containers are also independent. Propagation of sessions needs some external session management, it has its own pros and cons. Keeping them aside, <strong><em>who maintains those sessions now for us?</em></strong></p><p>Answer is, <strong><em>Redisson</em></strong> — <em>Redis</em> Java client with features of an in-memory data grid. Refer more details <strong><em>@</em></strong> <a href="https://github.com/redisson/redisson">https://github.com/redisson/redisson</a></p><p>Tomcat Session Manager supports this, so we are going to use it and configure all the tomcat containers connect the <strong><em>redis</em></strong> component for validating and maintaining sessions. Let us see the folder structure and components to be added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*5xRh6M3fh-WJ0ZI41rutgw.png" /></figure><p>jar files shown in the above image can be downloaded from the site, redisson.</p><p><strong>redission.conf </strong>to be created with below configurations.</p><pre>{<br>&quot;singleServerConfig&quot;:{<br>  &quot;address&quot;: &quot;redis://<strong><em>redis</em></strong>:6379&quot;,<br>  &quot;timeout&quot;:1800<br>},<br>&quot;threads&quot;:0,<br>&quot;nettyThreads&quot;:0,<br>&quot;transportMode&quot;:&quot;NIO&quot;<br>}</pre><p>The highlighted “redis” in the above is the host name of the container that we are going to setup down the line.</p><p><strong>context.xml </strong>to tell tomcat servers to use Redisson Session Manager. The contents are below.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;Context&gt;<br>    &lt;!-- Default set of monitored resources --&gt;<br>    &lt;WatchedResource&gt;WEB-INF/web.xml&lt;/WatchedResource&gt;<br>    &lt;!--<br>    &lt;Valve className=&quot;org.apache.catalina.valves.CometConnectionManagerValve&quot; /&gt;<br>    --&gt;<br>    &lt;Manager className=&quot;org.redisson.tomcat.RedissonSessionManager&quot;<br>             configPath=&quot;${catalina.base}/redisson.conf&quot; broadcastSessionEvents=&quot;true&quot;<br>             readMode=&quot;REDIS&quot; updateMode=&quot;DEFAULT&quot;/&gt;<br>&lt;/Context&gt;</pre><p>Let us now add “redis” container to the docker-compose.yml and link it to all the containers.</p><pre>redis:<br>  image: redis:alpine<br>  hostname: redis<br>  ports:<br>    - 6379:6379</pre><p>Now, the modified <strong><em>docker-compose.yml</em></strong>, with redis, looks like below.</p><pre>version: &quot;3&quot;<br><br>services:<br>  redis:<br>    image: redis:alpine<br>    hostname: redis<br>    ports:<br>      - 6379:6379<br><br>  tomcat_1:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t1.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br>      - &quot;./tomcat/conf/context.xml:/usr/local/tomcat/conf/context.xml&quot;<br>      - &quot;./tomcat/conf/redisson.conf:/usr/local/tomcat/redisson.conf&quot;<br>      - &quot;./tomcat/lib/redisson-tomcat-9-3.15.5.jar:/usr/local/tomcat/lib/redisson-tomcat-9-3.15.5.jar&quot;<br>      - &quot;./tomcat/lib/redisson-all-3.15.5.jar:/usr/local/tomcat/lib/redisson-all-3.15.5.jar&quot;<br>    links:<br>      - redis<br><br><br>  tomcat_2:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t2.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br>      - &quot;./tomcat/conf/context.xml:/usr/local/tomcat/conf/context.xml&quot;<br>      - &quot;./tomcat/conf/redisson.conf:/usr/local/tomcat/redisson.conf&quot;<br>      - &quot;./tomcat/lib/redisson-all-3.15.5.jar:/usr/local/tomcat/lib/redisson-all-3.15.5.jar&quot;<br>      - &quot;./tomcat/lib/redisson-tomcat-9-3.15.5.jar:/usr/local/tomcat/lib/redisson-tomcat-9-3.15.5.jar&quot;<br>    links:<br>      - redis<br><br><br>  tomcat_3:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t1.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br>      - &quot;./tomcat/conf/context.xml:/usr/local/tomcat/conf/context.xml&quot;<br>      - &quot;./tomcat/conf/redisson.conf:/usr/local/tomcat/redisson.conf&quot;<br>      - &quot;./tomcat/lib/redisson-tomcat-9-3.15.5.jar:/usr/local/tomcat/lib/redisson-tomcat-9-3.15.5.jar&quot;<br>      - &quot;./tomcat/lib/redisson-all-3.15.5.jar:/usr/local/tomcat/lib/redisson-all-3.15.5.jar&quot;<br>    links:<br>      - redis<br><br><br>  tomcat_4:<br>    image: tomcat:9-jdk8-openjdk<br>    environment:<br>      VIRTUAL_HOST: t2.my-site.com<br>      VIRTUAL_PORT: 8080<br>    restart: always<br>    volumes:<br>      - &quot;./tomcat/webapps:/usr/local/tomcat/webapps&quot;<br>      - &quot;./tomcat/logs:/usr/local/tomcat/logs&quot;<br>      - &quot;./tomcat/conf/context.xml:/usr/local/tomcat/conf/context.xml&quot;<br>      - &quot;./tomcat/conf/redisson.conf:/usr/local/tomcat/redisson.conf&quot;<br>      - &quot;./tomcat/lib/redisson-tomcat-9-3.15.5.jar:/usr/local/tomcat/lib/redisson-tomcat-9-3.15.5.jar&quot;<br>      - &quot;./tomcat/lib/redisson-all-3.15.5.jar:/usr/local/tomcat/lib/redisson-all-3.15.5.jar&quot;<br>    links:<br>      - redis<br><br><br>  reverse-proxy:<br>    image: jwilder/nginx-proxy<br>    restart: always<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - /var/run/docker.sock:/tmp/docker.sock:ro<br>      - ./nginx/certs:/etc/nginx/certs<br>      - ./nginx/nginx-proxy.conf:/etc/nginx/conf.d/nginx-proxy.conf:ro<br>    links:<br>      - tomcat_1<br>      - tomcat_2<br>      - tomcat_3<br>      - tomcat_4</pre><p>Read the above configuration, and the point of interest now is , <strong><em>“links”</em></strong> and <strong><em>“volume” </em></strong>sections of each tomcat container will have redis container link and redission configuration respectively.</p><p><strong>Verify Sticky Sessions</strong></p><p>Congratulations!!! Now containers share the load and share sessions and propagates. Let us bring the docker-compose up now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOcc7inQZOQLSrGi5zGNcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pg1C9sXKD52SUxQAmwdyQ.png" /></figure><p>Now, let us stop the host 388e96d2ed68, and the session now goes to the other, see the below screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl04NelIOyCXm0VgE_t7GA.png" /></figure><p>Now, stopping the container host, 359cb54354fa and bringing the other one back, the request goes to the other one, 388e96d2ed68. See below screen, all the session information is propagated vs <strong>STICKY</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umjZFlDBKKQ4GPQO8sUnNA.png" /></figure><p>Wait for sometime, and try to access the link, and now session is refreshed. And, you know, that is because “<strong><em>session-timeout</em></strong>” set in the web-app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7XfqBZeKQDz33cyf6BQ3g.png" /></figure><p>The docker scripts provided in this post are basic and has necessary information, like load balance, scale, reverse proxy, ssl, sticky sessions, session propagation. Based on these scripts, many security configuration and application tunings with JVM and ENV parameters and much more can be explored or added to make the deployment model production ready. But, the above does serve its purpose.</p><p>Some docker commands used, for stopping and starting containers,</p><p><em>docker stop 359cb54354fa</em></p><p><em>docker start 359cb54354fa</em></p><p><em>docker system prune -a (Cleans up all the docker installations)</em></p><p><em>docker-compose up</em></p><p>I tried as much as possible to keep the point straight for the people who doesn’t know anything on dockers and containers, but little Linux knowledge, can just follow the set up and understand container concepts based on the deployment model demonstrated in this post.</p><p>Please feel free to share any security and better capabilities to the above docker scripts to make the deployment model intact, would help all for the betterment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a4509ad6c50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App Deployment Setup on Ubuntu-Tomcat Cluster/Apache2 and MOD_JK Load Balance with Session…]]></title>
            <link>https://vsgump.medium.com/app-deployment-setup-on-ubuntu-tomcat-cluster-apache2-and-mod-jk-load-balance-with-session-c8cc656e3db6?source=rss-fb199312c601------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cc656e3db6</guid>
            <category><![CDATA[tomcat-cluster-sessions]]></category>
            <category><![CDATA[tomcat-clustering]]></category>
            <category><![CDATA[load-balance-mod-jk]]></category>
            <dc:creator><![CDATA[Sudhakar Gumparthi]]></dc:creator>
            <pubDate>Mon, 17 May 2021 19:37:57 GMT</pubDate>
            <atom:updated>2022-03-30T05:04:16.259Z</atom:updated>
            <content:encoded><![CDATA[<h3>App Deployment Setup on Ubuntu-Tomcat Cluster/Apache2 and MOD_JK Load Balance with Session Replication</h3><p>This post can be supportive to setup a <strong>cluster of tomcat servers</strong> behind <strong>apache2 </strong>and<strong> load balanced</strong> using “<strong>mod_jk</strong>”, one of the apache modules, has been specifically designed to allow the forwarding of requests from Apache to Tomcat server or a servlet container, while maintaining <strong>sessions</strong>, which is most important for us here.</p><p>We are not deep diving into any of the setups of installing ubuntu and setting up FTP or SFTP. We understand that we have ubuntu server installed and putty is ready with a root login for setting up the deployment environment for web applications or .war file(s) run on a cluster of tomcat servers.</p><p>We can split the tasks as below,</p><ol><li>Install JDK</li><li>Install Apache2</li><li>Install “mod_jk”</li><li>Install Tomcat Server</li><li>Set up Tomcat Cluster</li><li>Deploy sample web app</li><li>Load Balancer Configuration</li><li>Apache2 Configuration</li></ol><p><strong>Install JDK</strong></p><p>If not already installed, let us install jdk on ubuntu to a default location, run the below command.</p><p><em>sudo apt-get install openjdk-8-jdk</em></p><p>Once installed, check the java version,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*ES0_0z5pvVODk2Bo15vHjg.png" /></figure><p><strong>Install Apache2</strong></p><p>Just start typing <strong><em>sudo apt-get install apache2</em></strong><em>, </em>and leave all the default options. Once installation is completed, then check the configuration to see if everything installed right, use the command <strong><em>apachectl configtest </em></strong>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*4tcDEmADtmitbd213ZQw8Q.png" /></figure><p>You can ignore this message or if you want to fix then add ‘ServerName’ in the default config file of Apache2, in which we are going to do some changes down the line.</p><p><strong>Install “mod_jk”</strong></p><p>Do not wait any moment, just go ahead and hit the below command on the ubuntu terminal,</p><p><em>install libapache2-mod-jk</em></p><p>Once the installation is completed … … … wait a moment; we know that this component will be the key connector between apache and tomcat cluster, also acts as a load balancer. Now, we have Apache2 installed and mod_jk installed, we still need the tomcat cluster to be installed, why late? let us go there and back here again for configurations and setup.</p><p><strong>Install Tomcat Server</strong></p><p>Among multiple ways of installing Tomcat servers on ubuntu, we pick little straightforward for the use case. Let us download directly and unzip using below commands.</p><p><em>wget </em><a href="https://mirrors.estointernet.in/apache/tomcat/tomcat-8/v8.5.66/bin/apache-tomcat-8.5.66-windows-x64.zip"><em>https://mirrors.estointernet.in/apache/tomcat/tomcat-8/v8.5.66/bin/apache-tomcat-8.5.66-windows-x64.zip</em></a></p><p><em>apt-get install unzip</em></p><p><em>unzip apache-tomcat-8.5.66-windows-x64.zip</em></p><p>Now, create a folder <strong><em>tomcluster </em></strong>or any name you wish, under /opt. Once created, copy the extracted tomcat folder <em>apache-tomcat-8.5.66 </em>to <em>/opt/tomcluster.</em></p><p>Rename the folder <em>apache-tomcat-8.5.66 </em>to<em> tomcat-1</em></p><p>Make a copy of <em>tomcat-1</em> folder as <em>tomcat-2.</em></p><p>So now we have tomcat-1 and tomcat-2 servers and we can cluster them.</p><p><strong>Tomcat Cluster Setup</strong></p><p>Let us first configure <em>tomcat-1</em> server, the full path of tomcat-1 server would be <em>/opt/tomcluser/tomcat-1.</em></p><p>Go to <em>bin</em> folder, create a file with name <em>setenv.sh</em>, add the below line and save it. Simply, we are setting JAVA_HOME here.</p><p>JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64</p><p>Once done, let us go to <strong><em>conf/server.xml</em></strong> file and modify configurations as needed for clustering of tomcat servers.</p><p>Set Shutdown port =&gt; <strong>18005</strong></p><p>&lt;Server port=”18005&quot; shutdown=”SHUTDOWN”&gt;</p><p>Set up connection port =&gt;<strong> 18080</strong></p><p>&lt;Connector port=”18080&quot; protocol=”HTTP/1.1&quot; connectionTimeout=”20000&quot; redirectPort=”18443&quot; /&gt;</p><p>Set up AJP port =&gt; <strong>18009</strong></p><p>&lt;Connector port=”18009&quot; protocol=”AJP/1.3&quot; redirectPort=”18443&quot; secretRequired=”false”/&gt;</p><p>Now, getting to actual cluster configuration section, the below highlighted is our point of interest, and here onwards we call ‘tomcat-1’ as jvm1.</p><p>&lt;Engine name=”Catalina” defaultHost=”localhost” <strong><em>jvmRoute=”jvm1&quot;</em></strong>&gt;</p><p>Just add the below Cluster configuration under the element <em>&lt;Host&gt;.</em></p><pre>&lt;Cluster className=&quot;org.apache.catalina.ha.tcp.SimpleTcpCluster&quot; channelSendOptions=&quot;8&quot;&gt;<br>    &lt;Manager className=&quot;org.apache.catalina.ha.session.DeltaManager&quot; expireSessionsOnShutdown=&quot;false&quot;<br>             notifyListenersOnReplication=&quot;true&quot;/&gt;<br>    &lt;Channel className=&quot;org.apache.catalina.tribes.group.GroupChannel&quot;&gt;<br>        &lt;Membership className=&quot;org.apache.catalina.tribes.membership.McastService&quot; address=&quot;228.0.0.4&quot;<br>                    port=&quot;45564&quot; frequency=&quot;500&quot; dropTime=&quot;3000&quot;/&gt;<br>        &lt;Sender className=&quot;org.apache.catalina.tribes.transport.ReplicationTransmitter&quot;&gt;<br>            &lt;Transport className=&quot;org.apache.catalina.tribes.transport.nio.PooledParallelSender&quot;/&gt;<br>        &lt;/Sender&gt;<br>        &lt;Receiver className=&quot;org.apache.catalina.tribes.transport.nio.NioReceiver&quot;<br>                  address=&quot;auto&quot; port=&quot;4000&quot; autoBind=&quot;100&quot;<br>                  selectorTimeout=&quot;5000&quot; maxThreads=&quot;6&quot;/&gt;<br>        &lt;Interceptor className=&quot;org.apache.catalina.tribes.group.interceptors.TcpFailureDetector&quot;/&gt;<br>        &lt;Interceptor className=&quot;org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor&quot;/&gt;<br>        &lt;Interceptor<br>                className=&quot;org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor&quot;/&gt;<br>    &lt;/Channel&gt;<br>    &lt;Valve className=&quot;org.apache.catalina.ha.tcp.ReplicationValve&quot;/&gt;<br>    &lt;ClusterListener className=&quot;org.apache.catalina.ha.session.ClusterSessionListener&quot;/&gt;<br>    &lt;Deployer className=&quot;org.apache.catalina.ha.deploy.FarmWarDeployer&quot;<br>              tempDir=&quot;/opt/tomcluster/apps/temp&quot;<br>              deployDir=&quot;/opt/tomcluster/tomcat-1/webapps&quot;<br>              watchDir=&quot;/opt/tomcluster/apps&quot;<br>              watchEnabled=&quot;true&quot;/&gt;<br>&lt;/Cluster&gt;</pre><p>Let us discuss, little bit on the “Deployer” section, from above configuration</p><pre>&lt;Deployer className=&quot;org.apache.catalina.ha.deploy.FarmWarDeployer&quot;<br>              <strong>tempDir=&quot;/opt/tomcluster/apps/temp&quot;</strong><br>              <strong>deployDir=&quot;/opt/tomcluster/tomcat-1/webapps&quot;</strong><br>              <strong>watchDir=&quot;/opt/tomcluster/apps&quot;</strong><br>             <strong> watchEnabled=&quot;true&quot;</strong>/&gt;</pre><p>Create <strong><em>apps</em></strong> folder under /opt/tomcluster, which will be used for deploying and un-deploying of applications in the cluster.</p><p>And, <strong><em>temp</em></strong> folder under /opt/tomcluster/apps, for tomcat server’s work, if any needed.</p><p>Set, <strong><em>watchEnabled=true</em></strong> on the first server or jvm1, we call as host.</p><p><strong>NOTE</strong>=&gt; all the other tomcat servers in the clusters like jvm2, jvm3 … has to use this flag as false.</p><p>With this, jvm1 or tomcat-1 or host server of the tomcat cluster configuration is predominantly completed.</p><p>Now, we can configure <strong><em>jvm2</em></strong>, the tomcat-2 server we created, similarly, with the ports 28005 (Shutdown), 28080 (Connect), 28443 (Redirect) and <strong>28009 (AJP)</strong></p><p>&lt;Engine name=”Catalina” defaultHost=”localhost” <strong><em>jvmRoute=”jvm2&quot;</em></strong>&gt;</p><p>Refer below Deployer configuration, for all node servers</p><pre>&lt;Deployer className=&quot;org.apache.catalina.ha.deploy.FarmWarDeployer&quot;<br>              <strong>tempDir=&quot;/opt/tomcluster/apps/temp&quot;</strong><br>              <strong>deployDir=&quot;/opt/tomcluster/tomcat-2/webapps&quot;</strong><br>              <strong>watchDir=&quot;/opt/tomcluster/apps&quot;</strong><br>             <strong> watchEnabled=&quot;false&quot;</strong>/&gt;</pre><p><strong>NOTE =&gt; </strong>For all the node servers, <strong>watchEnabled=”false” </strong>and deployDir should be its own webapps deployment folder.</p><p>We configured, tomcat-1 (jvm1) as host and tomcat-2 (jvm2) as node servers of the Tomcat cluster.</p><p>Let us create a user and group on ubuntu and assign tomcat’s ownership. Refer below commands.</p><p>groupadd tomcat<br> useradd -s /sbin/nologin -g tomcat -d /opt/tomcluster tomcat<br> passwd tomcat<br> chown -R tomcat.tomcat /opt/tomcluster</p><p>Time to start the both jvms, navigate to <strong><em>/opt/tomcluster/tomcat-1/bin </em></strong>and<strong><em> /opt/tomcluster/tomcat-2/bin </em></strong>respectively to start the both servers.</p><p><em>sh startup.sh</em></p><p>Both the servers will be up and running on 18080 and 28080.</p><p><strong>Sample web app Deployment</strong></p><p>Take any sample webapp or .war file, and place it under <em>/opt/tomcluster/apps.</em></p><p>The host server as listens on this folder, will pick up this .war file and deploy it over its webapps, and also deploys on all the nodes in the cluster.</p><p>The application is now deployed to all the tomcat server nodes in the cluster along with the host.</p><p>Now, we have app deployed to the servers, and apache webserver installed, also the apache2-tomcat connector too installed.</p><p><strong>Load Balancer Configuration</strong></p><p>Let us navigate to <strong><em>/etc/libapache2-mod-jk</em></strong><em>, </em>and edit <strong><em>worker.properties</em></strong>. Copy the below properties as is and save the file. We are simply configuring two workers, jvm1 and jvm2 and pointing them to appropriate AJP ports we configured in the server.xml files of the tomcat servers accordingly.</p><p>Finally, we are coming to balance load among the workers, we have jvm1 and jvm2 for now. But any number of <strong><em>jvms</em></strong> can be added here, but they should be configured and up and running.</p><p># First we define virtual worker’s list<br>worker.list=jkstatus, jvm1,jvm2, loadbalancer<br> <br># Enable virtual workers earlier<br>worker.jkstatus.type=status<br>worker.loadbalancer.type=lb<br> <br># Add Tomcat instances as workers, three workers in our case<br>worker.jvm1.type=ajp13<br>worker.jvm1.host=localhost<br>worker.jvm1.port=18009<br> <br>worker.jvm2.type=ajp13<br>worker.jvm2.host=localhost<br>worker.jvm2.port=28009<br> <br># Provide workers list to the load balancer<br>worker.loadbalancer.balance_workers=jvm1,jvm2</p><p>Once saved the above, restart the apache2 server, by running command, <em>systemctl restart apache2</em></p><p><strong>Apache2 Configuration</strong></p><p>Enable mod re-write for apache running the below command</p><p><strong><em>a2enmod rewrite</em></strong></p><p>Go to <strong><em>/etc/apache2/sites-enabled/</em></strong> , open the file <strong><em>000-default.conf</em></strong></p><p>Add the below properties, under the <strong><em>&lt;VirtualHost&gt;</em></strong> section towards the end of the file</p><p>JkLogLevel debug</p><p>RewriteEngine on</p><p>RewriteRule ^/(.*)$ /$1 [PT,L]</p><p>JkMount /status status</p><p>JkMount /SampleWebApp loadbalancer</p><p>JkMount /SampleWebApp/* loadbalancer</p><p><strong>NOTE=&gt;</strong></p><p>loadbalancer is a keyword used in the worker.properties file.</p><p>/SampleWebApp is the sample application deployed to tomcat cluster in the previous sections. (You can use any web application here, with proper access to resources)</p><p>The below screens are for demonstrative purpose and show how sessions get propagates in contrast with sticky session and tomcat cluster work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXZCon282afe12TRkXM1hA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMFR-ib3sfHHhm_t_MMpVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRXpmlgaNR2TVkfv8C1EQw.png" /></figure><p>With the above setup, we have configured a simple tomcat cluster with apache2 webserver load balanced by mod_jk.</p><p>Sticky sessions, which may cause uneven loads shared across clusters, now are well managed with the session propagation and above configuration/setup. Also the load is balanced among the two jvms. In case of failure of any of the servers, session will still intact and the other server shares the load as long as session is valid.</p><p>Many of the load balance properties can be explored referring to original apache sites, so as how to weight balance the load and other combinations to yield maximum performance.</p><p>Any time, the status of the cluster, if in flux, if the application might have removed manually or accidentally from one of the nodes or host, then make sure, un-deploy the application from the cluster by removing the .war file from the <strong>“apps” </strong>folder configured. And, copy the latest war file again to <strong>“apps”</strong> folder to hint the cluster to makes sure all nodes and host have the latest deployments and load balanced.</p><p>Thanks for reading the long post and I hope it may be helpful for the small scale setups and enthusiastic developers.</p><p>We will see in the next post, how we re-architecture the above design with the utilization of container capabilities and for high availability and scaling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8cc656e3db6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>