<?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 Soyoyeolayinka on Medium]]></title>
        <description><![CDATA[Stories by Soyoyeolayinka on Medium]]></description>
        <link>https://medium.com/@soyoyeolayinka35?source=rss-ae12ae1d3411------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NYXz0tNDwD8-l8Ed</url>
            <title>Stories by Soyoyeolayinka on Medium</title>
            <link>https://medium.com/@soyoyeolayinka35?source=rss-ae12ae1d3411------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:11:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@soyoyeolayinka35/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 SwiftDeploy: A Manifest-Driven DevOps Deployment Tool with Docker, Nginx, OPA, Metrics…]]></title>
            <link>https://medium.com/@soyoyeolayinka35/building-swiftdeploy-a-manifest-driven-devops-deployment-tool-with-docker-nginx-opa-metrics-98304619be7a?source=rss-ae12ae1d3411------2</link>
            <guid isPermaLink="false">https://medium.com/p/98304619be7a</guid>
            <category><![CDATA[devops-tool]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[side-project]]></category>
            <category><![CDATA[devops-practice]]></category>
            <category><![CDATA[devops-automation-tools]]></category>
            <dc:creator><![CDATA[Soyoyeolayinka]]></dc:creator>
            <pubDate>Thu, 07 May 2026 12:14:24 GMT</pubDate>
            <atom:updated>2026-05-07T12:14:24.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building SwiftDeploy: A Manifest-Driven DevOps Deployment Tool with Docker, Nginx, OPA, Metrics, Canary Releases, Chaos Testing, and Auditing</h3><h3>Introduction</h3><p>For this project, I built <strong>SwiftDeploy</strong>, a DevOps automation tool that deploys a containerized Python API behind an Nginx reverse proxy using Docker Compose.</p><p>The project was completed in two stages.</p><p>In <strong>Stage 4A</strong>, I built the deployment engine. The tool could read a single manifest.yaml file, generate Docker Compose and Nginx configuration files, deploy a containerized Flask API, promote the app between stable and canary modes, inject controlled chaos, and tear down the environment.</p><p>In <strong>Stage 4B</strong>, I extended the project with observability, policy enforcement, and auditing. This meant SwiftDeploy no longer deployed blindly. It could now check metrics, ask Open Policy Agent whether an action was safe, block unsafe deployments or promotions, and record operational history.</p><p>I like to describe the final version of SwiftDeploy this way:</p><p>SwiftDeploy has <strong>eyes</strong>, because it exposes and reads metrics.</p><p>SwiftDeploy has a <strong>brain</strong>, because it uses OPA to make policy decisions.</p><p>SwiftDeploy has <strong>memory</strong>, because it stores status history and generates audit reports.</p><p>The final tool demonstrates practical DevOps concepts including Docker, Docker Compose, Nginx reverse proxying, manifest-driven configuration, Prometheus-style metrics, policy-as-code, canary release safety, chaos testing, and auditing.</p><h3>Final Architecture</h3><p>The final system has three main containers:</p><ol><li>1. A Flask/Gunicorn API container.</li><li>2. An Nginx reverse proxy container.</li><li>3. An Open Policy Agent sidecar container.</li></ol><p>Application traffic flows through Nginx:</p><p><strong>TEXT</strong></p><pre>Client / Browser / curl<br>        |<br>        v<br>Nginx reverse proxy<br>localhost:8080<br>        |<br>        v<br>Internal Docker network<br>        |<br>        v<br>Flask/Gunicorn API<br>port 3000 inside container</pre><p>Policy decisions flow through the SwiftDeploy CLI:</p><p><strong>TEXT</strong></p><pre>SwiftDeploy CLI<br>        |<br>        | collects host stats or service metrics<br>        v<br>Open Policy Agent<br>localhost:8181<br>        |<br>        | returns allow/deny decision with reasons<br>        v<br>SwiftDeploy CLI<br>        |<br>        | deploys or blocks action<br>        v<br>Docker Compose stack</pre><p>The app container is not exposed directly to the host. Only Nginx publishes a public application port. OPA is reachable by the CLI on localhost:8181, but it is not exposed through Nginx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ZA3lgJ4C_ipPPnflKwCnSA.jpeg" /><figcaption>SwiftDeploy architecture showing the CLI, OPA sidecar, Nginx reverse proxy, and internal Flask API container.</figcaption></figure><h3>Project Folder Structure</h3><p>I created the project as a CLI-based deployment tool.</p><p>The final structure looked like this:</p><p><strong>TEXT</strong></p><pre>swiftdeploy/<br>├── app/<br>│   ├── app.py<br>│   └── requirements.txt<br>├── generated/<br>│   ├── docker-compose.yml<br>│   └── nginx.conf<br>├── policies/<br>│   ├── infrastructure.rego<br>│   └── canary.rego<br>├── templates/<br>│   ├── docker-compose.yml.tpl<br>│   └── nginx.conf.tpl<br>├── Dockerfile<br>├── BLOG_POST.md<br>├── README.md<br>├── audit_report.md<br>├── history.jsonl<br>├── manifest.yaml<br>└── swiftdeploy</pre><p>The most important design decision was that manifest.yaml remains the single source of truth. I do not manually edit the generated Docker Compose or Nginx files. Instead, the CLI reads the manifest and generates those files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ZA3lgJ4C_ipPPnflKwCnSA.jpeg" /><figcaption>SwiftDeploy project structure showing the app, templates, generated files, policies, manifest, and CLI script.</figcaption></figure><h3>Step 1: Creating the Manifest as the Source of Truth</h3><p>The manifest.yaml file controls the deployment.</p><p>Here is the important part of the manifest:</p><p><strong>YAML</strong></p><pre>project:<br>  name: swiftdeploy<br>  version: &quot;1.0.0&quot;<br>  contact: &quot;devops@example.com&quot;</pre><pre>services:<br>  name: swiftdeploy-app<br>  image: swift-deploy-1-node:latest<br>  port: 3000<br>  mode: stable<br>  app_version: &quot;1.0.0&quot;<br>  restart_policy: unless-stopped</pre><pre>nginx:<br>  image: nginx:latest<br>  port: 8080<br>  proxy_timeout: 10</pre><pre>network:<br>  name: swiftdeploy-net<br>  driver_type: bridge</pre><pre>logs:<br>  volume_name: swiftdeploy-logs</pre><pre>policy:<br>  opa_url: <a href="http://localhost:8181/">http://localhost:8181</a><br>  infrastructure:<br>    min_disk_free_gb: 10<br>    max_cpu_load: 2.0<br>  canary:<br>    max_error_rate: 0.01<br>    max_p99_latency_seconds: 0.5<br>    window_seconds: 30</pre><p>This file controls:</p><ul><li>the project name and version;</li><li>the Docker image name;</li><li>the app port;</li><li>whether the app runs in `stable` or `canary` mode;</li><li>the Nginx public port;</li><li>the Docker network name;</li><li>the OPA URL;</li><li>infrastructure policy thresholds;</li><li>canary promotion thresholds.</li></ul><p>The policy thresholds are deliberately stored in manifest.yaml, not inside the Rego policy files. This makes the policies reusable across environments.</p><h3>Step 2: Building the Flask API</h3><p>The application is a simple Flask API. It exposes:</p><ul><li>`/`</li><li>`/healthz`</li><li>`/metrics`</li><li>`/chaos`</li></ul><p>The application reads its mode and version from environment variables:</p><p><strong>PYTHON</strong></p><pre>APP_VERSION = os.getenv(&quot;APP_VERSION&quot;, &quot;1.0.0&quot;)<br>MODE = os.getenv(&quot;MODE&quot;, &quot;stable&quot;)<br>APP_PORT = int(os.getenv(&quot;APP_PORT&quot;, &quot;3000&quot;))</pre><p>The root endpoint returns the current app mode:</p><p><strong>PYTHON</strong></p><pre>@app.route(&quot;/&quot;, methods=[&quot;GET&quot;])<br>def index():<br>    chaos_response = apply_chaos_if_enabled()<br>    if chaos_response:<br>        return chaos_response</pre><pre>    return jsonify({<br>        &quot;message&quot;: &quot;Welcome to SwiftDeploy API&quot;,<br>        &quot;mode&quot;: MODE,<br>        &quot;version&quot;: APP_VERSION,<br>        &quot;timestamp&quot;: datetime.now(timezone.utc).isoformat()<br>    }), 200</pre><p>The health endpoint returns service health:</p><p><strong>PYTHON</strong></p><pre>@app.route(&quot;/healthz&quot;, methods=[&quot;GET&quot;])<br>def healthz():<br>    uptime = round(time.time() - START_TIME, 2)</pre><pre>    return jsonify({<br>        &quot;status&quot;: &quot;ok&quot;,<br>        &quot;mode&quot;: MODE,<br>        &quot;version&quot;: APP_VERSION,<br>        &quot;uptime_seconds&quot;: uptime<br>    }), 200</pre><p>I tested it with:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8080/healthz</pre><p>Example successful response:</p><p><strong>JSON</strong></p><pre>{<br>  &quot;mode&quot;: &quot;stable&quot;,<br>  &quot;status&quot;: &quot;ok&quot;,<br>  &quot;uptime_seconds&quot;: 1458.0,<br>  &quot;version&quot;: &quot;1.0.0&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*TFDh-vrHWY4cvV8L-o8OGQ.jpeg" /><figcaption>The `/healthz` endpoint confirming the app is healthy and running in stable mode.</figcaption></figure><h3>Step 3: Adding Observability with `/metrics`</h3><p>Stage 4B required the app to expose metrics in Prometheus text format.</p><p>The required metrics were:</p><p><strong>TEXT</strong></p><pre>http_requests_total<br>http_request_duration_seconds<br>app_uptime_seconds<br>app_mode<br>chaos_active</pre><p>To track requests and latency, I used Flask request hooks.</p><p>Before every request, I store the start time:</p><p><strong>PYTHON</strong></p><pre>@app.before_request<br>def start_timer():<br>    g.start_time = time.time()</pre><p>After every request, I calculate duration and update counters:</p><p><strong>PYTHON</strong></p><pre>@app.after_request<br>def record_metrics_and_headers(response):<br>    duration = time.time() - getattr(g, &quot;start_time&quot;, time.time())<br>    path = normalise_path(request.path)<br>    method = request.method<br>    status_code = str(response.status_code)</pre><pre>    label_key = (method, path, status_code)<br>    REQUEST_TOTAL[label_key] += 1</pre><pre>    histogram_key = (method, path)<br>    REQUEST_DURATION_SUM[histogram_key] += duration<br>    REQUEST_DURATION_COUNT[histogram_key] += 1</pre><pre>    for bucket in REQUEST_DURATION_BUCKETS:<br>        if duration &lt;= bucket:<br>            REQUEST_DURATION_HISTOGRAM[histogram_key][bucket] += 1</pre><pre>    if MODE == &quot;canary&quot;:<br>        response.headers[&quot;X-Mode&quot;] = &quot;canary&quot;</pre><pre>    return response</pre><p>The /metrics endpoint then exposes the values:</p><p><strong>PYTHON</strong></p><pre>@app.route(&quot;/metrics&quot;, methods=[&quot;GET&quot;])<br>def metrics():<br>    lines = []</pre><pre>    lines.append(&quot;# HELP http_requests_total Total number of HTTP requests.&quot;)<br>    lines.append(&quot;# TYPE http_requests_total counter&quot;)</pre><pre>    for (method, path, status_code), count in sorted(REQUEST_TOTAL.items()):<br>        lines.append(<br>            f&#39;http_requests_total{{method=&quot;{method}&quot;,path=&quot;{path}&quot;,status_code=&quot;{status_code}&quot;}} {count}&#39;<br>        )</pre><pre>    lines.append(&quot;&quot;)<br>    lines.append(&quot;# HELP app_uptime_seconds Application uptime in seconds.&quot;)<br>    lines.append(&quot;# TYPE app_uptime_seconds gauge&quot;)<br>    lines.append(f&quot;app_uptime_seconds {round(time.time() - START_TIME, 2)}&quot;)</pre><pre>    lines.append(&quot;&quot;)<br>    lines.append(&quot;# HELP app_mode Current app mode. 0 means stable, 1 means canary.&quot;)<br>    lines.append(&quot;# TYPE app_mode gauge&quot;)<br>    lines.append(f&quot;app_mode {1 if MODE == &#39;canary&#39; else 0}&quot;)</pre><pre>    lines.append(&quot;&quot;)<br>    lines.append(&quot;# HELP chaos_active Current chaos state. 0 means none, 1 means slow, 2 means error.&quot;)<br>    lines.append(&quot;# TYPE chaos_active gauge&quot;)<br>    lines.append(f&quot;chaos_active {chaos_code()}&quot;)</pre><pre>    return Response(&quot;\n&quot;.join(lines) + &quot;\n&quot;, mimetype=&quot;text/plain&quot;)</pre><p>I tested the metrics endpoint with:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8080/metrics</pre><p>The output included metrics like:</p><p><strong>TEXT</strong></p><pre>http_requests_total{method=&quot;GET&quot;,path=&quot;/healthz&quot;,status_code=&quot;200&quot;} 4<br>app_uptime_seconds 977.2</pre><h3>Step 4: Containerizing the API with Docker</h3><p>The app was packaged using Docker.</p><p>My Dockerfile used Python slim, installed dependencies, copied the app, and ran Gunicorn:</p><p><strong>DOCKERFILE</strong></p><pre>FROM python:3.11-slim</pre><pre>WORKDIR /app</pre><pre>RUN addgroup --system appgroup &amp;&amp; adduser --system --ingroup appgroup appuser</pre><pre>COPY app/requirements.txt .</pre><pre>RUN pip install --no-cache-dir -r requirements.txt</pre><pre>COPY app/ .</pre><pre>RUN chown -R appuser:appgroup /app</pre><pre>USER appuser</pre><pre>EXPOSE 3000</pre><pre>CMD [&quot;gunicorn&quot;, &quot;--bind&quot;, &quot;0.0.0.0:3000&quot;, &quot;app:app&quot;]</pre><p>I built the image with:</p><p><strong>BASH</strong></p><pre>docker build -t swift-deploy-1-node:latest .</pre><h3>Step 5: Generating Docker Compose from a Template</h3><p>Instead of manually writing the final Docker Compose file, I created a template:</p><p><strong>TEXT</strong></p><pre>templates/docker-compose.yml.tpl</pre><p>The CLI replaces placeholders like:</p><p><strong>TEXT</strong></p><pre>__SERVICE_IMAGE__<br>__MODE__<br>__APP_PORT__<br>__NGINX_PORT__</pre><p>with values from manifest.yaml.</p><p>A key part of the template looks like this:</p><p><strong>YAML</strong></p><pre>services:<br>  app:<br>    image: __SERVICE_IMAGE__<br>    container_name: __SERVICE_NAME__<br>    restart: __RESTART_POLICY__<br>    environment:<br>      MODE: &quot;__MODE__&quot;<br>      APP_VERSION: &quot;__APP_VERSION__&quot;<br>      APP_PORT: &quot;__APP_PORT__&quot;<br>    expose:<br>      - &quot;__APP_PORT__&quot;<br>    networks:<br>      - swiftdeploy-network<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;python -c \&quot;import urllib.request; urllib.request.urlopen(&#39;http://localhost:__APP_PORT__/healthz&#39;, timeout=3).read()\&quot;&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br>      start_period: 5s<br>    cap_drop:<br>      - ALL<br>    security_opt:<br>      - no-new-privileges:true</pre><p>Notice that the app uses:</p><p><strong>YAML</strong></p><pre>expose:<br>  - &quot;__APP_PORT__&quot;</pre><p>not:</p><p><strong>YAML</strong></p><pre>ports:</pre><p>That means the app is available only inside the Docker network. It is not directly exposed to the host.</p><h3>Step 6: Adding Nginx as the Reverse Proxy</h3><p>Nginx is the public entry point.</p><p>The Nginx template looked like this:</p><p><strong>NGINX</strong></p><pre>events {}</pre><pre>http {<br>    server {<br>        listen __NGINX_PORT__;</pre><pre>        location / {<br>            proxy_pass <a href="http://__SERVICE_NAME__:__APP_PORT__;">http://__SERVICE_NAME__:__APP_PORT__;</a><br>            proxy_set_header Host $host;<br>            proxy_set_header X-Real-IP $remote_addr;<br>            proxy_connect_timeout __PROXY_TIMEOUT__s;<br>            proxy_send_timeout __PROXY_TIMEOUT__s;<br>            proxy_read_timeout __PROXY_TIMEOUT__s;<br>            add_header X-Deployed-By &quot;swiftdeploy&quot; always;<br>        }<br>    }<br>}</pre><p>The X-Deployed-By header was useful for testing:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8080/</pre><p>Expected header:</p><p><strong>TEXT</strong></p><pre>X-Deployed-By: swiftdeploy</pre><p>This confirms that traffic is going through the generated Nginx configuration.</p><h3>Step 7: Adding OPA as the Policy Sidecar</h3><p>Stage 4B required Open Policy Agent.</p><p>I added OPA to the generated Docker Compose template:</p><p><strong>YAML</strong></p><pre>opa:<br>  image: openpolicyagent/opa:latest<br>  container_name: swiftdeploy-opa<br>  restart: __RESTART_POLICY__<br>  command:<br>    - run<br>    - --server<br>    - --addr=0.0.0.0:8181<br>    - /policies<br>  ports:<br>    - &quot;127.0.0.1:8181:8181&quot;<br>  volumes:<br>    - ../policies:/policies:ro<br>  networks:<br>    - swiftdeploy-network<br>  cap_drop:<br>    - ALL<br>  security_opt:<br>    - no-new-privileges:true</pre><p>The key line is:</p><p><strong>YAML</strong></p><pre>ports:<br>  - &quot;127.0.0.1:8181:8181&quot;</pre><p>This binds OPA to localhost only. The CLI can reach it, but it is not publicly exposed through Nginx.</p><h3>Step 8: Writing the Infrastructure Policy in Rego</h3><p>The infrastructure policy answers one question:</p><blockquote><em>Is the host safe enough for deployment?</em></blockquote><p>It checks:</p><ul><li>free disk space;</li><li>CPU load.</li></ul><p>The policy file is:</p><p><strong>TEXT</strong></p><pre>policies/infrastructure.rego</pre><p>Here is the full policy:</p><p><strong>REGO</strong></p><pre>package swiftdeploy.infrastructure</pre><pre>import rego.v1</pre><pre>default decision := {<br>  &quot;allow&quot;: false,<br>  &quot;domain&quot;: &quot;infrastructure&quot;,<br>  &quot;reason&quot;: &quot;Infrastructure policy did not complete evaluation.&quot;,<br>  &quot;violations&quot;: [&quot;no policy decision was produced&quot;]<br>}</pre><pre>disk_violation if {<br>  input.host.disk_free_gb &lt; input.thresholds.min_disk_free_gb<br>}</pre><pre>cpu_violation if {<br>  input.host.cpu_load &gt; input.thresholds.max_cpu_load<br>}</pre><pre>violations contains msg if {<br>  disk_violation<br>  msg := sprintf(&quot;Disk free is %vGB, which is below the required %vGB.&quot;, [input.host.disk_free_gb, input.thresholds.min_disk_free_gb])<br>}</pre><pre>violations contains msg if {<br>  cpu_violation<br>  msg := sprintf(&quot;CPU load is %v, which is above the allowed %v.&quot;, [input.host.cpu_load, input.thresholds.max_cpu_load])<br>}</pre><pre>decision := {<br>  &quot;allow&quot;: true,<br>  &quot;domain&quot;: &quot;infrastructure&quot;,<br>  &quot;reason&quot;: &quot;Infrastructure policy passed. Disk and CPU are within the allowed limits.&quot;,<br>  &quot;violations&quot;: []<br>} if {<br>  count(violations) == 0<br>}</pre><pre>decision := {<br>  &quot;allow&quot;: false,<br>  &quot;domain&quot;: &quot;infrastructure&quot;,<br>  &quot;reason&quot;: &quot;Infrastructure policy blocked this action.&quot;,<br>  &quot;violations&quot;: violations<br>} if {<br>  count(violations) &gt; 0<br>}</pre><p>A key requirement was that OPA must not return a bare boolean. So the policy returns:</p><p><strong>JSON</strong></p><pre>{<br>  &quot;allow&quot;: true,<br>  &quot;domain&quot;: &quot;infrastructure&quot;,<br>  &quot;reason&quot;: &quot;Infrastructure policy passed...&quot;,<br>  &quot;violations&quot;: []<br>}</pre><p>or:</p><p><strong>JSON</strong></p><pre>{<br>  &quot;allow&quot;: false,<br>  &quot;domain&quot;: &quot;infrastructure&quot;,<br>  &quot;reason&quot;: &quot;Infrastructure policy blocked this action.&quot;,<br>  &quot;violations&quot;: [<br>    &quot;Disk free is below the required limit.&quot;,<br>    &quot;CPU load is above the allowed limit.&quot;<br>  ]<br>}</pre><p>This makes policy decisions explainable.</p><h3>Step 9: Writing the Canary Safety Policy</h3><p>The canary policy answers one question:</p><blockquote><em>Is the canary healthy enough to promote?</em></blockquote><p>It checks:</p><ul><li>error rate;</li><li>P99 latency.</li></ul><p>The file is:</p><p><strong>TEXT</strong></p><pre>policies/canary.rego</pre><p>Here is the policy:</p><p><strong>REGO</strong></p><pre>package swiftdeploy.canary</pre><pre>import rego.v1</pre><pre>default decision := {<br>  &quot;allow&quot;: false,<br>  &quot;domain&quot;: &quot;canary&quot;,<br>  &quot;reason&quot;: &quot;Canary policy did not complete evaluation.&quot;,<br>  &quot;violations&quot;: [&quot;no policy decision was produced&quot;]<br>}</pre><pre>error_rate_violation if {<br>  input.metrics.error_rate &gt; input.thresholds.max_error_rate<br>}</pre><pre>latency_violation if {<br>  input.metrics.p99_latency_seconds &gt; input.thresholds.max_p99_latency_seconds<br>}</pre><pre>violations contains msg if {<br>  error_rate_violation<br>  msg := sprintf(&quot;Error rate is %v, which is above the allowed %v.&quot;, [input.metrics.error_rate, input.thresholds.max_error_rate])<br>}</pre><pre>violations contains msg if {<br>  latency_violation<br>  msg := sprintf(&quot;P99 latency is %v seconds, which is above the allowed %v seconds.&quot;, [input.metrics.p99_latency_seconds, input.thresholds.max_p99_latency_seconds])<br>}</pre><pre>decision := {<br>  &quot;allow&quot;: true,<br>  &quot;domain&quot;: &quot;canary&quot;,<br>  &quot;reason&quot;: &quot;Canary policy passed. Error rate and P99 latency are within the allowed limits.&quot;,<br>  &quot;violations&quot;: []<br>} if {<br>  count(violations) == 0<br>}</pre><pre>decision := {<br>  &quot;allow&quot;: false,<br>  &quot;domain&quot;: &quot;canary&quot;,<br>  &quot;reason&quot;: &quot;Canary policy blocked this promotion.&quot;,<br>  &quot;violations&quot;: violations<br>} if {<br>  count(violations) &gt; 0<br>}</pre><p>This policy is separate from the infrastructure policy. Each policy domain owns one question.</p><p>This matters because changing the canary policy should not require touching the infrastructure policy.</p><h3>Step 10: Querying OPA from the CLI</h3><p>The CLI sends facts to OPA and waits for a decision.</p><p>This is one of the most important functions:</p><p><strong>PYTHON</strong></p><pre>def opa_decision(manifest, domain, package_path, input_data):<br>    url = f&quot;{opa_url(https://medium.com/manifest)}/v1/data/{package_path}/decision&quot;<br>    response = http_post_json(url, {&quot;input&quot;: input_data})</pre><pre>    if not response[&quot;ok&quot;]:<br>        return {<br>            &quot;allow&quot;: False,<br>            &quot;domain&quot;: domain,<br>            &quot;reason&quot;: f&quot;OPA decision failed: {response[&#39;error_type&#39;]}&quot;,<br>            &quot;violations&quot;: [response[&quot;error&quot;] or &quot;OPA was unavailable&quot;],<br>            &quot;opa_available&quot;: False,<br>        }</pre><pre>    payload = response[&quot;json&quot;]</pre><pre>    if not isinstance(payload, dict) or &quot;result&quot; not in payload:<br>        return {<br>            &quot;allow&quot;: False,<br>            &quot;domain&quot;: domain,<br>            &quot;reason&quot;: &quot;OPA returned an invalid decision shape.&quot;,<br>            &quot;violations&quot;: [&quot;missing result object&quot;],<br>            &quot;opa_available&quot;: True,<br>        }</pre><pre>    decision = payload[&quot;result&quot;]</pre><pre>    return {<br>        &quot;allow&quot;: bool(decision.get(&quot;allow&quot;, False)),<br>        &quot;domain&quot;: decision.get(&quot;domain&quot;, domain),<br>        &quot;reason&quot;: decision.get(&quot;reason&quot;, &quot;No reason returned by OPA.&quot;),<br>        &quot;violations&quot;: decision.get(&quot;violations&quot;, []),<br>        &quot;opa_available&quot;: True,<br>    }</pre><p>The important thing here is that the CLI does not decide whether deployment is allowed. It only sends input to OPA and acts on OPA’s response.</p><p>The CLI also handles OPA failures gracefully. If OPA is unavailable, the CLI returns a clear failure reason instead of crashing silently.</p><h3>Step 11: Gating Deployment</h3><p>Before running deployment, the CLI collects host stats:</p><p><strong>PYTHON</strong></p><pre>def get_host_stats():<br>    disk = shutil.disk_usage(ROOT)</pre><pre>    try:<br>        cpu_load = os.getloadavg()[0]<br>    except Exception:<br>        cpu_load = 0.0</pre><pre>    return {<br>        &quot;disk_free_gb&quot;: round(disk.free / (1024 ** 3), 2),<br>        &quot;disk_total_gb&quot;: round(disk.total / (1024 ** 3), 2),<br>        &quot;cpu_load&quot;: round(cpu_load, 2),<br>        &quot;memory&quot;: get_memory_stats(),<br>    }</pre><p>Then it creates the input for OPA:</p><p><strong>PYTHON</strong></p><pre>def infrastructure_policy_input(manifest, action):<br>    return {<br>        &quot;action&quot;: action,<br>        &quot;host&quot;: get_host_stats(),<br>        &quot;thresholds&quot;: {<br>            &quot;min_disk_free_gb&quot;: float(required(manifest, &quot;policy.infrastructure.min_disk_free_gb&quot;)),<br>            &quot;max_cpu_load&quot;: float(required(manifest, &quot;policy.infrastructure.max_cpu_load&quot;)),<br>        },<br>    }</pre><p>If OPA denies the action, the CLI blocks deployment:</p><p><strong>PYTHON</strong></p><pre>def enforce_policy(decision, action_name):<br>    if decision[&quot;allow&quot;]:<br>        print(f&quot;[OK] Policy allowed {action_name}&quot;)<br>        return</pre><pre>    print(f&quot;[POLICY BLOCK] {action_name} was blocked by {decision[&#39;domain&#39;]} policy&quot;)<br>    print(f&quot;[REASON] {decision[&#39;reason&#39;]}&quot;)</pre><pre>    for violation in decision.get(&quot;violations&quot;, []):<br>        print(f&quot; - {violation}&quot;)</pre><pre>    raise RuntimeError(f&quot;{action_name} blocked by OPA policy&quot;)</pre><p>A successful deploy shows:</p><p><strong>TEXT</strong></p><pre>[PASS] infrastructure policy: Infrastructure policy passed. Disk and CPU are within the allowed limits.<br>[OK] Policy allowed deploy<br>[OK] Deployment complete: http://localhost:8080</pre><h3>Step 12: Testing the Hard Gate</h3><p>To prove the hard gate, I temporarily changed the disk threshold in manifest.yaml:</p><p><strong>YAML</strong></p><pre>min_disk_free_gb: 9999</pre><p>Then I ran:</p><p><strong>BASH</strong></p><pre>./swiftdeploy deploy</pre><p>Because my machine did not have 9999GB of free disk space, OPA blocked the deployment.</p><p>Expected output:</p><p><strong>TEXT</strong></p><pre>[POLICY BLOCK] deploy was blocked by infrastructure policy<br>[REASON] Infrastructure policy blocked this action.<br>- Disk free is ...GB, which is below the required 9999GB.</pre><p>After proving the block, I restored the value:</p><p><strong>YAML</strong></p><pre>min_disk_free_gb: 10</pre><p>Then deployment worked again.</p><h3>Step 13: Gating Canary Promotion</h3><p>Before promotion, SwiftDeploy scrapes /metrics, calculates release health, and asks OPA whether promotion is safe.</p><p>The canary metric collection function:</p><p><strong>PYTHON</strong></p><pre>def collect_canary_metrics(manifest, wait_seconds=None):<br>    if wait_seconds is None:<br>        wait_seconds = int(required(manifest, &quot;policy.canary.window_seconds&quot;))</pre><pre>    print(f&quot;[INFO] Scraping /metrics for {wait_seconds} seconds to evaluate canary safety&quot;)<br>    before = scrape_metrics(manifest)<br>    start = time.time()</pre><pre>    time.sleep(wait_seconds)</pre><pre>    after = scrape_metrics(manifest)<br>    elapsed = time.time() - start</pre><pre>    metrics = calculate_window_metrics(before, after, elapsed)</pre><pre>    return metrics</pre><p>The input sent to OPA:</p><p><strong>PYTHON</strong></p><pre>def canary_policy_input(manifest, action, metrics):<br>    return {<br>        &quot;action&quot;: action,<br>        &quot;metrics&quot;: {<br>            &quot;error_rate&quot;: float(metrics[&quot;error_rate&quot;]),<br>            &quot;p99_latency_seconds&quot;: float(metrics[&quot;p99_latency_seconds&quot;]),<br>            &quot;requests_total&quot;: int(metrics[&quot;requests_total&quot;]),<br>            &quot;errors_total&quot;: int(metrics[&quot;errors_total&quot;]),<br>            &quot;window_seconds&quot;: float(metrics[&quot;window_seconds&quot;]),<br>        },<br>        &quot;thresholds&quot;: {<br>            &quot;max_error_rate&quot;: float(required(manifest, &quot;policy.canary.max_error_rate&quot;)),<br>            &quot;max_p99_latency_seconds&quot;: float(required(manifest, &quot;policy.canary.max_p99_latency_seconds&quot;)),<br>        },<br>    }</pre><p>To promote to canary:</p><p><strong>BASH</strong></p><pre>./swiftdeploy promote canary</pre><p>To confirm canary mode:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8080/</pre><p>Expected header:</p><p><strong>TEXT</strong></p><pre>X-Mode: canary</pre><h3>Step 14: Injecting Chaos and Blocking Unsafe Promotion</h3><p>To test canary safety, I injected slow chaos:</p><p><strong>BASH</strong></p><pre>curl -i -X POST http://localhost:8080/chaos \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;mode&quot;:&quot;slow&quot;,&quot;duration&quot;:2}&#39;</pre><p>Then I generated traffic:</p><p><strong>BASH</strong></p><pre>for i in {1..20}; do<br>  curl -s http://localhost:8080/ &gt; /dev/null<br>  echo &quot;slow request $i&quot;<br>  sleep 1<br>done</pre><p>Then I attempted promotion:</p><p><strong>BASH</strong></p><pre>./swiftdeploy promote stable</pre><p>Because slow chaos increased latency, OPA blocked the promotion.</p><p>Expected output:</p><p><strong>TEXT</strong></p><pre>[FAIL] canary policy: Canary policy blocked this promotion.<br>[POLICY BLOCK] promote stable was blocked by canary policy<br>- P99 latency is ... seconds, which is above the allowed 0.5 seconds.</pre><p>This proved that SwiftDeploy does not promote an unhealthy canary blindly.</p><p><em>.</em></p><p>To recover:</p><p><strong>BASH</strong></p><pre>curl -i -X POST http://localhost:8080/chaos \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;mode&quot;:&quot;recover&quot;}&#39;</pre><p>Then I promoted safely again:</p><p><strong>BASH</strong></p><pre>./swiftdeploy promote stable</pre><h3>Step 15: Adding the Status Dashboard</h3><p>The status command gives a live view of service health and policy compliance.</p><p>Run once:</p><p><strong>BASH</strong></p><pre>./swiftdeploy status --once</pre><p>Run continuously:</p><p><strong>BASH</strong></p><pre>./swiftdeploy status</pre><p>The dashboard displays:</p><p><strong>TEXT</strong></p><pre>SwiftDeploy Live Status<br>======================<br>Time:<br>App URL:<br>Mode:<br>Chaos:</pre><pre>Metrics<br>-------<br>Requests/sec:<br>Window requests:<br>Window errors:<br>Error rate:<br>P99 latency seconds:</pre><pre>Policy Compliance<br>-----------------<br>Infrastructure:<br>Canary:</pre><p>Every status scrape is appended to:</p><p><strong>TEXT</strong></p><pre>history.jsonl</pre><p>This is how the system builds its audit trail.</p><h3>Step 16: Generating the Audit Report</h3><p>The audit command parses history.jsonl and generates:</p><p><strong>TEXT</strong></p><pre>audit_report.md</pre><p>Command:</p><p><strong>BASH</strong></p><pre>./swiftdeploy audit</pre><p>The report includes:</p><ul><li>summary;</li><li>timeline;</li><li>mode changes;</li><li>chaos state changes;</li><li>policy violations.</li></ul><p>The generated report begins like this:</p><p><strong>MARKDOWN</strong></p><pre># SwiftDeploy Audit Report</pre><pre>Generated at: `...`</pre><pre>## Summary</pre><pre>- Total status samples analysed: `...`<br>- Timeline events detected: `...`<br>- Policy violations detected: `...`</pre><pre>## Timeline</pre><pre>| Time | Event | Details |<br>|---|---|---|</pre><pre>## Policy Violations</pre><h3>Step 17: Proving OPA Isolation</h3><p>One of the submission requirements was:</p><blockquote><em>OPA must not be accessible through Nginx.</em></blockquote><p>I tested the Nginx port:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8080/v1/data/swiftdeploy/infrastructure/decision</pre><p>The response was:</p><p><strong>TEXT</strong></p><pre>HTTP/1.1 404 Not Found<br>X-Deployed-By: swiftdeploy</pre><p>That means the request went through Nginx and the app, not OPA.</p><p>Then I tested OPA directly:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8181/health</pre><p>The response was:</p><p><strong>TEXT</strong></p><pre>HTTP/1.1 200 OK<br>{}</pre><p>This proves that OPA is available to the CLI on localhost but not exposed through the public application ingress.</p><h3>Step 18: Final Validation</h3><p>Before submission, I ran:</p><p><strong>BASH</strong></p><pre>./swiftdeploy validate<br>./swiftdeploy status --once<br>./swiftdeploy audit<br>git status</pre><p>The validation confirmed:</p><p><strong>TEXT</strong></p><pre>[PASS] Docker Engine is reachable<br>[PASS] Docker Compose is available<br>[PASS] Docker image exists locally<br>[PASS] generated docker-compose.yml is valid<br>[PASS] Nginx adds X-Deployed-By header<br>[PASS] app service is internal-only; no host port is published<br>[PASS] OPA sidecar service exists in generated docker-compose.yml<br>[PASS] OPA is bound to localhost only<br>[PASS] containers drop Linux capabilities and use no-new-privileges<br>[OK] Validation completed successfully</pre><h3>Step 19: GitHub Commit and Push</h3><p>After confirming the project worked, I committed the changes:</p><p><strong>BASH</strong></p><pre>git add .<br>git commit -m &quot;Complete SwiftDeploy Stage 4B observability policy and audit&quot;</pre><p>Then I pushed to GitHub:</p><p><strong>BASH</strong></p><pre>git push -u origin master</pre><p>or, if using main:</p><p><strong>BASH</strong></p><pre>git branch -M main<br>git push -u origin main</pre><h3>Challenges I Faced</h3><h3>Docker Engine Was Not Running</h3><p>At one point, Docker commands failed because Docker Desktop was not running.</p><p>The error looked like a Docker API connection failure.</p><p>The fix was to open Docker Desktop and confirm:</p><p><strong>BASH</strong></p><pre>docker version</pre><h3>Python Execution on Windows Git Bash</h3><p>Running:</p><p><strong>BASH</strong></p><pre>./swiftdeploy --help</pre><p>did not work at one point because Python was not found through the script execution path.</p><p>The workaround was:</p><p><strong>BASH</strong></p><pre>python swiftdeploy --help</pre><h3>README Saved as Empty</h3><p>When writing the README with a heredoc, I accidentally created a zero-line file.</p><p>I checked it with:</p><p><strong>BASH</strong></p><pre>wc -l README.md</pre><p>Then recreated it properly using:</p><p><strong>BASH</strong></p><pre>cat &gt; README.md &lt;&lt;&#39;EOF&#39;<br>content here<br>EOF</pre><h3>OPA Needed to Be Isolated</h3><p>The OPA API must not leak through Nginx.</p><p>I verified this by testing:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8080/v1/data/swiftdeploy/infrastructure/decision</pre><p>and:</p><p><strong>BASH</strong></p><pre>curl -i http://localhost:8181/health</pre><p>The first returned a normal Nginx/app 404.</p><p>The second returned OPA health.</p><h3>What I Learned</h3><p>This project helped me understand that DevOps is not just about starting containers.</p><p>A good deployment workflow should include:</p><ul><li>repeatable configuration;</li><li>automatic validation;</li><li>secure container networking;</li><li>reverse proxying;</li><li>observability;</li><li>policy-as-code;</li><li>canary release safety;</li><li>controlled failure testing;</li><li>auditability.</li></ul><p>The biggest lesson I learned is:</p><blockquote><em>Deploying is easy. Deploying safely is the real DevOps challenge.</em></blockquote><p>Stage 4A gave SwiftDeploy the deployment engine.</p><p>Stage 4B gave SwiftDeploy the eyes, brain, and memory needed for safer operations.</p><h3>Possible Improvements</h3><p>If I continue improving SwiftDeploy, I would add:</p><ul><li>Prometheus server integration;</li><li>Grafana dashboards;</li><li>GitHub Actions CI pipeline;</li><li>OPA unit tests;</li><li>structured JSON logging;</li><li>automatic rollback after failed canary checks;</li><li>remote cloud deployment;</li><li>authentication for sensitive endpoints;</li><li>Slack or email notifications for failed policy checks.</li></ul><h3>Conclusion</h3><p>SwiftDeploy started as a simple deployment automation tool, but it became a more complete DevOps workflow.</p><p>It now demonstrates:</p><ul><li>Docker packaging;</li><li>Docker Compose orchestration;</li><li>Nginx reverse proxying;</li><li>manifest-driven deployment;</li><li>generated infrastructure files;</li><li>Prometheus-style observability;</li><li>Open Policy Agent policy enforcement;</li><li>infrastructure safety gates;</li><li>canary promotion safety gates;</li><li>chaos testing;</li><li>live status monitoring;</li><li>audit reporting.</li></ul><p>The final result is a tool that does not only ask:</p><blockquote><em>Can I deploy?</em></blockquote><p>It also asks:</p><blockquote><em>Is it safe to deploy?</em></blockquote><p>That is the main value of SwiftDeploy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98304619be7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time HTTP Anomaly Detection Engine with Python, Nginx, Docker, and iptables.]]></title>
            <link>https://medium.com/@soyoyeolayinka35/building-a-real-time-http-anomaly-detection-engine-with-python-nginx-docker-and-iptables-73ca4af387c7?source=rss-ae12ae1d3411------2</link>
            <guid isPermaLink="false">https://medium.com/p/73ca4af387c7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Soyoyeolayinka]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 15:59:41 GMT</pubDate>
            <atom:updated>2026-04-28T15:59:41.493Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a Real-Time HTTP Anomaly Detection Engine with Python, Nginx, Docker, and iptables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6hcjoZS7apPwk5hU3uXLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*qbAU4lXiSDUgqRdkf-VzRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPt70rfLglwl3zRRbatrUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*SUfCkJzrgawTnONvIdsN3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*pTze1E2H6uepRSe5nF3efQ.png" /></figure><p>Introduction</p><p>For my HNG Stage 3 DevOps task, I built a real-time HTTP anomaly-detection and DDoS-response engine. The purpose of the project was to protect a publicly accessible Nextcloud application by monitoring incoming HTTP traffic, learning what normal traffic looks like, detecting unusual traffic spikes, and automatically responding when something becomes suspicious.</p><p>The project runs on an AWS EC2 Linux VPS using Docker Compose. It contains three main services: a pre-built Nextcloud container, an Nginx reverse proxy, and a custom Python detector daemon. Nginx sits in front of Nextcloud and writes every HTTP request into a JSON access log. The detector continuously reads that log, tracks traffic patterns, calculates baselines, sends Slack alerts, blocks abusive IP addresses with iptables, and exposes a live metrics dashboard.</p><p>The live dashboard is available at:<br><a href="http://metrics.dziphomefix.com.ng/">http://metrics.dziphomefix.com.ng</a><br>The GitHub repository is available at:<br><a href="https://github.com/soyoyeyinka/hng-stage3-anomaly-detector">https://github.com/soyoyeyinka/hng-stage3-anomaly-detector</a></p><p>Why This Project Matters:</p><p>Web applications are constantly exposed to different kinds of traffic. Some traffic is normal, such as users browsing pages, logging in, or uploading files. Other traffic can be suspicious, such as one IP address sending hundreds of requests very quickly or a sudden global spike in requests.</p><p>A simple static threshold is not always enough. For example, 20 requests per second may be normal for one application but dangerous for another. That is why this project does not depend on a hardcoded traffic limit. Instead, it learns from recent traffic and compares current behaviour against what the system has recently observed.</p><p>This makes the detector more realistic because it adapts to the application’s traffic pattern instead of assuming that the same threshold works in every situation.</p><p>Overall Architecture</p><p>The architecture has three main containers.</p><p>The first container is **Nginx**, which acts as the reverse proxy. All incoming HTTP traffic goes through Nginx first. Nginx forwards normal traffic to Nextcloud and forwards dashboard traffic to the detector dashboard.</p><p>The second container is **Nextcloud**, using the required pre-built Docker image:<br>kefaslungu/hng-nextcloud</p><p>This image was not modified. All custom work was done in the detector service.</p><p>The third container is the **Python detector daemon**. This service tails the Nginx JSON log file, detects anomalies, sends Slack alerts, writes audit logs, and applies `iptables` blocks when needed.</p><p>The Nginx logs are stored in a named Docker volume:<br>HNG-nginx-logs</p><p>Nginx writes to this volume, while the detector reads it.</p><p>JSON Access Logs</p><p>Instead of writing plain text logs, Nginx was configured to write JSON logs. This makes the logs easier for the detector to parse.</p><p>A sample log entry looks like this:</p><p>json<br>{<br> “source_ip”: “203.0.113.77”,<br> “timestamp”: “2026–04–28T08:30:00+00:00”,<br> “method”: “GET”,<br> “path”: “/ban-test”,<br> “status”: 200,<br> “response_size”: 1024<br>}</p><p>The detector reads each line, extracts the source IP, HTTP method, path, status code, and response size, then updates the traffic metrics.</p><p>How the Sliding Window Works</p><p>The detector uses a sliding window to measure request rates over the last 60 seconds.</p><p>A sliding window is like a moving time frame. Instead of counting requests forever, the detector only looks at recent requests. For example, if a request happened more than 60 seconds ago, it is removed from the current calculation.</p><p>In Python, I used deque for this.</p><p>Conceptually, the structure looks like this:</p><p>python<br>global_window = deque()<br>ip_windows[ip] = deque()</p><p>Whenever a new request arrives, the detector adds the current timestamp to the global window and also to the window for that specific IP address.</p><p>Then it removes old timestamps:</p><p>python<br>while window and window[0] &lt; now — 60:<br> window.popleft()</p><p>The current request rate is then:<br>number of requests in the window / 60 seconds</p><p>This gives two important metrics:<br>global requests per second<br>per-IP requests per second</p><p>This approach avoids using rate-limiting libraries and keeps the logic transparent.</p><p>How the Baseline Learns From Traffic</p><p>The baseline is what the detector considers “normal”.</p><p>The detector maintains a rolling 30-minute history of per-second request counts. Every 60 seconds, it recalculates:<br>mean<br>standard deviation<br>error rate</p><p>The mean tells us the average request rate. The standard deviation tells us how much traffic normally varies. The error rate helps detect situations where an IP is producing too many 4xx or 5xx responses.</p><p>The detector also stores hourly slots. This means it can learn that one hour may naturally have more traffic than another. When the current hour has enough data, the detector prefers that hour’s baseline.</p><p>This is useful because traffic is not always the same throughout the day. A system may be quiet at night and busier in the morning.</p><p>Detection Logic</p><p>The detector checks both per-IP traffic and global traffic.</p><p>An anomaly is detected if either of these conditions is true:<br>z-score &gt; 3.0<br>or:<br>current rate &gt; 5 × baseline mean</p><p>The z-score tells us how far the current traffic rate is from the normal baseline. A high z-score means the traffic is unusually high compared with recent behaviour.</p><p>The multiplier rule is easier to understand. If the current rate exceeds five times the learned mean, the detector treats it as suspicious.</p><p>For example, if the baseline says an IP usually sends:<br>0.08 requests per second<br>But it suddenly sends:<br>0.4 requests per second<br>That is 5x the baseline, so the detector flags it.</p><p>Error Surge Detection</p><p>The detector also watches HTTP errors. If an IP starts producing too many 4xx or 5xx responses, this may indicate scanning, brute forcing, or probing.</p><p>If an IP’s error rate becomes at least three times the baseline error rate, the detector tightens the thresholds.</p><p>Normal thresholds:<br>z-score &gt; 3.0<br>current rate &gt; 5 × baseline mean</p><p>Tightened thresholds:<br>z-score &gt; 2.0<br>current rate &gt; 3 × baseline mean</p><p>This makes the detector more sensitive when an IP is already behaving suspiciously.</p><p>Blocking With iptables</p><p>When the detector identifies a per-IP anomaly, it blocks that IP using iptables.</p><p>For normal Linux traffic, a DROP rule can be added to the INPUT chain. Because this project runs with Docker, container traffic may pass through Docker’s DOCKER-USER chain. Therefore, the detector also supports blocking through DOCKER-USER.</p><p>An example rule looks like this:</p><p>bash<br>sudo iptables -I DOCKER-USER 1 -s 203.0.113.77 -j DROP</p><p>This means traffic from 203.0.113.77 should be dropped before it reaches the application.</p><p>Global anomalies are handled differently. If the entire platform experiences a global spike, the detector sends a Slack alert only. It does not block everyone because that could accidentally deny access to legitimate users.</p><p>Auto-Unban Logic</p><p>The detector does not keep every IP blocked forever. It uses a backoff schedule.</p><p>The ban durations are:<br>1st ban: 10 minutes<br>2nd ban: 30 minutes<br>3rd ban: 2 hours<br>4th ban: permanent</p><p>When a temporary ban expires, the detector removes the iptables rule and sends a Slack notification.</p><p>This gives suspicious IPs a chance to be released while still escalating repeat behaviour.</p><p>Slack Alerts</p><p>Slack alerts are sent for important events:<br>IP banned<br>IP unbanned<br>Global traffic anomaly<br>Detector started</p><p>Each alert includes:<br>condition fired<br>current rate<br>baseline<br>timestamp<br>ban duration</p><p>This makes it easier for an engineer to understand why the detector took action.</p><p>Live Metrics Dashboard</p><p>The dashboard refreshes every 3 seconds and shows:</p><p>text<br>banned IPs<br>global requests per second<br>top 10 source IPs<br>CPU usage<br>memory usage<br>effective mean/stddev<br>uptime<br>hourly baseline slots</p><p>The baseline graph is especially important because it shows how the detector learns over time. In my test, the hourly slots showed different effective mean values, proving that the baseline was not hardcoded.</p><p>Example:</p><p>text<br>06:00 → 0.0033<br>07:00 → 0.0919<br>08:00 → 0.1256<br>Audit Log</p><p>The detector writes structured audit entries for every important event.</p><p>Example format:</p><p>text<br>[timestamp] ACTION ip | condition | rate | baseline | duration</p><p>Example:</p><p>text<br>[2026–04–28T08:36:51+00:00] BAN 203.0.113.77 | per_ip_multiplier rate&gt;5.0x_mean | rate=0.4 | baseline=mean=0.0781,std=0.4350,source=hour_slot_07 | duration=1800 seconds</p><p>The audit log is useful for evidence, debugging, and explaining what happened during an incident.</p><p>Testing the Detector</p><p>To test the system safely, I generated controlled log entries inside my own Nginx container. This allowed me to confirm that the detector could process traffic, trigger Slack alerts, write audit logs, and create `iptables` DROP rules.</p><p>The test evidence included:</p><p>text<br>daemon running<br>Slack ban notification<br>Slack unban notification<br>Slack global anomaly notification<br>iptables DROP rule<br>audit log entries<br>baseline graph</p><p>Challenges Faced</p><p>One challenge was understanding how Docker networking interacts with iptables. Initially, I expected every block to appear only in the INPUT chain. However, Docker-published traffic may pass through the DOCKER-USER chain, so the detector was adjusted to support blocking there too.</p><p>Another challenge was protecting the Slack webhook. Since webhook URLs are secrets, the real config.yaml file was excluded from GitHub using .gitignore. A safe config.example.yaml file was committed instead.</p><p>What I Learnt</p><p>This project helped me understand how security monitoring tools work behind the scenes. I learned how to:</p><p>text<br>configure Nginx JSON logs<br>tail logs in real time<br>track traffic with deque-based sliding windows<br>calculate rolling baselines<br>detect anomalies using z-score and multiplier rules<br>send Slack alerts<br>block IPs with iptables<br>build a live dashboard<br>prepare DevSecOps evidence for submission</p><p>Most importantly, I learned that effective security tooling is not just about blocking traffic. It is about observing behaviour, understanding what is normal, responding carefully, and keeping useful evidence.</p><p>Conclusion</p><p>This project demonstrates a practical DevSecOps approach to real-time traffic monitoring and automated response. The detector watches live HTTP traffic, learns from recent behaviour, detects unusual activity, alerts the team, and blocks suspicious IPs when necessary.</p><p>It is not a replacement for enterprise-grade DDoS protection, but it is a strong learning project that shows how log monitoring, anomaly detection, Slack alerting, dashboards, and Linux firewall rules can work together in a real-world deployment.</p><p>GitHub repository:<br><a href="https://github.com/soyoyeyinka/hng-stage3-anomaly-detector">https://github.com/soyoyeyinka/hng-stage3-anomaly-detector</a></p><p>Live dashboard:<br><a href="http://metrics.dziphomefix.com.ng/">http://metrics.dziphomefix.com.ng</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ca4af387c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>