Backend API Issue: Special Characters in MongoDB URI


Every DevOps journey has its hiccups—here’s one I ran into while deploying my backend API.
The Problem
My FastAPI backend needed to connect to MongoDB using a URI like this:
mongodb+srv://username:password@cluster.mongodb.net/mydb?retryWrites=true&w=majority
But this URI has special characters like &
, which caused issues during deployment via CircleCI. When injecting the URI into the systemd
service file using awk
or sed
, the special characters were getting misinterpreted—so the backend failed to connect.
What Was Happening
Originally, I tried writing the MongoDB URI directly into the service file during deployment. This looked something like:
ExecStart=/usr/bin/env MONGODB_URI=mongodb+srv://...&w=majority uvicorn main:app
But shell tools like awk
and sed
didn’t play nice with the &
, breaking or corrupting the string.
The Fix
Environment File to the Rescue.
Instead of embedding the URI directly, I created a separate file for environment variables:
Step 1: Create an environment file
# /opt/resume-api/api.env
MONGODB_URI="mongodb+srv://...&w=majority"
Step 2: Reference it in the systemd service file
EnvironmentFile=/opt/resume-api/api.env
ExecStart=/usr/bin/env uvicorn main:app --host 0.0.0.0 --port 8000
This way, systemd
loads the environment variables safely from the file.
💡 Why This Works
It avoids shell parsing issues—no more fighting with escaping special characters.
It’s cleaner and more secure—you can
.gitignore
the file and even manage it via secrets.
Result
The backend now connects to MongoDB without a hitch, and deployments via CircleCI run smoothly every time.
Subscribe to my newsletter
Read articles from Enoch directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Enoch
Enoch
I have a passion for automating and optimizing cloud infrastructure. I have experience working with various cloud platforms, including AWS, Azure, and Google Cloud. My goal is to help companies achieve scalable, reliable, and secure cloud environments that drive business success.