# Connect to MongoDB Atlas

Source: https://prontaro.com/docs/integrations/mongodb-atlas/

Lock MongoDB Atlas Network Access down to a single /32 instead of 0.0.0.0/0 while connecting from serverless apps, CI runners, or laptops.

MongoDB Atlas rejects every connection whose source IP is missing from your project’s Network Access list. Prontaro gives you two TCP options: driver-level SOCKS5 (`socks5h://`) with no CLI installation, or `prontaro forward` for `mongosh`, `mongodump`, and clients that do not support SOCKS5.

## Why an HTTP proxy does not work with MongoDB

MongoDB drivers speak a binary TCP protocol on port `27017`, not HTTP. Setting `HTTP_PROXY` or passing an `http://` proxy URL will not route database connections.

Choose one of two TCP paths:

| Method | Best for | Replica set & SRV handling |
| --- | --- | --- |
| **Driver SOCKS5 (`socks5h://`)** | Node.js (`mongodb`, Mongoose), serverless (Vercel, AWS Lambda), containers | Supports `mongodb+srv://` discovery and automatic primary failover |
| `prontaro forward` | Local dev, `mongosh`, `mongodump`, Prisma, Python `pymongo` | Maps one local TCP port to one Atlas shard host at a time |

## Prerequisites

- A Prontaro account on Dedicated or Pro ([plans](https://prontaro.com/docs/billing/plans.md)). Open [my.prontaro.com/ips](https://my.prontaro.com/ips), choose the location closest to your Atlas cluster, and click **Add IP**.
- A MongoDB Atlas cluster with a database user configured.
- You do not need `prontaro CLI` for Option A (SOCKS5 in your driver) — create proxy credentials in the dashboard. The CLI is only required for Option B (`prontaro forward`).

## Step 1. Allowlist your static IP in MongoDB Atlas

Network Access is configured at the Project level (not Organization). Open your project in MongoDB Atlas and add your IPv4 with a `/32` mask:

**Project → Security → Network Access → Add IP Address**

- `Access List Entry`: `203.0.113.10/32`
- `Comment`: `prontaro-atlas-prod`

Click **Confirm** and wait for the status badge to change from `Pending` to `Active`. Remove any temporary `0.0.0.0/0` rule after verifying connectivity in Step 4.

## Step 2. Create proxy credentials

1. Open **IP addresses** in [my.prontaro.com](https://my.prontaro.com/ips), select your IP, and click **Create proxy credentials** (for example, `atlas-prod`).
2. Copy the `SOCKS5` URL (`socks5h://u_atlas:s3cr3t@<entry>.prontaro.io:1080`).

IP addresses Proxy credentials [Open in dashboard](https://my.prontaro.com/ips)

Leave the **To** destination list unrestricted until Step 5 so you can verify your exit IP with `api.ipify.org` in Step 4.

> **Why socks5h:// matters**
>
> The `h` tells the client to pass the hostname (`cluster0-shard-00-00.example.mongodb.net`) to the Prontaro node for DNS resolution instead of resolving it locally to an IP address. Domain rules like `*.mongodb.net:27017` in Step 5 only match when the node sees the hostname.
>
> The Node.js driver still runs the initial `mongodb+srv://` SRV/TXT lookup locally, while all TCP shard connections go through `socks5h`.

## Step 3. Connect through your static IP

### Option A. Node.js (`mongodb` and Mongoose) over SOCKS5

The official Node.js `mongodb` driver (v6+) supports SOCKS5 via the optional `socks` package and sends hostnames to the proxy (`socks5h`), so `mongodb+srv://` and primary failover work out of the box.

Install the driver with `socks`:

```bash
npm install mongodb socks
```

Create a one-off verification script `atlas-check.mjs` (in a server or Lambda, instantiate `MongoClient` once at startup and do not call `client.close()` on every request):

```js
// atlas-check.mjs — one-off verification script
import { MongoClient } from 'mongodb';

const mongoUri = process.env.MONGODB_URI;
const socksUrl = process.env.PRONTARO_SOCKS_URL;

if (!mongoUri || !socksUrl) {
  throw new Error('Set MONGODB_URI and PRONTARO_SOCKS_URL in your environment');
}

const proxy = new URL(socksUrl);

const client = new MongoClient(mongoUri, {
  proxyHost: proxy.hostname,
  proxyPort: Number(proxy.port),
  proxyUsername: decodeURIComponent(proxy.username),
  proxyPassword: decodeURIComponent(proxy.password),
  maxPoolSize: 10,
  serverSelectionTimeoutMS: 10_000,
});

try {
  await client.connect();
  const result = await client.db('admin').command({ ping: 1 });
  console.log('Atlas ping:', result);
} finally {
  await client.close();
}
```

- **Mongoose:** install `socks` and pass the same `proxyHost`, `proxyPort`, `proxyUsername`, and `proxyPassword` options to `mongoose.connect(mongoUri, { ... })`.
- **Prisma and Python `pymongo`:** neither supports SOCKS5 out of the box — use Option B (`prontaro forward`), or `PySocks` for `pymongo`.

### Option B. Local TCP forwarding with `prontaro forward` (`mongosh`, `mongodump`, Prisma, `pymongo`)

When a tool or driver does not support SOCKS5, bind a local TCP port on `127.0.0.1`:

1. Find one of your Atlas shard hostnames (from **Connect → Drivers** or `dig`):

```bash
dig +short SRV _mongodb._tcp.cluster0.example.mongodb.net
```

1. Start the forwarder to that shard host:

```bash
prontaro forward 27018 cluster0-shard-00-00.example.mongodb.net:27017 --ip 203.0.113.10
```

```text
prontaro forward 27018 cluster0-shard-00-00.example.mongodb.net:27017
  127.0.0.1:27018  →  cluster0-shard-00-00.example.mongodb.net:27017 from your IP 203.0.113.10
```

1. Connect with `mongosh` or `mongodump`. Atlas enforces TLS hostname verification against `*.example.mongodb.net`, so connecting directly to `127.0.0.1:27018` fails validation.

On a workstation with `sudo`, temporarily map `127.0.0.1 cluster0-shard-00-00.example.mongodb.net` in `/etc/hosts`, then connect by hostname:

```bash
mongosh "mongodb://cluster0-shard-00-00.example.mongodb.net:27018/app?tls=true&directConnection=true&authSource=admin" \
  --username "$ATLAS_USER"
```

For `mongodump`, pass the same URI via `--uri`:

```bash
mongodump --uri="mongodb://${ATLAS_USER}:${ATLAS_PASS}@cluster0-shard-00-00.example.mongodb.net:27018/app?tls=true&directConnection=true&authSource=admin"
```

> **Remember to clean up /etc/hosts**
>
> Editing `/etc/hosts` requires `sudo`/`root` privileges (which may be unavailable in non-root containers or restricted CI runners). Remove the `127.0.0.1 cluster0-shard-00-00.example.mongodb.net` line once your session ends so direct connections do not break later.

## Step 4. Verify the exit IP and Atlas connection

First confirm the SOCKS5 route exits from your dedicated IPv4:

```
 export PRONTARO_SOCKS_URL="socks5h://u_atlas:s3cr3t@<entry>.prontaro.io:1080"
curl -fsS --proxy "$PRONTARO_SOCKS_URL"
203.0.113.10
```

Then run the Atlas ping script:

```
 export MONGODB_URI="mongodb+srv://app_user:db_pass@cluster0.example.mongodb.net/app?retryWrites=true&w=majority"
Atlas ping: { ok: 1 }
```

Once `ping` succeeds, delete any temporary `0.0.0.0/0` entry from Atlas **Network Access**.

## Step 5. Lock down allowed targets (recommended)

Now restrict your proxy credentials to MongoDB Atlas hosts on port `27017`:

1. Open **IP addresses → Proxy credentials** in [my.prontaro.com](https://my.prontaro.com/ips), select `atlas-prod`, and switch to **Access**.
2. Add `*.mongodb.net:27017` under **To** and save.

IP addresses Proxy credentials Access [Open in dashboard](https://my.prontaro.com/ips)

## Limits and notes

- **Single-host forwarding and primary failover.** One `prontaro forward` targets one shard (`directConnection=true`). If Atlas elects a new primary, writes fail until you re-forward it. Use driver SOCKS5 in production.
- **Keep serverless pools small.** Set `maxPoolSize` to `5–10` and reuse `MongoClient` across invocations to stay within your [concurrent connection limit](https://prontaro.com/docs/billing/limits.md).
- **Match regions.** Place your Prontaro IP near your Atlas cluster to keep latency low when your app runs many small queries.
- **BGP failover keeps your IP unchanged.** [BGP failover](https://prontaro.com/docs/outbound/failover.md) moves your `/32` automatically without changing the Atlas allowlist, and drivers with `retryWrites=true` reconnect on their own.

## Common errors

| Error | Cause | Fix |
| --- | --- | --- |
| `MongoServerSelectionError: Server selection timed out` | Dedicated IP is still `Pending` in Atlas Network Access, or wrong IP was entered. | Confirm `<your-IP>/32` is `Active` under **Project → Security → Network Access**. |
| `Hostname/IP does not match certificate's altnames` | Connected `mongosh` to `127.0.0.1:27018` over `prontaro forward` without matching TLS SNI. | Map the shard hostname to `127.0.0.1` in `/etc/hosts` for the session, or switch to driver SOCKS5. |
| Proxy blocks Atlas after Step 5 | Client resolved DNS locally (`socks5://` without `h`) instead of passing the hostname. | Switch to `socks5h://` and verify `*.mongodb.net:27017` is in the **To** list. |

For `407`, `403`, and general proxy issues, see [error codes](https://prontaro.com/docs/cli/errors.md) and [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md).

## Next steps

- [Static IP for Vercel](https://prontaro.com/docs/integrations/vercel.md) — configure outbound proxy routing for Vercel Functions.
- [Static IP for AWS Lambda](https://prontaro.com/docs/integrations/aws-lambda.md) — connect from Lambda to allowlisted services without a NAT Gateway.
- [Local port forwarding (`prontaro forward`)](https://prontaro.com/docs/outbound/forward.md) — full reference for outbound TCP forwarding and TLS verification.
- [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md) — proxy credentials, target allowlists, and password rotation.
