Secure Static IP for Python & MongoDB using QGTunnel Shield

Learn how to securely route Python PyMongo database traffic through a QuotaGuard Shield proxy using QGTunnel with zero code changes.

Prerequisites

This example shows how to connect to a MongoDB instance through a QuotaGuard Shield proxy using QGTunnel.

QGTunnel wraps your process and automatically routes all outgoing TCP connections through the Shield proxy — no code changes to your application required.

Requirements
pip install pymongo
curl https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz | tar xz

Environment Variables

1. QUOTAGUARDSHIELD_URL: Your QuotaGuard Shield proxy URL, e.g. https://user:password@us-east-shield-01.quotaguard.com:9294.

Found in your QuotaGuard Dashboard.

2. MONGO_URIA standard mongodb:// or mongodb+srv:// connection string.

Instructions

Run Directly
QUOTAGUARDSHIELD_URL=https://... MONGO_URI=mongodb://... bin/qgtunnel python app.py
Run in Docker
docker build -t qg-shield-python-mongo-qgtunnel-example .
docker run \
  -e QUOTAGUARDSHIELD_URL=https://... \
  -e MONGO_URI=mongodb://... \
  qg-shield-python-mongo-qgtunnel-example

Note : mongodb+srv:// URIs work fine here because QGTunnel intercepts DNS lookups as well as TCP connections.

Code Samples

App.py
import os
import pymongo
from pymongo.errors import ConnectionFailure

MONGO_URI = os.getenv("MONGO_URI")

def test_mongo_connection():
    try:
        client = pymongo.MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)

        client.server_info()  # Will attempt to connect to the server

        print("Connection Success.")
    except ConnectionFailure as e:
        print(f"Connection failed: {e}")

if __name__ == "__main__":
    test_mongo_connection()
Docker File
# Use an official Python runtime as a parent image
FROM python:latest

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install the required Python packages
RUN pip install --no-cache-dir pymongo

# Download and extract QGTunnel software
RUN curl https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz | tar xz

# Command to run when the container starts
CMD ["bin/qgtunnel", "python", "app.py"]