When to use this stack
This stack runs a Node.js API built with Express and a MongoDB 7.0 database. MongoDB stores documents as JSON-like objects, which matches the way Express handlers already pass data around, so a small API can be built quickly without a schema migration tool. The compose file starts both services together, enables authentication on the database from the first start, and keeps the database off the public network. It is a good starting point for a JSON API, a prototype, a dashboard backend or a small service that stores flexible records.
Choose it when your data is document-shaped, your access patterns are mostly lookups by key, and your team already knows JavaScript. It also suits projects that need to move quickly and can tolerate MongoDB’s looser schema rules, provided you validate input in Express. Do not choose it for data with many relationships and joins, financial ledgers that need multi-document transactions across many collections, or workloads that need the strict guarantees of a relational database. For those, PostgreSQL is usually the better fit.
The Dockerfile uses node:22-alpine, installs only production dependencies with npm ci, and runs as the non-root node user. Your project must have a package-lock.json, so that the build is reproducible, and an entry file named server.js that listens on the port in the PORT variable. The MongoDB driver reads its connection string from MONGO_URL, which this file builds from the root credentials of the official image.
docker-compose.yml
services:
app:
build: ./app
restart: unless-stopped
depends_on:
mongo:
condition: service_healthy
ports:
- "3000:3000"
environment:
NODE_ENV: production
PORT: 3000
MONGO_URL: mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@mongo:27017/${MONGO_INITDB_DATABASE}?authSource=admin
mongo:
image: mongo:7.0
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
volumes:
- mongo_data:/data/db
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping')"]
interval: 10s
timeout: 5s
retries: 10
start_period: 20s
volumes:
mongo_data:# MongoDB root user, created on the first start of an empty volume
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=CHANGE_ME_mongo_root_password
# Database that the app uses
MONGO_INITDB_DATABASE=appdbDockerfile (app/Dockerfile)
Put this file in ./app next to package.json and server.js. Add a .dockerignore with node_modules and .env.
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"].env
# MongoDB root user, created on the first start of an empty volume
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=CHANGE_ME_mongo_root_password
# Database that the app uses
MONGO_INITDB_DATABASE=appdbStart and verify
docker compose config --quiet
# Build the API image and start both services
docker compose up -d --build
# mongo must show "healthy" before app starts
docker compose ps
# Check the API log for the listening message and any connection errors
docker compose logs --tail=50 app
# Ping the database with the root user from inside the container
docker compose exec mongo mongosh --quiet -u admin -p "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --eval "db.adminCommand('ping')"
# Call the API (replace the path with a route from your server.js)
curl -i http://localhost:3000/Production checklist
- Create a dedicated application user with readWrite rights on the app database, and use it in MONGO_URL instead of the root account.
- Put the API behind HTTPS with a reverse proxy, and set the trust proxy option in Express so rate limits see the real client address.
- Validate request bodies with a schema library such as Zod or Joi, because MongoDB accepts any document shape.
- Keep port 27017 unpublished. If you need remote access, use a VPN or an SSH tunnel.
- Set Helmet and a request body size limit in Express, and never return stack traces to clients.
- Pin the mongo tag to 7.0 and move to a newer minor version only after you test your queries.
- Back up with mongodump on a schedule, copy the backups off the server, and test a restore.
- Give the app container a memory limit so a large query cannot exhaust the host.
Common problems
- Symptom: The app logs “MongoServerError: Authentication failed”. Cause: MONGO_URL uses a different password than the one in .env, or the root user was created with other values after the volume existed. Fix: Make the values match. MONGO_INITDB_* variables apply only to an empty volume; to change the root password later, use the mongosh command with db.changeUserPassword.
- Symptom: The app starts before the database is ready and exits. Cause: The healthcheck has not passed yet. Fix: Keep the depends_on condition, and check that docker compose ps shows mongo as healthy.
- Symptom: “EACCES: permission denied” when writing files in the app. Cause: The app runs as the node user and the folder is owned by root. Fix: Use COPY –chown=node:node or write only to /tmp.
- Symptom: The API responds with 404 for every route. Cause: The server listens on another port, or the route is mounted under a prefix. Fix: Confirm that PORT is 3000 and that the path matches your Express router.
- Symptom: The image build fails at npm ci. Cause: package-lock.json is missing or out of date. Fix: Run npm install locally, commit the lock file and rebuild.
Variations
- Mongo Express admin UI: Add a mongo-express service with a pinned image tag, set its ME_CONFIG_MONGODB_URL to the same URL, and bind its port to 127.0.0.1 only. Do not expose it publicly, because it has no strong login by default.
- Hot reload for development: Use a separate compose.dev.yml with a bind mount of ./app to /app and a command that runs nodemon. Keep the production file unchanged.
- Replica set for transactions: Start mongo with –replSet rs0 and initialize the replica set once. Multi-document transactions need this, even on a single node.
Questions
Which folder holds my Express code?
The app service builds from ./app. Put package.json, package-lock.json and your entry file server.js in that folder. The code is copied into the image at build time.
Why is MongoDB not reachable from my browser?
This stack does not publish the mongo port, which is the safe default. Only the app container connects to mongo:27017 on the internal network. Add a port mapping only for local debugging, and bind it to 127.0.0.1.
Can the app use the root database user?
It works, but it is poor practice. Create a database user with only readWrite rights on your database and use that user in MONGO_URL for production.
Adapt this stack
Load these files into the builder to rename services, change ports, add a cache or a proxy, and generate fresh passwords for the .env.
Open in builderRelated stacks
Laravel + PostgreSQL + Redis
Run a Laravel app on Apache with PostgreSQL 16 and Redis 7 in Docker Compose, with a Dockerfile, queue and cache settings, volumes and a production checklist.
Next.js + PostgreSQL + Redis
Containerize a Next.js app with PostgreSQL 16 and Redis 7 in Docker Compose, using a minimal Dockerfile, healthchecks, named volumes and a production checklist.
Nuxt + PostgreSQL
Run a Nuxt 3 app built with Nitro and PostgreSQL 16 in Docker Compose, with a Node 22 Dockerfile, a database healthcheck, persistent data and a checklist.
Spring Boot + MariaDB
Run a Spring Boot 3 API on Java 21 with MariaDB 11.4 in Docker Compose, with a JRE image, datasource variables, a database healthcheck and a checklist.
Browse more Web & Frameworks stacks or the full library.