Skip to Content
DocsDockerMulti-containerMongoDB Alternative

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.
  • api still reaches it by service name, over the network Compose builds automatically.

What Changes: The db Service

compose.yaml
db: image: mongo:7 environment: - MONGO_INITDB_ROOT_USERNAME=appuser - MONGO_INITDB_ROOT_PASSWORD=secret volumes: - db-data:/data/db

Compare this against the PostgreSQL version from the last page:

PostgreSQLMongoDB
Imagepostgres:16-alpinemongo:7
Username/password variablesPOSTGRES_USER, POSTGRES_PASSWORDMONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD
Also creates a named databasePOSTGRES_DBNo direct equivalent — databases are created on first use
Where data is stored inside the container/var/lib/postgresql/data/data/db
Connection string stylepostgresql://user:pass@db:5432/dbnamemongodb://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 api and web find db by name?

Next → Health Checks & Restart

docker compose mongodb, mongodb vs postgresql docker, docker compose mongo volume, mongo docker environment variables

Last updated on