How to Deploy FastAPI with MongoDB on a Secure VPS Using Docker (Beginner Friendly Guide)

Want to deploy your FastAPI backend and MongoDB database to a VPS using Docker? This complete guide walks you through setting up a secure, production-grade environment with commands and explanations.

Views: 28

Setting up a secure and production-ready server for your FastAPI application with MongoDB backend can feel overwhelming. But with the right steps and tools like Docker, you can make your app live on a VPS server in no time.

In this blog post, you’ll learn how to deploy FastAPI and MongoDB on a VPS server using Docker, step by step β€” with exact commands, security considerations, and real-life troubleshooting tips.

Whether you’re building an AI-powered service, SaaS backend, or just want to take your Python app live, this guide has you covered.


🧰 What You’ll Need

Before we dive into the commands and configurations, let’s list out what you need:

  • A Linux-based VPS (e.g. Ubuntu 22.04 on Hostinger, DigitalOcean, etc.)
  • Root SSH access to your VPS
  • Your FastAPI project (preferably Dockerized)
  • Basic knowledge of terminal commands

πŸ›  Step-by-Step: Deploy FastAPI + MongoDB with Docker

1. πŸ” Connect to Your VPS

ssh root@your-server-ip

Update packages:

apt update && apt upgrade -y

Install essentials:

apt install -y git curl ufw unzip

2. 🐳 Install Docker & Docker Compose

curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

# Add your deploy user to Docker group (optional)
usermod -aG docker yourusername

Install Docker Compose:

apt install docker-compose -y

Verify installation:

docker -v
docker-compose -v

3. 🧾 Set Up MongoDB with Docker

Create a dedicated directory:

mkdir -p /opt/mongodb && cd /opt/mongodb

Create a Docker Compose file for MongoDB:

# docker-compose.yml
version: '3'
services:
mongodb:
image: mongo:6.0
container_name: mongodb
ports:
- "27017:27017"
volumes:
- ./data:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: strongpassword

Start MongoDB:

docker-compose up -d

4. πŸ§‘β€πŸ’» Create MongoDB App User

Once MongoDB is running:

docker exec -it mongodb mongosh -u root -p strongpassword

Inside the shell:

use db_name_here
db.createUser({
user: "add_username_here",
pwd: "add_password_here",
roles: [ { role: "readWrite", db: "db_name_here" } ]
})

Now MongoDB is ready with a secured user for your app.


5. πŸš€ Deploy FastAPI via Docker

Assuming your FastAPI app is structured and Dockerized:

Directory structure:

/opt/backend/
β”œβ”€β”€ app/
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ Dockerfile
└── .env

Example .env:

MONGODB_CONNECTION=mongodb://username:user_password@mongodb:27017/db_name?authSource=db_name

Dockerfile Example:

FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Docker Compose:

version: '3'
services:
api:
build: .
container_name: fastapi
ports:
- "8000:8000"
env_file:
- .env
depends_on:
- mongodb

mongodb:
image: mongo:6.0
container_name: mongodb
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: strongpassword
volumes:
- ./mongodb-data:/data/db

Deploy:

docker-compose up -d --build

6. πŸ”₯ Set UFW Firewall Rules

ufw allow OpenSSH
ufw allow 8000
ufw allow 27017
ufw enable

Tip: Only expose MongoDB to localhost in production using internal Docker networks or reverse proxies.


7. πŸ§ͺ Test MongoDB and FastAPI Locally

On your machine:

python
from pymongo import MongoClient
client = MongoClient("mongodb://username:user_password@<your-server-ip>:27017/db_name?authSource=db_name")
print(client.server_info())

If you get connection info, it’s working!


8. πŸ” Make It Production-Ready

  • Use Docker volumes for persistence.
  • Set up daily MongoDB backups (e.g., via cron and mongodump).
  • Configure SSL with Nginx for secure access.
  • Use PM2 or systemd only for static frontends, not Docker containers.

πŸ‘¨β€πŸ« In Simple Terms

Here’s a non-technical breakdown of what we just did:

  • We rented a VPS (virtual private server).
  • Installed Docker, which lets us package our backend app and database as containers.
  • Set up MongoDB securely with usernames and passwords.
  • Deployed our FastAPI Python backend that connects to this database.
  • Made it all live by exposing ports and running the app in the background.

βœ… Final Thoughts

With Docker and proper configuration, deploying FastAPI and MongoDB to a VPS is easier than ever. It gives you full control, strong security, and scalability β€” ideal for SaaS apps, AI tools, internal dashboards, or any web backend.

By following this guide, you can replicate the same setup on your own VPS and deploy your Python apps securely and professionally.


πŸ’‘ Bonus Tips

  • Use .env files to manage secrets and API keys.
  • Consider tools like Watchtower for automatic container updates.
  • Monitor logs using docker logs or external tools like Loki or Datadog.

Leave a Reply