<?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 Anshu Garg on Medium]]></title>
        <description><![CDATA[Stories by Anshu Garg on Medium]]></description>
        <link>https://medium.com/@garganshu?source=rss-ea89a9db9450------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BMhkY47o-zs3YNRl5htL4Q.jpeg</url>
            <title>Stories by Anshu Garg on Medium</title>
            <link>https://medium.com/@garganshu?source=rss-ea89a9db9450------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:19:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@garganshu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How We Built the Fastest In-Memory Key-Value Store in Pure Go (Hitting 6.87M ops/sec Without CGO)]]></title>
            <link>https://blog.devgenius.io/how-we-built-the-fastest-in-memory-key-value-store-in-pure-go-hitting-6-87m-ops-sec-without-cgo-600b4dba141f?source=rss-ea89a9db9450------2</link>
            <guid isPermaLink="false">https://medium.com/p/600b4dba141f</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Anshu Garg]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 16:46:56 GMT</pubDate>
            <atom:updated>2026-09-30T09:58:36.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZmNu6kv6bia3tNX.png" /></figure><p>For over a decade, the consensus in systems engineering has been unanimous: <strong>if you want raw, bare-metal networking throughput, you write it in C, C++, or Rust.</strong></p><p>Managed runtimes with garbage collection — especially Go — were considered “great for microservices and cloud infrastructure,” but fundamentally handicapped for extreme low-latency, multi-million-ops-per-second storage engines.</p><p>Standard Redis processes commands through a single-threaded event loop. While simple and lock-free, single-threaded architectures leave 95% of modern multi-core server CPUs completely idle.</p><p>When we set out to build <a href="https://github.com/GargAnshu9468/vortexkv"><strong>VortexKV</strong></a>, our goal was ambitious:</p><blockquote><strong><em>Can we build a drop-in Redis replacement in 100% pure Go (zero CGO, zero external C dependencies) that not only matches Redis, but shatters its concurrent throughput — hitting over 6.8 Million ops/sec while keeping p50 latency under 120 microseconds?</em></strong></blockquote><p>Here is the exact architecture, the bottlenecks we hit, and the engineering breakthroughs that made it possible.</p><h3>The Benchmark Numbers</h3><p>Before diving into code, here are the audited benchmark numbers running on modern hardware (verified via standard redis-benchmark):</p><h3>1. High-Concurrency &amp; Peak Pipelined Throughput</h3><p>Workload ConfigurationOperations / Secp50 LatencyBottleneck / Note<strong>Direct Concurrency (Non-pipelined, C=50)210,970 ops/sec111 µs</strong>Network round-trip time<strong>Medium Pipeline (P=16, C=50)1,048,218 ops/sec655 µs</strong>Breaks 1M ops/sec barrier<strong>Peak Pipelined SET (P=64, C=50, -r 100k)2,688,172 ops/sec1.33 ms</strong>In-place zero-alloc writes<strong>Peak Pipelined GET (P=64, C=50, -r 100k)3,076,923 ops/sec1.11 ms</strong>Memory bus &amp; L1/L2 cache<strong>Saturated Pipeline PING (P=128, C=64)5,495,560 ops/sec1.11 ms</strong>Coalescing 128 responses/syscall<strong>Peak Pipelined Burst PING (P=64, C=100)9,411,764 ops/sec175 µs</strong>Hardware theoretical ceiling</p><h3>2. Audited Head-to-Head vs Redis 7.2 &amp; DragonflyDB</h3><p>Audited with standard redis-benchmark -c 50 -n 100,000 (Randomized Keys -r 100000):</p><p>Benchmark TestVortexKV (Pure Go)Redis 7.2 ©DragonflyDB (C++)VortexKV vs Competition<strong>SET, no pipeline71,942 req/s</strong>76,000 req/s63,000 req/s<strong>+14.2% faster than DragonflyGET, no pipeline73,367 req/s</strong>76,000 req/s66,000 req/s<strong>+11.2% faster than DragonflySET, P=16931,098 req/s</strong>797,000 req/s847,000 req/s⚡ <strong>1.17× faster than Redis; 1.10× vs DragonflyGET, P=161,048,218 req/s</strong>1,100,000 req/s858,000 req/s⚡ <strong>1.22× faster than DragonflyDBSET, P=642,688,172 req/s</strong>1,230,000 req/s2,240,000 req/s⚡ <strong>2.18× faster than Redis; 1.20× vs DragonflyGET, P=643,076,923 req/s</strong>1,930,000 req/s2,310,000 req/s⚡ <strong>1.59× faster than Redis; 1.33× vs Dragonfly</strong></p><p>Anyone can verify these numbers on their own machine in 60 seconds:</p><pre>git clone https://github.com/GargAnshu9468/vortexkv.git<br>cd vortexkv<br>./scripts/run_docker_benchmarks.sh</pre><h3>Why Standard Go (net.Listen) Fails at 1M+ ops/sec</h3><p>The idiomatic way to write network servers in Go is simple:</p><pre>ln, _ := net.Listen(&quot;tcp&quot;, &quot;:7379&quot;)<br>for {<br>    conn, _ := ln.Accept()<br>    go handleConnection(conn) // Goroutine-per-connection<br>}</pre><p>This model is elegant for microservices. But at <strong>500,000+ commands per second</strong>, it hits a performance cliff:</p><ol><li><strong>Goroutine Stack Overhead</strong>: Even a 2KB stack per goroutine causes cache line pollution across L1/L2 CPU caches when thousands of connections churn.</li><li><strong>Go Runtime Scheduler Preemption</strong>: Cooperative scheduling introduces micro-jitter and context-switching overhead.</li><li><strong>Write Syscall Amplification</strong>: Writing each small Redis response (e.g. +OK\r\n or +PONG\r\n) incurs an independent kernel write syscall. Syscalls are expensive.</li><li><strong>Listener Bottleneck</strong>: A single Accept() loop serializes all incoming connection handshakes, causing socket listen backlog drops under burst traffic.</li></ol><p>To hit 6.8M+ ops/sec, we had to rethink the networking engine from the metal up.</p><h3>1. Multi-Reactor with SO_REUSEPORT Kernel Steering</h3><p>Rather than spawning unbounded goroutines or funneling connections through a single listener, VortexKV implements a hardware-accelerated <strong>Multi-Reactor pattern</strong> (using Linux epoll and macOS/BSD kqueue) powered by <strong>SO_REUSEPORT</strong>:</p><pre>func (s *KqueueServer) Start() error {<br>    for i := 0; i &lt; s.cfg.Workers; i++ {<br>        // Each worker opens its own dedicated listener on port 7379 via SO_REUSEPORT<br>        lFd, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)<br>        _ = syscall.SetsockoptInt(lFd, syscall.SOL_SOCKET, 0x0200 /* SO_REUSEPORT */, 1)<br>        _ = syscall.Bind(lFd, sa)<br>        _ = syscall.Listen(lFd, 4096)<br>        <br>        worker := newWorker(i, lFd)<br>        go worker.run()<br>    }<br>}</pre><h3>Why Kernel SO_REUSEPORT matters:</h3><p>Instead of a single acceptor thread passing sockets to worker channels (which introduces lock contention and channel buffer bottlenecks), the <strong>OS kernel directly hashes new client connections across worker reactor queues in hardware</strong>.</p><ul><li><strong>Zero Cross-Thread Mutexes on Accept</strong>: Every worker is autonomous.</li><li><strong>L1/L2 Instruction &amp; Data Cache Preservation</strong>: CPU caches stay hot.</li><li><strong>Kernel-Level Load Balancing</strong>: Sockets land directly on the core assigned to process their I/O.</li></ul><h3>2. Zero-Allocation Cyclic Ring Buffers</h3><p>Under extreme network load, Go’s Garbage Collector (GC) is your biggest enemy. If every socket read allocates a new make([]byte, 4096), GC pauses quickly degrade p99 latency into milliseconds.</p><p>VortexKV equips every active client connection with a dedicated <strong>cyclic circular ring buffer</strong>:</p><pre>type ConnectionRing struct {<br>    buf    []byte<br>    head   int<br>    tail   int<br>    mask   int<br>}</pre><pre>func (r *ConnectionRing) ReadFromSocket(fd int) (int, error) {<br>    // Read directly into preallocated ring buffer without heap allocs<br>    // Wrap-around handled via bitwise mask: (pos &amp; mask)<br>}</pre><p>Because socket payloads are processed, decoded, and executed in-place within the ring buffer, <strong>the steady-state read pipeline produces zero heap allocations.</strong></p><h3>3. Batch Socket Write Coalescing</h3><p>In Redis pipelines, a client sends 64 or 128 commands back-to-back in a single TCP packet.</p><p>If a server responds by issuing 64 individual write() syscalls back to the socket, the Linux kernel spends more time switching between user space and kernel space than actually moving data.</p><p>VortexKV implements <strong>smart socket write coalescing</strong>:</p><pre>func (c *Client) QueueResponse(resp []byte) {<br>    c.writeBuf.Append(resp)<br>    <br>    // If the socket receive queue still has pending commands,<br>    // coalesce responses in memory instead of flushing immediately<br>    if c.hasPendingReads() &amp;&amp; c.writeBuf.Len() &lt; MaxBatchSize {<br>        return<br>    }<br>    <br>    // Flush all queued responses in a single vectorized kernel write<br>    c.flush()<br>}</pre><p>When processing pipelined workloads, <strong>up to 128 responses are consolidated into a single kernel </strong><strong>writev / </strong><strong>send syscall</strong>. This single optimization boosted pipelined throughput from 1.8M ops/sec to over <strong>6.87M ops/sec</strong>!</p><h3>4. 256 Mutex-Striped Shards with Cacheline Padding</h3><p>Standard Redis is single-threaded to avoid lock contention. But to utilize all 16 or 32 cores on modern hardware, you need concurrency.</p><p>If you protect your keyspace with a global sync.RWMutex, CPU cores fight over the same memory cache line, causing devastating lock convoying.</p><p>VortexKV splits the global keyspace into <strong>256 independent, lock-striped shards</strong>:</p><pre>type KeyspaceShard struct {<br>    mu    sync.RWMutex<br>    data  map[string]*vortexObject<br>    // Cacheline padding: prevents CPU False Sharing across cores<br>    _pad  [64]byte<br>}</pre><pre>type Engine struct {<br>    shards [256]*KeyspaceShard<br>}</pre><h3>The Secret: Cacheline Padding (_pad [64]byte)</h3><p>Modern x86 and ARM CPUs synchronize memory in 64-byte chunks (cache lines). If two mutexes reside in the same 64-byte cache line, Core 0 updating Shard 0 invalidates the cache line for Core 1 updating Shard 1 — even though they are locking completely different data!</p><p>By padding each shard with [64]byte, every mutex occupies its own dedicated cache line. Contention drops to near-zero, and internal keyspace throughput exceeds <strong>75,900,000 ops/sec</strong> (27 ns/op).</p><h3>5. The Final Mile: Single-Cycle 32-bit Dispatch &amp; In-Place Slice Mutation</h3><p>When pushing past 2M ops/sec, profiling with pprof revealed two invisible bottlenecks that plague high-throughput Go services:</p><h3>A. Single-Cycle 32-bit Integer Word Dispatch</h3><p>Most Redis parsers read a command like &quot;GET&quot; or &quot;SET&quot;, allocate a Go string, and run strings.ToUpper(cmd). At 64 pipelined commands across 50 clients, that generated <strong>over 3,200 string allocations per batch</strong>, crushing the Go runtime GC.</p><p>VortexKV replaces string hashing with <strong>32-bit integer word matching</strong>:</p><pre>// Read first 4 bytes as a uint32 integer word<br>w := *(*uint32)(unsafe.Pointer(&amp;cmdBytes[0]))<br>// Single bitwise operation folds ASCII uppercase to lowercase in 1 cycle<br>w |= 0x20202020</pre><pre>switch w {<br>case 0x00746573: // &#39;s&#39; | &#39;e&#39;&lt;&lt;8 | &#39;t&#39;&lt;&lt;16<br>    return CmdSet<br>case 0x00746567: // &#39;g&#39; | &#39;e&#39;&lt;&lt;8 | &#39;t&#39;&lt;&lt;16<br>    return CmdGet<br>case 0x676e6970: // &#39;p&#39; | &#39;i&#39;&lt;&lt;8 | &#39;n&#39;&lt;&lt;16 | &#39;g&#39;&lt;&lt;24<br>    return CmdPing<br>}</pre><p>Command identification now executes in <strong>a single CPU clock cycle (0.3 nanoseconds)</strong> with zero string conversions and zero allocations.</p><h3>B. In-Place Zero-Allocation Keyspace Updates</h3><p>When updating an existing key (SET key new_val), allocating a new vortexObject struct forces heap allocation and GC scanning. VortexKV&#39;s SetString overwrites the existing byte slice in-place:</p><pre>func (s *KeyspaceShard) SetString(key string, val []byte, ttl int64) {<br>    if entry, exists := s.data[key]; exists &amp;&amp; entry.Type == TypeString {<br>        // Reuse capacity in-place without triggering GC allocation<br>        entry.Val = append(entry.Val[:0], val...)<br>        entry.ExpiresAt = ttl<br>        return<br>    }<br>    // Fallback only for new keys<br>    s.data[key] = &amp;vortexObject{Type: TypeString, Val: bytes.Clone(val), ExpiresAt: ttl}<br>}</pre><p>Overwriting keys now produces <strong>0 bytes/op of garbage</strong>, allowing sustained write throughput of <strong>2.68M ops/sec</strong> without GC latency spikes.</p><h3>More Than Just a Cache: AI Vectors &amp; Streams</h3><p>Because we built the storage engine in pure Go, we could embed modern capabilities that traditional Redis lacks:</p><h3>🧠 Native HNSW AI Vector Search</h3><p>Skip external vector databases. Store high-dimensional embeddings and execute nearest-neighbor queries directly in VortexKV:</p><pre># Store vector embeddings<br>redis-cli -p 7379 VADD embeddings doc1 0.95 0.05 0.0 0.0</pre><pre># Top-1 Cosine Similarity search<br>redis-cli -p 7379 VSEARCH embeddings 1 cosine 0.90 0.10 0.0 0.0<br># Returns: &quot;doc1&quot;, &quot;0.999512&quot;</pre><h3>🌊 Event Streams with Consumer Groups &amp; PEL</h3><p>Full support for distributed event streaming with XADD, XREADGROUP, XACK, and Pending Entries Lists.</p><h3>🌌 Embedded Cyberpunk Web Studio (:7380)</h3><p>The binary embeds a visual web command deck with 2D/3D keyspace visualization, live latency monitors, slowlog stream, and ACL configuration.</p><h3>Running VortexKV in 30 Seconds</h3><p>VortexKV is completely open-source under the MIT license.</p><p><strong>Via One-Line Installer (macOS / Linux):</strong></p><pre>curl -fsSL https://raw.githubusercontent.com/GargAnshu9468/vortexkv/main/install.sh | bash</pre><p><strong>Via Docker:</strong></p><pre>docker run -d -p 7379:7379 -p 7380:7380 ianshugarg/vortexkv:latest</pre><p><strong>Connect with your favorite Redis client:</strong></p><pre>redis-cli -p 7379 PING<br># PONG</pre><h3>Conclusion &amp; Lessons Learned</h3><p>Building high-throughput network engines in Go isn’t about avoiding the language — it’s about understanding the runtime:</p><ol><li><strong>Steer connections with </strong><strong>SO_REUSEPORT</strong> to let the OS kernel balance load across multi-reactor workers with zero cross-thread mutexes.</li><li><strong>Use preallocated ring buffers</strong> to starve the garbage collector of read buffers.</li><li><strong>Dispatch commands in a single CPU cycle</strong> using 32-bit integer word matching instead of string conversions.</li><li><strong>Mutate byte slices in-place</strong> to eliminate GC pressure on hot-path key overwrites.</li><li><strong>Batch kernel write syscalls</strong> when pipelined command queues drain.</li><li><strong>Pad concurrent structs with 64 bytes and 256-way sharding</strong> to stop CPU cache line bouncing and lock contention.</li></ol><p>If you love systems engineering, performance optimization, and pure Go, check out the code and consider leaving a star!</p><p>⭐ <strong>GitHub Repository</strong>: <a href="https://github.com/GargAnshu9468/vortexkv">https://github.com/GargAnshu9468/vortexkv</a><br>🌐 <strong>Live Interactive Web Demo</strong>: <a href="https://garganshu9468.github.io/vortexkv/">https://garganshu9468.github.io/vortexkv/</a><br>📖 <strong>Official Wiki &amp; Docs</strong>: <a href="https://github.com/GargAnshu9468/vortexkv/wiki">https://github.com/GargAnshu9468/vortexkv/wiki</a></p><p><em>Originally published at </em><a href="https://dev.to/anshugarg/how-we-built-the-fastest-in-memory-key-value-store-in-pure-go-hitting-687m-opssec-without-cgo-39ae"><em>https://dev.to</em></a><em> on September 18, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=600b4dba141f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-we-built-the-fastest-in-memory-key-value-store-in-pure-go-hitting-6-87m-ops-sec-without-cgo-600b4dba141f">How We Built the Fastest In-Memory Key-Value Store in Pure Go (Hitting 6.87M ops/sec Without CGO)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD Pipeline for a Django application using PostgreSQL, Gunicorn, Nginx, Docker & Jenkins]]></title>
            <link>https://blog.devgenius.io/ci-cd-pipeline-for-a-django-application-using-postgresql-gunicorn-nginx-docker-jenkins-6987b6bd1a40?source=rss-ea89a9db9450------2</link>
            <guid isPermaLink="false">https://medium.com/p/6987b6bd1a40</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Anshu Garg]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 13:12:33 GMT</pubDate>
            <atom:updated>2024-09-12T07:03:13.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Robust CI/CD Pipeline for a Django Application with PostgreSQL, GitHub, Gunicorn, Nginx, Docker &amp; Jenkins on AWS EC2</h3><p><strong>Introduction:</strong></p><p>Continuous Integration and Continuous Deployment (CI/CD) pipelines play a pivotal role in modern software development, transforming traditional development practices into streamlined and efficient workflows. These pipelines represent a set of automated processes that enable developers to integrate code changes, conduct thorough testing, and seamlessly deploy applications. The significance of CI/CD pipelines lies in their ability to enhance collaboration, reduce manual errors, and accelerate the delivery of high-quality software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VduAKmhelpf4TdY3xn3SqA.jpeg" /></figure><p><strong>Technologies and Tools:</strong></p><ol><li><strong>Django:</strong></li></ol><ul><li>A high-level Python web framework, Django, is used for building scalable and maintainable web applications.</li></ul><p>2.<strong> PostgreSQL:</strong></p><ul><li>A powerful, open-source relational database system, PostgreSQL, is integrated with Django for robust data storage and retrieval.</li></ul><p>3. <strong>Gunicorn:</strong></p><ul><li>Gunicorn (Green Unicorn) serves as the HTTP server for deploying Django applications, providing a reliable and efficient WSGI server.</li></ul><p>4. <strong>Nginx:</strong></p><ul><li>Nginx acts as a reverse proxy server for Gunicorn, managing client requests and enhancing application performance.</li></ul><p>5. <strong>Docker:</strong></p><ul><li>Docker facilitates containerization, encapsulating the application and its dependencies for consistent deployment across different environments.</li></ul><p>6. <strong>Jenkins:</strong></p><ul><li>Jenkins is a widely used automation server that orchestrates CI/CD pipelines, automating the build, test, and deployment processes.</li></ul><p>7. <strong>Groovy Scripting:</strong></p><ul><li>Groovy scripting in Jenkins allows the definition of complex CI/CD pipeline configurations, providing flexibility and customization.</li></ul><p>8. <strong>AWS EC2:</strong></p><ul><li>Amazon EC2 instances host the deployed application, leveraging the scalability and reliability of Amazon Web Services for production deployment.</li></ul><p>9. <strong>GitHub:</strong></p><ul><li>Centralized platform for collaborative version control, code hosting, and CI/CD integration, facilitating collaborative development, codebase management, and automated workflows in modern software projects.</li></ul><p><strong>Hierarchy:</strong></p><pre>.<br>└── myproject-on-docker/<br>    ├── app/<br>        ├── media<br>    │   ├── myproject/<br>    │   │   ├── __init__.py<br>    │   │   ├── asgi.py<br>    │   │   ├── settings.py<br>    │   │   ├── urls.py<br>    │   │   └── wsgi.py<br>    │   ├── myapp/<br>    │   │   ├── migrations/<br>    │   │   │   ├── __init__.py<br>    │   │   │   └── ...<br>    │   │   ├── static/<br>    │   │   │   └── myapp/<br>    │   │   │       ├── css/<br>    │   │   │       │   ├── index.css<br>    │   │   │       │   └── ...<br>    │   │   │       ├── fonts/<br>    │   │   │       │   └── ...<br>    │   │   │       ├── img/<br>    │   │   │       │   └── ...<br>    │   │   │       └── js/<br>    │   │   │           ├── index.js<br>    │   │   │           └── ...<br>    │   │   ├── templates/<br>    │   │   │   └── myapp/<br>    │   │   │       ├── upload_media_files.html<br>    │   │   │       └── ...<br>    │   │   ├── admin.py<br>    │   │   ├── apps.py<br>    │   │   ├── models.py<br>    │   │   ├── tests.py<br>    │   │   ├── urls.py<br>    │   │   └── views.py<br>    │   ├── static/<br>    │   │   ├── myapp/<br>    │   │   │   ├── css/<br>    │   │   │   │   ├── index.css<br>    │   │   │   │   └── ...<br>    │   │   │   ├── fonts/<br>    │   │   │   │   └── ...<br>    │   │   │   ├── img/<br>    │   │   │   │   └── ...<br>    │   │   │   └── js/<br>    │   │   │       ├── index.js<br>    │   │   │       └── ...<br>    │   │   └── admin/<br>    │   │       ├── css/<br>    │   │       │   └── ...<br>    │   │       ├── fonts/<br>    │   │       │   └── ...<br>    │   │       ├── img/<br>    │   │       │   └── ...<br>    │   │       └── js/<br>    │   │           └── ...<br>    │   ├── Dockerfile<br>    │   ├── entrypoint.sh<br>    │   ├── manage.py<br>    │   └── requirements.txt<br>    ├── nginx/<br>    │   ├── Dockerfile<br>    │   └── nginx.conf<br>    ├── .dockerignore<br>    ├── .gitignore<br>    ├── Jenkinsfile<br>    ├── README.md<br>    ├── compose.yaml<br>    ├── .env<br>    └── .env.db</pre><p><strong>Setting Up the Django Project:</strong></p><ol><li>Create a Virtual Environment (To isolate project dependencies):</li></ol><pre>python -m venv venv</pre><p>2. Activate the Virtual Environment:</p><ul><li>On Windows:</li></ul><pre>venv\Scripts\activate</pre><ul><li>On Unix or MacOS:</li></ul><pre>source venv/bin/activate</pre><p>3. Install Dependencies (Django, Gunicorn, &amp; psycopg2-binary):</p><pre>pip install Django<br>pip install gunicorn<br>pip install psycopg2-binary</pre><p>4. Make and Navigate to <em>myproject-on-docker/app</em> Directory:</p><pre>mkdir -p myproject-on-docker/app<br>cd myproject-on-docker/app</pre><p>5. Create and Navigate to the new Django Project:</p><pre>django-admin startproject myproject .<br>cd myproject</pre><p>6. Bundle all the project requirements:</p><pre>pip freeze &gt; requirements.txt</pre><p>7. Create a new Django app:</p><pre>python manage.py startapp myapp</pre><p>8. Navigate to <em>myproject.</em></p><p>Edit <em>settings.py including</em>:</p><ul><li>Settings Environment Variables</li><li>Host Allowance</li><li>New App Listing</li><li>Database Configuration</li><li>Static and Media Files Configurations</li></ul><pre>... # Other imports<br>import os<br><br>...# Other variables<br>SECRET_KEY = os.environ.get(&quot;SECRET_KEY&quot;)<br>DEBUG = bool(os.environ.get(&quot;DEBUG&quot;, default=0))<br>ALLOWED_HOSTS = [&quot;*&quot;]<br><br>INSTALLED_APPS = [<br>    ... # Other apps<br>    &#39;myapp.apps.MyappConfig&#39;,<br>]<br><br>...# Other variables<br>DATABASES = {<br>    &quot;default&quot;: {<br>        &quot;ENGINE&quot;: os.environ.get(&quot;SQL_ENGINE&quot;),<br>        &quot;NAME&quot;: os.environ.get(&quot;SQL_DATABASE&quot;),<br>        &quot;USER&quot;: os.environ.get(&quot;SQL_USER&quot;),<br>        &quot;PASSWORD&quot;: os.environ.get(&quot;SQL_PASSWORD&quot;),<br>        &quot;HOST&quot;: os.environ.get(&quot;SQL_HOST&quot;),<br>        &quot;PORT&quot;: os.environ.get(&quot;SQL_PORT&quot;),<br>    }<br>}<br><br>...# Other variables<br>STATIC_ROOT = os.path.join(BASE_DIR, &#39;static&#39;)<br>STATIC_URL = &#39;/static/&#39;<br><br>MEDIA_ROOT = os.path.join(BASE_DIR, &#39;media&#39;)<br>MEDIA_URL = &quot;/media/&quot;<br>...# Other variables</pre><p>Edit <em>urls.py including</em>:</p><ul><li>New App URLs</li><li>URL Patterns Configurations for Serving Media Files for Local Development</li></ul><pre>from django.conf.urls.static import static<br>from django.urls import path, include<br>from django.contrib import admin<br>from django.conf import settings<br>... # Other imports<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, include(&#39;myapp.urls&#39;)),<br>    ... # Other urls<br>]<br><br>if bool(settings.DEBUG):<br>    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><p>9. Navigate to <em>myapp.</em></p><p>Create <em>urls.py including </em>:</p><ul><li>Health Check API URL</li><li>Upload Media Files URL</li></ul><pre>from django.urls import path<br>from . import views<br>... # Other imports<br><br>urlpatterns = [<br>    path(&#39;health-check/&#39;, views.health_check, name=&#39;health_check&#39;),<br>    path(&#39;&#39;, views.UploadMediaFiles.as_view(), name=&#39;upload_media_files&#39;),<br>    ... # Other urls<br>]</pre><p>Edit <em>views.py including f</em>unctionalities of:</p><ul><li>Health Check API</li><li>Upload Media Files</li></ul><pre>from django.core.files.storage import FileSystemStorage<br>from django.views.generic import View<br>from django.http import JsonResponse<br>from django.shortcuts import render<br>... # Other imports<br><br><br>def health_check(request):<br>    return JsonResponse({&#39;status&#39;: &#39;ok&#39;})<br><br><br>class UploadMediaFiles(View):<br><br>    def get(self, request, *args, **kwargs):<br>        return render(request, &quot;myapp/upload_media_files.html&quot;)<br><br>    def post(self, request, *args, **kwargs):<br><br>        file = request.FILES[&quot;file&quot;]<br>        fs = FileSystemStorage()<br><br>        file = fs.save(file.name, file)<br>        file_url = fs.url(https://medium.com/file)<br><br>        context = {<br>            &quot;file_url&quot;: file_url<br>        }<br><br>        return render(request, &quot;myapp/upload_media_files.html&quot;, context)<br><br>... # Other views</pre><p>Create a <em>templates/myapp </em>directory and create an <em>upload_media_files.html</em> file inside the <em>templates/myapp </em>directory to render a web page that includes a form for file uploads. When the form is submitted, it sends the file to the server, which can process it and, if successful, provide a link to the uploaded file.</p><p><em>upload_media_files.html:</em></p><pre>{% block content %}<br><br>&lt;form action=&quot;/&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>    {% csrf_token %}<br>    &lt;input type=&quot;file&quot; name=&quot;file&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;submit&quot; /&gt;<br>&lt;/form&gt;<br><br>{% if file_url %}<br>  &lt;p&gt;File uploaded at: &lt;a href=&quot;{{ file_url }}&quot;&gt;{{ file_url }}&lt;/a&gt;&lt;/p&gt;<br>{% endif %}<br><br>{% endblock %}</pre><p>10. Collect static files:</p><pre>python manage.py collectstatic</pre><p><strong><em>Dockerfile</em>:</strong></p><p>Now, Create a <em>Dockerfile </em>in the<em> app </em>directory. The <em>Dockerfile </em>plays a crucial role in the containerization of applications using Docker. It serves as a set of instructions for building a Docker image, which is a lightweight, standalone, and executable package that includes all the necessary dependencies and configurations to run a software application. Below are the complete instructions which are required:</p><p>1. <strong>Base Image:</strong></p><p>It starts with a slim Debian-based Python 3.11.4 image.</p><pre>FROM python:3.11.4-slim-buster</pre><p>2. <strong>Environment Variables:</strong></p><p>Sets environment variables to control Python behavior and define the application’s home directory.</p><pre>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONUNBUFFERED 1<br>ENV HOME=/home/app<br>ENV APP_HOME=${HOME}/web</pre><p>3. <strong>User and Directories:</strong></p><p>Creates a user and necessary directories for the application.</p><pre>RUN mkdir -p $HOME &amp;&amp; \<br>    addgroup --system app &amp;&amp; \<br>    adduser --system --group app &amp;&amp; \<br>    mkdir $APP_HOME ${APP_HOME}/static ${APP_HOME}/media</pre><p>4. <strong>Working Directory:</strong></p><p>Sets the working directory for subsequent commands.</p><pre>WORKDIR $APP_HOME</pre><p>5. <strong>Copy Requirements and Install Dependencies:</strong></p><p>Copies the application’s requirements and installs Python dependencies.</p><pre>COPY ./requirements.txt $APP_HOME<br>RUN pip install --upgrade pip &amp;&amp; pip install --no-cache-dir -r requirements.txt</pre><p>6. <strong>Install Other Dependencies:</strong></p><p>Installs additional system dependencies (netcat in this case). To check the availability of our database service.</p><pre>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends netcat &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>7. <strong>Copy Entrypoint Script:</strong></p><p>Copies an entrypoint script used to initialize the application.</p><pre>COPY ./entrypoint.sh $APP_HOME</pre><p>8. <strong>Set Permissions and Ownership:</strong></p><p>Sets ownership and permissions for the app user on the app directory.</p><pre>RUN chown -R app:app $APP_HOME &amp;&amp; chmod -R 777 $APP_HOME</pre><p>9. <strong>Switch to App User:</strong></p><p>Switches to the app user for subsequent commands.</p><pre>USER app</pre><p>10. <strong>Collect Static Files:</strong></p><p>Collects static files for the Django application.</p><pre>RUN python manage.py collectstatic --no-input --clear</pre><p>11. <strong>Expose Port:</strong></p><p>Exposes port 8000 for the application that means our application will listen at port 8000.</p><pre>EXPOSE 8000</pre><p>12. <strong>Healthcheck:</strong></p><p>Configures a health check using curl to verify the application&#39;s health.</p><pre>HEALTHCHECK --interval=5s \<br>            --timeout=3s \<br>            CMD curl --fail http://localhost:8000/health-check || exit 1</pre><p>13. <strong>Entrypoint and CMD:</strong></p><p>Sets the entrypoint script and the default command to run the Gunicorn server for the Django application.</p><ul><li><em>Number of Workers = (Number of CPU Cores × 2) + 1.</em></li><li><em>For ASGI based application, Use “uvicorn” as worker class instead of “gunicorn”.</em></li></ul><pre>ENTRYPOINT [&quot;/home/app/web/entrypoint.sh&quot;]<br>CMD [&quot;gunicorn&quot;, &quot;--workers&quot;, &quot;1&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;, &quot;--timeout&quot;, &quot;90&quot;, &quot;--access-logfile&quot;, &quot;/home/app/web/access.log&quot;, &quot;--error-logfile&quot;, &quot;/home/app/web/error.log&quot;, &quot;myproject.wsgi:application&quot;]</pre><p><strong><em>Finally, Below is the complete Dockerfile</em>:</strong></p><pre># Pull python base image<br>FROM python:3.11.4-slim-buster<br><br># Set environment variables<br>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONUNBUFFERED 1<br><br>ENV HOME=/home/app<br>ENV APP_HOME=${HOME}/web<br><br># Create app user and necessary directories<br>RUN mkdir -p $HOME &amp;&amp; \<br>    addgroup --system app &amp;&amp; \<br>    adduser --system --group app &amp;&amp; \<br>    mkdir $APP_HOME ${APP_HOME}/static ${APP_HOME}/media<br><br># Set work directory<br>WORKDIR $APP_HOME<br><br># Copy requirements.txt<br>COPY ./requirements.txt $APP_HOME<br><br># Install python dependencies<br>RUN pip install --upgrade pip &amp;&amp; pip install --no-cache-dir -r requirements.txt<br><br># Install other dependencies (Debian)<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends netcat &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Copy entrypoint.sh<br>COPY ./entrypoint.sh $APP_HOME<br><br># Remove Windows line endings and make entrypoint.sh executable<br>RUN sed -i &#39;s/\r$//g&#39; ${APP_HOME}/entrypoint.sh &amp;&amp; chmod +x ${APP_HOME}/entrypoint.sh<br><br># Copy project<br>COPY . $APP_HOME<br><br># Set ownership and permissions for app user on app directory<br>RUN chown -R app:app $APP_HOME &amp;&amp; chmod -R 777 $APP_HOME<br><br># Switch to app user<br>USER app<br><br># Collect static files<br>RUN python manage.py collectstatic --no-input --clear<br><br># Expose port 8000<br>EXPOSE 8000<br><br># Healthcheck<br>HEALTHCHECK --interval=5s \<br>            --timeout=3s \<br>            CMD curl --fail http://localhost:8000/health-check || exit 1<br><br># Run entrypoint.sh<br>ENTRYPOINT [&quot;/home/app/web/entrypoint.sh&quot;]<br><br># Run application<br>CMD [&quot;gunicorn&quot;, &quot;--workers&quot;, &quot;1&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;, &quot;--timeout&quot;, &quot;90&quot;, &quot;--access-logfile&quot;, &quot;/home/app/web/access.log&quot;, &quot;--error-logfile&quot;, &quot;/home/app/web/error.log&quot;, &quot;myproject.wsgi:application&quot;]</pre><p><strong><em>entrypoint.sh</em>:</strong></p><p>Now, Create a <em>entrypoint.sh</em><strong> </strong>in the<em> app </em>directory. The <em>entrypoint.sh</em> script is a shell script used as the entry point for a Docker container running a Django application. The purpose of entrypoint.sh is to handle database initialization (specifically for PostgreSQL) by waiting for the database server to be ready before migrating the database schema. After the initialization steps, it executes the command provided as arguments to the script, which usually starts the main application server. This script is commonly used in Docker images to ensure proper coordination between the Django application and its database during container startup. Below is the break down of the script:</p><ol><li><strong>Check Database Type:</strong></li></ol><p>Checks if the specified database type is PostgreSQL. If so, it enters a loop to wait until the PostgreSQL server is reachable at the specified host and port.</p><pre>if [ &quot;$DATABASE&quot; = &quot;postgres&quot; ]<br>then<br>    # Wait for PostgreSQL to start<br>    echo &quot;Waiting for postgres...&quot;<br>    while ! nc -z $SQL_HOST $SQL_PORT; do<br>      sleep 0.1<br>    done<br><br>    echo &quot;PostgreSQL started&quot;<br>fi</pre><p>2. <strong>Database Migration:</strong></p><p>Once the PostgreSQL server is available or if the database type is not PostgreSQL, it runs Django’s makemigrations&amp; migrate commands to apply any pending database migrations.</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>3. <strong>Execute Command:</strong></p><p>Executes the command passed to the script. This is typically the command to start the application server (e.g., Gunicorn) along with any additional parameters.</p><pre>exec &quot;$@&quot;</pre><p><strong><em>Finally, Below is the complete entrypoint.sh</em>:</strong></p><pre>#!/bin/sh<br><br>if [ &quot;$DATABASE&quot; = &quot;postgres&quot; ]<br>then<br>    echo &quot;Waiting for postgres...&quot;<br><br>    while ! nc -z $SQL_HOST $SQL_PORT; do<br>      sleep 0.1<br>    done<br><br>    echo &quot;PostgreSQL started&quot;<br>fi<br><br>python manage.py makemigrations<br>python manage.py migrate<br><br>exec &quot;$@&quot;</pre><p><strong><em>compose.yaml</em>:</strong></p><p>Now, Create a <em>compose.yaml</em> file in the<em> myproject-on-docker </em>directory. A Docker Compose file (compose.yml) is used to define and manage multi-container Docker applications. It allows you to define the services, networks, and volumes of an application in a single file, making it easier to configure and manage complex setups. Now, Let&#39;s define all the required services in <em>compose.yaml</em>:</p><ol><li><strong>Services Section:</strong></li></ol><p>Defines the services that make up the application.</p><p>2. <strong>Web Service:</strong></p><ul><li><strong>Build Configuration:</strong></li></ul><pre>build:<br>  context: ./app</pre><p>Specifies that the Docker image for the web service should be built from the Dockerfile located in the ./app directory.</p><ul><li><strong>Volumes:</strong></li></ul><pre>volumes:<br>  - static-volume:/home/app/web/static<br>  - media-volume:/home/app/web/media</pre><p>Mounts the static-volume volume to the /home/app/web/static directory and the media-volume volume to the /home/app/web/media directory in the web service container.</p><ul><li><strong>Ports Mapping:</strong></li></ul><pre>ports:<br>  - 8000:8000</pre><p>Maps port 8000 on the host to port 8000 in the web service container.</p><ul><li><strong>Environment File:</strong></li></ul><pre>env_file:<br>  - ./.env</pre><p>Specifies an environment file (./.env) to be used for environment variable configuration in the web service.</p><ul><li><strong>Dependency on Database Service:</strong></li></ul><pre>depends_on:<br>  - db</pre><p>Indicates that the web service depends on the db service and should wait for it to be ready before starting.</p><p>3. <strong>Db Service:</strong></p><ul><li><strong>Docker Image:</strong></li></ul><pre>image: postgres:16</pre><p>Specifies the Docker image (postgres:16) to be used for the db service.</p><ul><li><strong>Volumes:</strong></li></ul><pre>volumes:<br>  - postgres-data:/var/lib/postgresql/data/</pre><p>Mounts the postgres-data volume to the /var/lib/postgresql/data/ directory in the db service container.</p><ul><li><strong>Ports Mapping:</strong></li></ul><pre>ports:<br>  - 5432:5432</pre><p>Maps port 5432 on the host to port 5432 in the db service container.</p><ul><li><strong>Environment File:</strong></li></ul><pre>env_file:<br>  - ./.env.db</pre><p>Specifies an environment file (./.env.db) for environment variable configuration in the db service.</p><p>4. <strong>Nginx Service:</strong></p><ul><li><strong>Build Configuration:</strong></li></ul><pre>build: ./nginx</pre><p>Specifies that the Docker image for the nginx service should be built from the Dockerfile located in the ./nginx directory.</p><ul><li><strong>Volumes:</strong></li></ul><pre>volumes:<br>  - static-volume:/home/app/web/static<br>  - media-volume:/home/app/web/media</pre><p>Mounts the static-volume volume to the /home/app/web/static directory and the media-volume volume to the /home/app/web/media directory in the nginx service container.</p><ul><li><strong>Ports Mapping:</strong></li></ul><pre>ports:<br>  - 80:80</pre><p>Maps port 80 on the host to port 80 in the nginx service container.</p><ul><li><strong>Dependency on Web Service:</strong></li></ul><pre>depends_on:<br>  - web</pre><p>Indicates that the nginx service depends on the web service and should wait for it to be ready before starting.</p><p>5. <strong>Volumes Section:</strong></p><ul><li><strong>Volume Definitions:</strong></li></ul><pre>volumes:<br>  postgres-data:<br>  static-volume:<br>  media-volume:</pre><p>Defines three named volumes (postgres-data,static-volume and media-volume). These volumes are used to persist data between container restarts and share data between services.</p><p><strong><em>Finally, Below is the complete compose.yaml</em>:</strong></p><pre>services:<br>  web:<br>    build:<br>      context: ./app<br>    volumes:<br>      - static-volume:/home/app/web/static<br>      - media-volume:/home/app/web/media<br>    ports:<br>      - 8000:8000<br>    env_file:<br>      - ./.env<br>    depends_on:<br>      - db<br>  db:<br>    image: postgres:16<br>    volumes:<br>      - postgres-data:/var/lib/postgresql/data/<br>    ports:<br>      - 5432:5432<br>    env_file:<br>      - ./.env.db<br>  nginx:<br>    build: ./nginx<br>    volumes:<br>      - static-volume:/home/app/web/static<br>      - media-volume:/home/app/web/media<br>    ports:<br>      - 80:80<br>    depends_on:<br>      - web<br><br>volumes:<br>  postgres-data:<br>  static-volume:<br>  media-volume:</pre><p><strong>Nginx:</strong></p><p>Now, Create a <em>nginx </em>directory inside the <em>myproject-on-docker</em> directory. And inside the <em>nginx </em>directory create a <em>Dockerfile </em>and a<em> nginx.conf </em>file. The nginx.conf file is a configuration file for the Nginx web server. It plays a crucial role in defining how Nginx handles incoming requests, proxying them to the appropriate backend services, and serving static files. Now, Let&#39;s understand how to configure nginx:</p><p><strong><em>Dockerfile:</em></strong></p><ol><li><strong>Base Image:</strong></li></ol><pre>FROM nginx:1.25</pre><p><strong>Importance:</strong></p><ul><li>Specifies the base image to use, the official Nginx image with version 1.25.</li></ul><p><strong>Role:</strong></p><ul><li>Sets the foundation for the custom image, inheriting the Nginx image and its configurations.</li></ul><p>2. <strong>Remove default Nginx configuration file:</strong></p><pre>RUN rm /etc/nginx/conf.d/default.conf</pre><p><strong>Importance:</strong></p><ul><li>Removes the default Nginx configuration file.</li></ul><p><strong>Role:</strong></p><ul><li>Customizes the Nginx configuration by removing the default settings to allow for a user-defined configuration.</li></ul><p>3. <strong>Copy custom Nginx configuration file:</strong></p><pre>COPY nginx.conf /etc/nginx/conf.d</pre><p><strong>Importance:</strong></p><ul><li>Copies the local nginx.conf file to the /etc/nginx/conf.d directory within the container.</li></ul><p><strong>Role:</strong></p><ul><li>Introduces a custom Nginx configuration file, allowing users to define specific configurations for their application.</li></ul><p>4. <strong>Expose Port:</strong></p><pre>EXPOSE 80</pre><p><strong>Importance:</strong></p><ul><li>Informs Docker that the container will listen on port 80 at runtime.</li></ul><p><strong>Role:</strong></p><ul><li>Declares the port that Nginx will use, making it accessible externally.</li></ul><p><strong><em>Finally, Below is the complete Dockerfile for Nginx:</em></strong></p><pre>FROM nginx:1.25<br><br>RUN rm /etc/nginx/conf.d/default.conf<br><br>COPY nginx.conf /etc/nginx/conf.d<br><br>EXPOSE 80</pre><p><strong><em>nginx.conf:</em></strong></p><ol><li><strong>Upstream Block:</strong></li></ol><pre>upstream myproject {<br>    server web:8000;<br>}</pre><p><strong>Purpose:</strong></p><ul><li>Defines an upstream server group named myproject.</li><li>Specifies that it consists of a single server named web running on port 8000.</li></ul><p><strong>Role:</strong></p><ul><li>This block defines a connection pool to the Django application (web) using the specified port.</li></ul><p>2. <strong>Server Block:</strong></p><pre>server {<br>    listen 80;</pre><p><strong>Purpose:</strong></p><ul><li>Defines an Nginx server block to handle HTTP requests on port 80.</li></ul><p><strong>Role:</strong></p><ul><li>Listens on port 80, which is the default port for HTTP traffic.</li></ul><p>3. <strong>Root Location Block:</strong></p><pre>location / {<br>    proxy_pass http://myproject;<br>    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_set_header Host $host;<br>    proxy_redirect off;<br>}</pre><p><strong>Purpose:</strong></p><ul><li>Handles requests to the root URL (/).</li><li>Proxies requests to the upstream server group (myproject).</li><li>Sets headers for proxying (X-Forwarded-For, Host), ensuring the backend receives relevant information about the client.</li></ul><p><strong>Role:</strong></p><ul><li>Forwards requests to the Django application server (myproject).</li></ul><p>4. <strong>Static Location Block:</strong></p><pre>location /static/ {<br>    alias /home/app/web/static/;<br>}</pre><p><strong>Purpose:</strong></p><ul><li>Handles requests to the /static/ path.</li><li>Serves static files directly from the specified directory.</li></ul><p><strong>Role:</strong></p><ul><li>Directly serves static files from the specified directory without passing the request to the upstream server.</li></ul><p>5. <strong>Media Location Block:</strong></p><pre>location /media/ {<br>  alias /home/app/web/media/;<br>}</pre><p><strong>Purpose:</strong></p><ul><li>Handles requests to the /media/ path.</li><li>Serves media files directly from the specified directory.</li></ul><p><strong>Role:</strong></p><ul><li>Directly serves media files from the specified directory without passing the request to the upstream server.</li></ul><p><strong><em>Finally, Below is the complete nginx.conf</em>:</strong></p><pre>upstream myproject {<br>    server web:8000;<br>}<br><br>server {<br><br>    listen 80;<br><br>    location / {<br>        proxy_pass http://myproject;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header Host $host;<br>        proxy_redirect off;<br>    }<br><br>    location /static/ {<br>        alias /home/app/web/static/;<br>    }<br><br>    location /media/ {<br>        alias /home/app/web/media/;<br>    }<br><br>}</pre><p><strong>Jenkinsfile:</strong></p><p>The Jenkinsfile is a configuration file written in Groovy that defines a Jenkins Pipeline. It provides a way to express the entire build process as code, enabling continuous integration and delivery. Jenkinsfile defines a pipeline with stages for checking out code, cleaning up previous containers, building and testing the application, deploying it using Docker Compose, and performing post-build cleanup actions. It encapsulates the entire CI/CD process, allowing for automation and repeatability. Now, Let’s make a pipeline using groovy script:</p><ol><li><strong>Pipeline Block:</strong></li></ol><p><strong>Purpose:</strong></p><ul><li>Defines the entire Jenkins Pipeline.</li></ul><p><strong>Role:</strong></p><ul><li>Specifies the agent, stages, and post-actions for the pipeline.</li></ul><p>2. <strong>Agent Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Specifies that the pipeline can run on any available agent.</li></ul><p><strong>Role:</strong></p><ul><li>Allows flexibility in choosing an available Jenkins agent to execute the pipeline.</li></ul><p>3. <strong>Stages Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Divides the build process into different stages.</li></ul><p><strong>Role:</strong></p><ul><li>Organizes the build process into distinct phases, providing better visibility and control.</li></ul><p>4. <strong>Stage(‘Checkout’) Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Checks out the source code from the version control system.</li></ul><p><strong>Role:</strong></p><ul><li>Retrieves the codebase for the subsequent build and test stages.</li></ul><p>5. <strong>Stage(‘Cleanup Previous Containers’) Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Terminates and removes any existing Docker containers.</li></ul><p><strong>Role:</strong></p><ul><li>Ensures a clean environment before building and testing the application.</li></ul><p>6. <strong>Stage(‘Build and Test’) Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Builds Docker images and runs tests inside a Docker container.</li></ul><p><strong>Role:</strong></p><ul><li>Constructs the Docker images required for the application and executes tests.</li></ul><p>7. <strong>Stage(‘Deploy’) Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Deploys the application using Docker Compose.</li></ul><p><strong>Role:</strong></p><ul><li>Starts the application in a detached mode, making it accessible.</li></ul><p>8. <strong>Post Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Defines post-build actions that should always be executed.</li></ul><p><strong>Role:</strong></p><ul><li>Contains cleanup actions, such as pruning Docker resources.</li></ul><p>9. <strong>Always Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Specifies that the contained steps should be executed regardless of the build result.</li></ul><p><strong>Role:</strong></p><ul><li>Ensures that cleanup actions are performed even if earlier stages fail.</li></ul><p>10. <strong>Script Block:</strong></p><p><strong>Purpose:</strong></p><ul><li>Allows the execution of shell scripts.</li></ul><p><strong>Role:</strong></p><ul><li>Executes various shell commands, including Docker and Jenkins CLI commands.</li></ul><p>11. <strong>Docker Commands:</strong></p><p>1. <strong><em>docker-compose down:</em></strong></p><p><strong>Purpose:</strong></p><ul><li>Stops and removes Docker containers defined in the compose.yaml file.</li></ul><p><strong>Role:</strong></p><ul><li>Ensures a clean environment before building and testing.</li></ul><p>2. <strong><em>docker-compose build:</em></strong></p><p><strong>Purpose:</strong></p><ul><li>Builds Docker images based on the instructions in the Dockerfile and compose.yaml.</li></ul><p><strong>Role:</strong></p><ul><li>Prepares the Docker images required for the application.</li></ul><p>3. <strong><em>docker-compose run web python manage.py test:</em></strong></p><p><strong>Purpose:</strong></p><ul><li>Runs Django tests inside a Docker container.</li></ul><p><strong>Role:</strong></p><ul><li>Executes tests for the Django application.</li></ul><p>4. <strong><em>docker-compose up -d:</em></strong></p><p><strong>Purpose:</strong></p><ul><li>Starts Docker containers in detached mode.</li></ul><p><strong>Role:</strong></p><ul><li>Deploys the application, making it accessible.</li></ul><p>12. <strong>Docker System Prune:</strong></p><p><strong><em>docker system prune -a — volumes:</em></strong></p><p><strong>Purpose:</strong></p><ul><li>Cleans up unused Docker resources, including images, containers, and volumes.</li></ul><p><strong>Role:</strong></p><ul><li>Helps prevent the accumulation of unused resources and keeps the environment clean.</li></ul><p><strong><em>Finally, Below is the complete Jenkinsfile</em>:</strong></p><pre>pipeline {<br>    agent any<br><br>    stages {<br>        stage(&#39;Checkout&#39;) {<br>            steps {<br>                script {<br>                    checkout scm<br>                }<br>            }<br>        }<br><br>        stage(&#39;Cleanup Previous Containers&#39;) {<br>            steps {<br>                script {<br>                    sh &#39;docker-compose down&#39;<br>                }<br>            }<br>        }<br><br>        stage(&#39;Build and Test&#39;) {<br>            steps {<br>                script {<br>                    sh &#39;docker-compose build&#39;<br>                    sh &#39;docker-compose run web python manage.py test&#39;<br>                }<br>            }<br>        }<br><br>        stage(&#39;Deploy&#39;) {<br>            steps {<br>                script {<br>                    sh &#39;docker-compose up -d&#39;<br>                }<br>            }<br>        }<br>    }<br><br>    post {<br>        always {<br>            script {<br>                // Clean up Docker resources<br>                sh &#39;echo &quot;y&quot; | docker system prune -a --volumes&#39;<br>            }<br>        }<br>    }<br><br>}</pre><p><strong><em>.dockerignore:</em></strong></p><p>The .dockerignore file is used to specify files and directories that should be excluded when building a Docker image. It helps in reducing the size of the image and improving the build performance by avoiding unnecessary files and directories.</p><p><strong>Importance:</strong></p><ul><li>Reducing the size of the Docker image is crucial for efficient image distribution and deployment.</li><li>Avoiding unnecessary files accelerates the Docker build process, as only relevant files are considered.</li></ul><p><strong><em>Below is the complete .dockerignore</em>:</strong></p><pre># Exclude macOS .DS_Store files<br>**/.DS_Store<br><br># Exclude Python cache directories<br>**/__pycache__<br><br># Exclude Python virtual environment<br>**/.venv<br><br># Exclude Eclipse files<br>**/.classpath<br>**/.project<br>**/.settings<br><br># Exclude Visual Studio Code files<br>**/.vscode<br><br># Exclude Visual Studio files<br>**/.vs<br>**/*.dbmdl<br>**/*.jfm<br>**/*.*proj.user<br><br># Exclude compiled binaries<br>**/bin<br>**/obj<br><br># Exclude Helm charts<br>**/charts<br><br># Exclude Docker Compose files<br>**/docker-compose*<br>**/compose*<br><br># Exclude Dockerfile<br>**/Dockerfile*<br><br># Exclude Node.js modules<br>**/node_modules<br>**/npm-debug.log<br><br># Exclude secrets and values files<br>**/secrets.dev.yaml<br>**/values.dev.yaml<br><br># Exclude license and README files<br>LICENSE<br>README.md</pre><p><strong><em>.gitignore:</em></strong></p><p>The .gitignore file is used to specify files and directories that should be excluded from version control when using Git. It helps in avoiding the unintentional inclusion of temporary files, build artifacts, and environment-specific configurations in the Git repository.</p><p><strong>Importance:</strong></p><ul><li>Ensures that files and directories specific to individual developers or local environments are not committed to the shared Git repository.</li><li>Reduces repository size and keeps the repository focused on source code and essential configuration.</li></ul><p><strong><em>Below is the complete .gitignore</em>:</strong></p><pre># Exclude Python compiled files<br>*.pyc<br><br># Exclude Python cache directory<br>__pycache__<br><br># Exclude macOS system files<br>.DS_Store<br><br># Exclude environment-specific configuration files<br>.env<br>.env.db</pre><p>Now, Initialize git into the <em>myproject-on-docker </em>directory. Go to <a href="https://github.com/">github.com</a> and Create a new repository named <em>myproject-on-docker. </em>Push the entire code into the repository using below commands:</p><pre>git init<br>git add .<br>git commit -m &quot;myproject on docker&quot;<br>git branch -M main<br>git remote add origin https://github.com/&lt;username&gt;/&lt;repository-name&gt;.git<br>git push -u origin main</pre><p>Now, Create an Access Token of your github account. Because Jenkins need to communicate with your github account to access the project repository to pull the code in his workspace which is required to replicate the new changes on live.</p><p>To create an access token, follow below flow:</p><p>settings → <a href="https://github.com/settings/apps">Developer Settings</a> → Personal access tokens → Tokens (classic) → Generate new token → Generate new token (classic)</p><p><strong>Note:</strong> jenkins-user</p><p><strong>Expiration:</strong> No Expiration</p><p><strong>Select scopes</strong>: repo, workflow, project, etc.</p><p>Now, Click on Generate token. Copy the token and paste it somewhere for the later use.</p><p>Now, Create AWS EC2 Instance. Go to AWS console and login into your AWS account as a root user. Launch a new EC2 instance with the latest Amazon Linux Machine Image and name it as <em>jenkins-server</em>. Create a new RSA type key-pair if you haven’t already and name it as <em>jenkins-key </em>with a file format (.pem). Now, Check Allow SSH traffic from, Allow HTTPS traffic from the internet, Allow HTTP traffic from the internet &amp; Add one more security group rule for Jenkins which is of type Custom TCP, Source type anywhere, &amp; Port range of 8080 in the security group in Network settings. Then, your machine will be ready within few seconds.</p><p>Now, take access of your machine using PuTTY &amp; PuTTYgen or through SSH:</p><pre>ssh -i &lt;your-key-pair.pem&gt; ec2-user@&lt;your-instance-ip&gt;</pre><p>Now, become a root user:</p><pre>sudo su</pre><p>Install &amp; Start the Docker Service:</p><pre>yum update -y<br>yum install docker -y<br>service docker start</pre><p>Install &amp; Start the Jenkins Service using Docker &amp; Docker Hub:</p><p>Docker Hub is a cloud-based registry service provided by Docker, Inc. It serves as a central repository for containerized applications and allows users to share and distribute Docker images. Docker Hub is a key component of the Docker ecosystem, providing a platform for collaboration, image sharing, and version management.</p><p>Below commands are commonly used to quickly pull and run the Jenkins Docker image with a bridge network, having volumes to preserve Jenkins data and making Jenkins accessible on http://&lt;your-instance-public-ip&gt;:8080 in detached mode. Adjustments can be made to the ports or other configurations based on specific requirements.</p><pre>docker pull jenkins/jenkins<br>docker network create jenkins<br><br>docker run \<br>  --name jenkins-docker \<br>  --rm \<br>  --detach \<br>  --privileged \<br>  --network jenkins \<br>  --network-alias docker \<br>  --env DOCKER_TLS_CERTDIR=/certs \<br>  --volume jenkins-docker-certs:/certs/client \<br>  --volume jenkins-data:/var/jenkins_home \<br>  --publish 8080:8080 \<br>  docker:dind \<br>  --storage-driver overlay2</pre><p><strong>Unlocking Jenkins:</strong></p><p>When you first access a new Jenkins instance, you are asked to unlock it using an automatically-generated password.</p><ol><li>Browse to http://&lt;your-instance-public-ip&gt;:8080 (or whichever port you configured for Jenkins when installing it) and wait until the <strong>Unlock Jenkins</strong> page appears.</li><li>From the Jenkins console log output, copy the automatically-generated alphanumeric password (between the 2 sets of asterisks).</li></ol><p>To print the password in the console, execute below command on your terminal:</p><pre>docker exec jenkins-docker cat /var/jenkins_home/secrets/initialAdminPassword</pre><p>To get CONTAINER_ID or CONTAINER_NAME, use below command:</p><pre>docker ps</pre><p>3. On the <strong>Unlock Jenkins</strong> page, paste this password into the <strong>Administrator password</strong> field and click <strong>Continue</strong>.</p><p><strong>Customizing Jenkins with plugins:</strong></p><p>After unlocking Jenkins, the <strong>Customize Jenkins</strong> page appears. Click on <strong>Install suggested plugins </strong>to install the recommended set of plugins, which are based on most common use cases.</p><p><strong>Creating the first administrator user:</strong></p><p>Finally, after customizing Jenkins with plugins, Jenkins asks you to create your first administrator user.</p><ol><li>When the <strong>Create First Admin User</strong> page appears, specify the details for your administrator user in the respective fields and click <strong>Save and Finish</strong>.</li><li>When the <strong>Jenkins is ready</strong> page appears, click <strong>Start using Jenkins</strong>.</li></ol><p>Now, click on New Item tab. Enter an item name <em>myproject, </em>select Pipeline &amp; click OK. And fill details as mentioned below:</p><p><strong>Description:</strong> CI/CD Pipeline for myproject</p><p><strong>Pipeline:</strong> <em>Pipeline script using SCM</em></p><p><strong>SCM</strong>: <em>Git</em></p><p><strong>Repository URL:</strong> https://&lt;username&gt;:&lt;github-access-token&gt;<a href="http://twitter.com/github">@github</a>.com/&lt;repository&gt;.git</p><p><strong>Credentials:</strong> none</p><p><strong>Branches to build:</strong> */main</p><p><strong>Repository browser:</strong> (Auto)</p><p><strong>Script Path:</strong> Jenkinsfile</p><p><strong>Lightweight checkout:</strong> <em>checked</em></p><p>Then, Click on Save and the CI/CD Pipeline is now ready.</p><p><strong>Note:</strong> Now, For the first build, Go to GitHub &amp; edit Jenkinsfile and comment out all the stages except first stage which is a checkout stage then commit the changes because for the first build our only goal should be creation of Jenkins Workspace. Now, Go to Jenkins Dashboard and click on Build Now. Then, Go to Jenkins Workspace in your AWS EC2 machine using below command:</p><pre>docker exec -it jenkins-docker /bin/bash<br>cd /var/jenkins_home/workspace/myproject/</pre><p>And, now create .env &amp; .env.db files inside your workspace:</p><p><strong><em>.env (for production):</em></strong></p><pre><br>vi .env</pre><pre>DEBUG=0<br>DATABASE=postgres<br>SECRET_KEY=your-project-secret-key<br><br>SQL_HOST=db<br>SQL_PORT=5432<br>SQL_USER=myproject<br>SQL_PASSWORD=myproject<br>SQL_DATABASE=myproject_db<br>SQL_ENGINE=django.db.backends.postgresql</pre><p><strong><em>.env.db (for production):</em></strong></p><pre>vi .env.db</pre><pre>POSTGRES_USER=myproject<br>POSTGRES_PASSWORD=myproject<br>POSTGRES_DB=myproject_db</pre><p>Now, again Go to GitHub &amp; uncomment all the stages in Jenkinsfile and commit the changes. Then, Go to Jenkins Dashboard and start a new build.</p><p>Test it out at <a href="http://remote-ip/">http://</a>&lt;your-instance-public-ip&gt;.</p><p>Now whenever you have a new change in your repository, and you want to replicate the change on live, just go to Jenkins dashboard and click on Build Now then your change will be automatically replicate on live.</p><p><strong>Configuring a Custom Domain (Optional):</strong></p><p>After successfully deploying your Django application, the next step is to serve your application through a custom domain and secure it using SSL. In this section, we’ll walk through the process of configuring a custom domain and setting up SSL certificates on an AWS EC2 instance.</p><p><strong>1. Get a Domain Name:</strong></p><ul><li>Purchase a domain from any domain registrar such as GoDaddy, Namecheap, Google Domains, etc.</li></ul><p><strong>2. Configure DNS to Point to Your EC2 Instance:</strong></p><ul><li>In your domain registrar’s dashboard, you need to create <strong>DNS records</strong> that point to your EC2 instance’s <strong>Elastic IP</strong> (EIP) or public IP.</li><li>Create an <strong>A (Address) record</strong> that points your domain (e.g., myproject.com) or subdomain (e.g., www.myproject.com) to the Elastic IP or public IP of your EC2 instance.</li></ul><p><strong>Example A record:</strong></p><ul><li><strong>Name</strong>: @ (or www for a subdomain)</li><li><strong>Type</strong>: A</li><li><strong>Value</strong>: Your Elastic IP or public IP (e.g., 3.110.162.247)</li></ul><p>After setting the DNS records, it may take some time (up to 48 hours) to propagate.</p><p><strong>3. Update Allowed Hosts in Django Settings:</strong></p><p>In your Django project, update the ALLOWED_HOSTS setting in the settings.py file to include your domain name:</p><pre>ALLOWED_HOSTS = [&#39;myproject.com&#39;, &#39;www.myproject.com&#39;]</pre><p><strong>4. Run Certbot in a Separate Container</strong>:</p><p>You’ll need to run a Certbot container to obtain and manage your SSL certificates.</p><pre>docker run -it --rm --name certbot \<br>-v /etc/letsencrypt:/etc/letsencrypt \<br>-v /var/lib/letsencrypt:/var/lib/letsencrypt \<br>certbot/certbot certonly --webroot \<br>-w /home/app/web/static -d myproject.com -d www.myproject.com</pre><p>This command will create your SSL certificates and store them in /etc/letsencrypt and /var/lib/letsencrypt on your EC2 machine. You&#39;ll mount these directories into your Nginx container in the next step.</p><p><strong>5. Update Nginx Configuration</strong>:</p><ul><li>In your compose.yaml, ensure you mount the /etc/letsencrypt and /var/lib/letsencrypt volumes into your Nginx container so it can access the SSL certificates.</li></ul><p><strong><em>compose.yaml (updated):</em></strong></p><pre>services:<br>  web:<br>    build:<br>      context: ./app<br>    volumes:<br>      - static-volume:/home/app/web/static<br>      - media-volume:/home/app/web/media<br>    ports:<br>      - 8000:8000<br>    env_file:<br>      - ./.env<br>    depends_on:<br>      - db<br>  db:<br>    image: postgres:16<br>    volumes:<br>      - postgres-data:/var/lib/postgresql/data/<br>    ports:<br>      - 5432:5432<br>    env_file:<br>      - ./.env.db<br>  nginx:<br>    build: ./nginx<br>    volumes:<br>      - static-volume:/home/app/web/static<br>      - media-volume:/home/app/web/media<br>      - /etc/letsencrypt:/etc/letsencrypt<br>      - /var/lib/letsencrypt:/var/lib/letsencrypt<br>    ports:<br>      - 80:80<br>      - 443:443<br>    depends_on:<br>      - web<br><br>volumes:<br>  postgres-data:<br>  static-volume:<br>  media-volume:</pre><p><strong>6. Update the </strong><strong>nginx.conf</strong>:</p><p>Update the Nginx configuration in your Docker container to handle SSL by adding the certificate paths:</p><p><strong><em>nginx.conf (updated):</em></strong></p><pre>upstream myproject {<br>    server web:8000;<br>}<br><br>server {<br>    listen 443 ssl;<br>    server_name myproject.com www.myproject.com;<br><br>    ssl_certificate /etc/letsencrypt/live/myproject.com/fullchain.pem;<br>    ssl_certificate_key /etc/letsencrypt/live/myproject.com/privkey.pem;<br><br>    ssl_protocols TLSv1.2 TLSv1.3;<br>    ssl_prefer_server_ciphers on;<br>    ssl_ciphers HIGH:!aNULL:!MD5;<br><br>    location / {<br>        proxy_pass http://myproject;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header Host $host;<br>        proxy_redirect off;<br>    }<br><br>    location /static/ {<br>        alias /home/app/web/static/;<br>    }<br><br>    location /media/ {<br>        alias /home/app/web/media/;<br>    }<br>}<br><br>server {<br>    listen 80;<br>    server_name myproject.com www.myproject.com;<br><br>    return 301 https://$host$request_uri;<br>}</pre><p>Now, Go to Jenkins Dashboard and start a new build. Test it out at <a href="http://remote-ip/">https://</a>www.myproject.com/</p><p><strong>Note: </strong>As your db service is up through AWS EC2 Instance, if you are not running your application through docker in your local machine then change the SQL_HOST to your EC2 public IP in your .env file to run your application. Below is the .env for local development -</p><p><strong><em>.env (for local):</em></strong></p><pre>DEBUG=1<br>SECRET_KEY=your-project-secret-key<br><br>SQL_HOST=your_ec2_public_ip<br>SQL_PORT=5432<br>SQL_USER=myproject<br>SQL_PASSWORD=myproject<br>SQL_DATABASE=myproject_db<br>SQL_ENGINE=django.db.backends.postgresql</pre><p>Your <strong><em>.env.db</em></strong> remains unchanged. And now, you can simply run your application by using below command:</p><pre>python manage.py runserver</pre><p>Now, Below are some other useful Docker commands that you should know:</p><p>If the container fails to start, check for errors in the logs via:</p><pre>docker-compose logs -f</pre><p>To access the database inside the container (1st way):</p><pre>docker exec -it myproject-db-1 /bin/bash<br>psql --username=myproject--dbname=myproject_db</pre><p>To access the database inside the container (2nd way):</p><pre>docker-compose exec db psql --username=myproject --dbname=myproject_db</pre><p>To access the web service inside the container:</p><pre>docker exec -it myproject-web-1 /bin/bash</pre><p>To see access logs:</p><pre>docker-compose exec web cat access.log</pre><p>To see error logs:</p><pre>docker-compose exec web cat error.log</pre><p>To access the nginx service inside the container:</p><pre>docker exec -it myproject-nginx-1 /bin/bash</pre><p>To see all running containers:</p><pre>docker ps</pre><p>To see all docker images:</p><pre>docker images</pre><p>To build the images and run the containers (manually):</p><pre>docker-compose up -d --build</pre><p>To remove or bring down volumes along with the containers once done (manually):</p><pre>docker-compose down -v</pre><p>Now, you can find the entire code which we have discussed yet on my GitHub Public Repository. Below is the URL:</p><p><a href="https://github.com/GargAnshu9468/myproject-on-docker">GitHub - GargAnshu9468/myproject-on-docker: This project demonstrates Dockerizing a Django app with PostgreSQL using Docker, Nginx, and Gunicorn. Its structured setup includes Django app, Nginx config, Dockerfiles, and env files. The Jenkinsfile establishes a CI/CD pipeline for flexible branch-based builds. Explore efficient Python and Django app management with Docker containers.</a></p><p>Feel free to explore it and don’t forgot to share your thoughts.</p><p>That’s it! Finally, We wrap up this blog. Thank you for joining me. I hope you have enjoyed this blog and it actually going to help you. Good Luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6987b6bd1a40" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/ci-cd-pipeline-for-a-django-application-using-postgresql-gunicorn-nginx-docker-jenkins-6987b6bd1a40">CI/CD Pipeline for a Django application using PostgreSQL, Gunicorn, Nginx, Docker &amp; Jenkins</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>