MongoDB Alternative
Not every project uses a relational database. This page shows what changes in your Compose file if you use MongoDB instead of PostgreSQL — and, just as important, what does not change.
What Stays the Same
The web and api services from the last page do not care what database engine sits behind api, as long as api knows how to talk to it. The Compose ideas are identical:
- The database still runs as its own service, using an official image.
- The database still needs a named volume, or its data disappears with the container.
apistill reaches it by service name, over the network Compose builds automatically.
What Changes: The db Service
db:
image: mongo:7
environment:
- MONGO_INITDB_ROOT_USERNAME=appuser
- MONGO_INITDB_ROOT_PASSWORD=secret
volumes:
- db-data:/data/dbCompare this against the PostgreSQL version from the last page:
| PostgreSQL | MongoDB | |
|---|---|---|
| Image | postgres:16-alpine | mongo:7 |
| Username/password variables | POSTGRES_USER, POSTGRES_PASSWORD | MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD |
| Also creates a named database | POSTGRES_DB | No direct equivalent — databases are created on first use |
| Where data is stored inside the container | /var/lib/postgresql/data | /data/db |
| Connection string style | postgresql://user:pass@db:5432/dbname | mongodb://user:pass@db:27017 |
Each official image documents its own environment variables and data folder. When you reach for a different database image in the future, check its Docker Hub page for these two things first — they are almost always what differs.
What Changes: The api Service
api would swap its database driver — the pg package used for PostgreSQL — for a MongoDB driver like mongodb or mongoose. Its queries would be rewritten in MongoDB’s style instead of SQL. That is an application-code change, not a Docker change, so it is outside the scope of this guide.
Why This Matters
The lesson here is not “learn MongoDB.” It is that Compose’s role stays the same regardless of which database you pick — define the service, give it a named volume, let other services reach it by name. Once you understand this pattern with PostgreSQL, adapting it to MongoDB, Redis, or anything else is mostly copying the same shape with different details.
Quick Check
- Can you name the two Postgres environment variables and their Mongo equivalents?
- Do you understand why the data folder path differs between the two images?
- Can you explain why swapping databases does not change how
apiandwebfinddbby name?
Next → Health Checks & Restart