Hosting and connecting to mongodb database

Docker-compose runs multiple processes (in isolation) on a single machine. Fly.io runs the image produced by a Dockerfile on a single virtual machine. Different models require different approaches.

If you want to stay close to the docker-compose model, you will need to install mongodb in the same dockerfile you use for your application. Assuming you are starting with the Dockerfile that flyctl launch produces which starts with FROM debian:bullseye ..., you would need to follow the instructions here: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-debian/ ; since you won’t be needing sudo, the lines would look like:

RUN apt-get update; apt-get install -y wget gnupg
RUN wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | apt-key add -
RUN echo "deb http://repo.mongodb.org/apt/debian bullseye/mongodb-org/6.0 main" > /etc/apt/sources.list.d/mongodb-org-6.0.list
RUN apt-get update; apt-get install -y mongodb-org

That’s step 1. Next you need to make sure that the mongodb databases are placed on a volume so that they survive restart. These instructions are pretty straightforward: Volumes · Fly Docs. For destination, you will need to match what the value dbPath in /etc/mongod.conf, which is /var/lib/mongodb.

The final step is starting multiple processes. You’ve undoubtedly already got a package.json with a list of “scripts”. Install an npm package called concurrently and add a start script that looks something like this:

"start": "NODE_ENV=production concurrently --kill-others-on-fail npm:client npm:server npm:db"

Add three more scripts, one for the client, server, and db.

This should get you up and running. There are other ways to configure things - for example to put different processes on different virtual machines and connect them via Private Networking · Fly Docs.